i tried to create the 'Conweys game of life'. So at first i create a empty (null) arrays of tile's. Then i set a list for each neightbour tile to commit it on the creating tile on this place of the array.
private static Tile[,] GenerateGeneration(int rowlenght, int colLenght)
{
Tile[,] newGeneration = new Tile[rowlenght, colLenght]; //Emty array
for (int row = 0; row < rowlenght; row++)
{
for (int column = 0; column < colLenght; column++)
{
List<Tile> tiles = new() //Set neighbourtiles in a list
{
newGeneration[row,CalculateIndexOverOrUnderflow(column - 1,colLenght)], //Left
newGeneration[CalculateIndexOverOrUnderflow(row - 1, rowlenght), CalculateIndexOverOrUnderflow(column - 1, colLenght)], //LeftAbove
newGeneration[CalculateIndexOverOrUnderflow(row - 1, rowlenght), column], //Above
newGeneration[CalculateIndexOverOrUnderflow((row - 1), rowlenght), CalculateIndexOverOrUnderflow((column + 1), colLenght)], //AboveRight
newGeneration[row, CalculateIndexOverOrUnderflow((column + 1), colLenght)], //Right
newGeneration[CalculateIndexOverOrUnderflow((row + 1), rowlenght), CalculateIndexOverOrUnderflow(column + 1, colLenght)], //BelowRight
newGeneration[CalculateIndexOverOrUnderflow((row + 1), rowlenght), column], //Below
newGeneration[CalculateIndexOverOrUnderflow((row + 1), rowlenght), CalculateIndexOverOrUnderflow(column - 1, colLenght)], //BelowLeft
};
newGeneration[row, column] = new Tile(tiles, row, column); //commit the neighbours
}
}
return newGeneration;
}
The 'CalculateIndexOverOrUnderflow' methode sets the index to the upperbound of the array if it's < 0 and vice versa.
So my question is. On running this programm the most of the neighbours ar null. In my opinion all tiles should not be null, because a class is a reference type and I always pass the reference.
I always pass the reference
This's right, but null
is also a reference in a sense, and all your tiles are null on initial. When you do this:
List<Tile> tiles = new() //Set neighbourtiles in a list
{
newGeneration[row, column],
...
}
If newGeneration[row, column]
isn't set at that moment, the tile list will contain a null
value.
The easiest solution is full fill the array with empty tiles first:
for (int row = 0; row < rowlenght; row++)
{
for (int column = 0; column < colLenght; column++)
{
newGeneration[row, column] = new Tile(new Tiles(), row, column);
}
}
Fill the tile list in each tile next:
for (int row = 0; row < rowlenght; row++)
{
for (int column = 0; column < colLenght; column++)
{
var tiles = newGeneration[row, column].Tiles; // Assume the tile list is public
tiles.Add(newGeneration[row,CalculateIndexOverOrUnderflow(column - 1,colLenght)]);
tiles.Add(...);
}
}