-1

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;
    }
}
Hale Jan
  • 75
  • 7
  • as additional info i have already tried setting all the cells in the array using a foreach loop but that didnt work. I am also aware that it seems like a simple question that I could just google but I really didnt find any answers for this thats why I asked here. – Hale Jan Aug 14 '21 at 10:54

1 Answers1

2

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.

Michael
  • 1,166
  • 5
  • 4