0

I've been attempting to make a ludo game to learn a bit more about C# Unfortunately I have run into a for loop that I can't figure out, it gives me an out of bound error. What I am trying to do in this code is make the board( Which is the 15x15 array) I am assigning all the blank spots on the game board with the value 9, so that I can play with it easily later on.

Quadrant 1 does what it is intended to, but it gives me the "Out of bound" error in Quadrant 2.

// Make the 2D array (Game board)
int[,] GameBoard = new int[15, 15];

// Quadrant 1
for(int Blankspotx1 = 0; Blankspotx1 < 7; Blankspotx1++)
{
    GameBoard[Blankspotx1, 0] = 9;
    int Blankspoty1 = 0;
    for (Blankspoty1 = 0; Blankspoty1 < 7; Blankspoty1++)
    {
        GameBoard[Blankspotx1, Blankspoty1] = 9;
    }
    Blankspoty1 = 0;
}

// Quadrant 2
for (int Blankspotx2 = 10; Blankspotx2 < 16; Blankspotx2++)
{
    GameBoard[Blankspotx2, 0] = 9;

    int Blankspoty2 = 0;
    for (Blankspoty2 = 0; Blankspoty2 < 7; Blankspoty2++)
    {
        GameBoard[Blankspotx2, Blankspoty2] = 9;
    }
    Blankspoty2 = 0;
}
maccettura
  • 10,514
  • 3
  • 28
  • 35
hhh
  • 13
  • 2

2 Answers2

6

for (int Blankspotx2 = 10; Blankspotx2 < 16; Blankspotx2++) should be
for (int Blankspotx2 = 10; Blankspotx2 < 15; Blankspotx2++)

The last index of any zero-based index collection is it's length - 1.

As a rule of thumb, it's always best to use the collection's length-1 instead of hard coding the number, to prevent such mistakes from happening.

For multi-dimensional arrays, use the GetLength(Int32) method to get the length of the specified dimension, so it's either:

for (int Blankspotx2 = 10; Blankspotx2 < GameBoard.GetLength(0); Blankspotx2++)

Or

for (int Blankspotx2 = 10; Blankspotx2 <= GameBoard.GetLength(0)-1; Blankspotx2++)
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
0

Arrays are zero based counted. so you need to get the for loop up to 15 and not to 16. The fifteenth element is the one who is "out of Bounds"

 // Quadrant 2
for (int Blankspotx2 = 10; Blankspotx2 < 15; Blankspotx2++)
{
    GameBoard[Blankspotx2, 0] = 9;

    int Blankspoty2 = 0;
    for (Blankspoty2 = 0; Blankspoty2 < 7; Blankspoty2++)
    {
        GameBoard[Blankspotx2, Blankspoty2] = 9;
    }
   Blankspoty2 = 0;
 }
Matthias Neubert
  • 275
  • 1
  • 5
  • 24