I am building a little Minesweeper program at the moment. I initiate the playing field with a 2D array made of cells. When I initiate this array, all entry are null. How do I initiate it correctly?
public Cell[,] _playField;
...
public void GeneratePlayField(PlayField playField)
{
_playField = new Cell[XSize, YSize];
foreach (Cell cell in playField._playField)
{
if (playField._random.NextDouble() <= playField.FillAmount)
{
cell.IsMine = true;
}
}
}
...
internal class Cell
{
public int Neighbors;
public bool IsMine;
public Cell(int neighbors, bool isMine)
{
Neighbors = neighbors;
IsMine = isMine;
}
}
Multidimensional arrays are a little bit tricky. You can initialize them with 2 for loops and GetLength(dimension):
int YSize = 30, XSize = 10;
Cell[,] numbers = new Cell[YSize, XSize];
for (int row = 0; row < numbers.GetLength(0); row++)
for (int col = 0; row < numbers.GetLength(1); row++)
numbers[row, col] = new Cell();
Typically [row,col] is used (instead of [col,row]), so the elements of a line are in succession in the memory.