Ich schreibe ein Game of Life Programm in C#. Ich verwende ein 2D-Array von Strukturen. Es scheint, wenn ich die Random-Methode anzeigen, dass der Algorithmus der Nachbarn oder etwas falsch ist. Wenn es Generationen durchläuft, kommen zufällige Zellen "lebendig", wenn sie es nicht sollen. Irgendeine Hilfe?Game of Life Algorithmus Problem
public struct cellDetail
{
public int curGenStatus;
public int nextGenStatus;
public int age;
}
public class Class1
{
static cellDetail[,] Generations(cellDetail[,] cells)
{
int neighbours = 0;
for (int i = 0; i < 40; i++)
for (int j = 0; j < 60; j++)
cells[i, j].nextGenStatus = 0;
for (int row = 0; row < 39; row++)
for (int col = 0; col < 59; col++)
{
neighbours = 0;
if (row > 0 && col > 0)
{
if (cells[row - 1, col - 1].curGenStatus > 0)
neighbours++;
if (cells[row - 1, col].curGenStatus > 0)
neighbours++;
if (cells[row - 1, col + 1].curGenStatus > 0)
neighbours++;
if (cells[row, col - 1].curGenStatus > 0)
neighbours++;
if (cells[row, col + 1].curGenStatus > 0)
neighbours++;
if (cells[row + 1, col - 1].curGenStatus > 0)
neighbours++;
}
if (cells[row + 1, col].curGenStatus > 0)
neighbours++;
if (cells[row + 1, col + 1].curGenStatus > 0)
neighbours++;
if (neighbours < 2)
cells[row, col].nextGenStatus = 0;
if (neighbours > 3)
cells[row, col].nextGenStatus = 0;
if ((neighbours == 2 || neighbours == 3) && cells[row, col].curGenStatus > 0)
cells[row, col].nextGenStatus = 1;
if (neighbours == 3 && cells[row, col].curGenStatus == 0)
cells[row, col].nextGenStatus = 1;
}
for (int i = 0; i < 40; i++)
for (int j = 0; j < 60; j++)
cells[i, j].curGenStatus = cells[i, j].nextGenStatus;
return cells;
}
static void PrintCells(cellDetail[,] cells)
{
for (int row = 0; row < 40; row++)
{
for (int col = 0; col < 60; col++)
{
if (cells[row, col].curGenStatus != 0)
{
cells[row, col].curGenStatus = (char)30;
Console.Write((char)cells[row, col].curGenStatus);
}
else
Console.Write(" ");
}
}
}
public static void Random(int numOfGenerations)
{
cellDetail[,] cells = new cellDetail[40,60];
Random rand = new Random();
for (int row = 0; row < 40; row++)
for (int col = 0; col < 60; col++)
cells[row, col].curGenStatus = rand.Next(0, 2);
for (int i = 0; i < numOfGenerations; i++)
{
Console.ForegroundColor = (ConsoleColor.Green);
Generations(cells);
Console.SetCursorPosition(0, 3);
PrintCells(cells);
}
}
}
Sollte dies ein Hausaufgaben-Tag haben? – Servy
Ich habe nicht genau hinschauend gesucht, um zu sehen, ob es sich um Ihr zugrunde liegendes Problem handelt, aber Sie sollten in kurzer Zeit nicht viele "zufällige" Objekte erstellen. Sie sind standardmäßig mit der aktuellen Zeit versehen. Die kurze Antwort ist nur einmal ein "Random" erstellen und speichern Sie es herum, so dass Sie '.Next' darauf wiederholt aufrufen können. – Servy
Aye, es sollte Hausaufgaben Tag sein. Ich habe es markiert. –