简体   繁体   中英

Index is outside the array bounds in a while loop

I have a question concerning this piece of code that I'm writing. The purpose of this code should be like the game Reversi or Othello. So, you have a playing board and every time you click, you can make a new circle. If a player has a circle in between two circles of the other player, the circle changes color. This is how you make points. For example: red = r and blue = b, empty = 0. The board is as follows: rb 0. Now, it is reds turn and red does this rb r. This makes the blue circle change color to red. So the board now says rrr, scoring red an extra point, while blue loses one.
It should check this for the whole line, but it doesn't do this. I get an error saying the index is outside the array bounds. If you need more code, I would be happy to provide you. Thanks.

public void makeMoveArray(int x, int y, int a, int b, int color)
    {
        boardArray[x, y] = color;
        while (boardArray[x + a, y + b] != turn)
        {
            boardArray[x + a, y + b] = color;
            x += a;
            y += b;
        }
    }

    public void makeMove(int x, int y, int a)
    {
        if (lockedIn(x, y, 0, 1)) { this.makeMoveArray(x, y, 0, 1, a); }
        if (lockedIn(x, y, 1, 0)) { this.makeMoveArray(x, y, 1, 0, a); }
        if (lockedIn(x, y, 1, 1)) { this.makeMoveArray(x, y, 1, 1, a); }
        if (lockedIn(x, y, -1, 0)) { this.makeMoveArray(x, y, -1, 0, a); }
        if (lockedIn(x, y, 0, -1)) { this.makeMoveArray(x, y, 0, -1, a); }
        if (lockedIn(x, y, -1, -1)) { this.makeMoveArray(x, y, -1, -1, a); }
        if (lockedIn(x, y, 1, -1)) { this.makeMoveArray(x, y, 1, -1, a); }
        if (lockedIn(x, y, -1, 1)) { this.makeMoveArray(x, y, -1, 1, a); }

        panel1.Refresh();
    }

You keep increasing the indexes without checking the array borders. You should add this condition to your while loop:

while (x + a >= 0 &&
       x + a < boardArray.GetLength(0) &&
       y + b >= 0 &&
       y + b < boardArray.GetLength(1) &&
       boardArray[x + a, y + b] != turn)

{
    boardArray[x + a, y + b] = color;
    x += a;
    y += b;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM