- Home /
how to fix Index Out Of Range Exception
I made this code for the king in a chess game. Whenever the king is on the very right or left side of the board, I get the "IndexOutOfRangeException" error. Anyone know how to fix?
using UnityEngine;
using System.Collections;
public class King : Chessman
{
public override bool[,] PossibleMove()
{
bool[,] r = new bool[8, 8];
Chessman c;
int i, j;
//Top Side
i = CurrentX - 1;
j = CurrentY + 1;
if (CurrentY != 7)
{
for (int k = 0; k < 3; k++)
{
if (i >= 0 || i < 8)
{
c = BoardManager.Instance.Chessmans[i, j];
if (c == null)
r[i, j] = true;
else if (isWhite != c.isWhite)
r[i, j] = true;
}
i++;
}
}
//Down Side
i = CurrentX - 1;
j = CurrentY - 1;
if (CurrentY != 0)
{
for (int k = 0; k < 3; k++)
{
if (i >= 0 || i < 8)
{
c = BoardManager.Instance.Chessmans[i, j];
if (c == null)
r[i, j] = true;
else if (isWhite != c.isWhite)
r[i, j] = true;
}
i++;
}
}
//Midlle Left
if (CurrentX != 0)
{
c = BoardManager.Instance.Chessmans[CurrentX - 1, CurrentY];
if (c == null)
r[CurrentX - 1, CurrentY] = true;
else if (isWhite != c.isWhite)
r[CurrentX - 1, CurrentY] = true;
}
//Midlle Right
if (CurrentX != 7)
{
c = BoardManager.Instance.Chessmans[CurrentX + 1, CurrentY];
if (c == null)
r[CurrentX + 1, CurrentY] = true;
else if (isWhite != c.isWhite)
r[CurrentX + 1, CurrentY] = true;
}
return r;
}
}
doublemax is right about your error.
$$anonymous$$eep in $$anonymous$$d that a king is not allowed to move himself into check so he would be checkmate. Same is true for any other piece. You are not allowed to move away a piece that would put your king in check. This complicates the calculations significantly ^^. Also don't forget the requirements for "castling" ^^.
ps: using a boolean array with 64 values is a bit "strange". I would prefer to return a simple list of a custom class / struct that holds the coordinates of possible end points.
public struct ChessPos
{
public int x;
public int y;
}
It also would be useful to be able to create a temporary board for the various check you have to perform. So using a singleton can be a problem here.
Your answer
Follow this Question
Related Questions
Help with basic AI script 1 Answer
Why is this error coming up in my code ? 1 Answer
Distribute terrain in zones 3 Answers
Help please guys thank you so much! 1 Answer