I am coding the game checkers in C using the Ncurses library and I have all the pieces stored in a matrix, g.board, and when looking for possible moves I need to make sure the program doesn't try and access an element outside of the matrix, because segmentation faults. I have a solution, but it feels rather crude and I have the feeling there is a more elegant way to do this, but I can't find or think of it.
int x
and int y
refer the x and y location in that matrix that I want to look for possible moves around. char ck
just tells me if the piece is a king a color, the normal colors can only move in one direction. g.board[y][x].possible
just is bool variable in the structure that tells me if it's a possible move.
void checkPossible(int y, int x, char ck);
{
bool left = false, right = false, top = false, bottem = false;
// Dertimes if a tile is out of bounds
if (y != 0)
{
top = true;
}
if (y != 8)
{
bottem = true;
}
if (x != 0)
}
left = true;
}
if (x != 8)
{
right = true;
{
// Sets g.board.possible to true if possible move
if ((top == true && left == true) && (ck == 'k' || ck == 'w'))
{
g.board[y - 1][x - 1].possible = true;
}
if ((top == true && right == true) && (ck == 'k' || ck == 'w'))
{
g.board[y - 1][x + 1].possible = true;
}
if ((bottem == true && left == true) && (ck == 'k' || ck == 'r'))
{
g.board[y + 1][x - 1].possible = true;
}
if ((bottem == true && right == true) && (ck == 'k' || ck == 'r'))
{
g.board[y + 1][x + 1].possible = true;
}
}
As far as I know it works, I haven't tested it much, but it feels crude. I apologize for any mistakes or less than optimal coding, I am rather new to this.