I've created a a function that will move a tile that a user specifies within the game board.
The game board can be from 3*3 up to 9*9 and is filled with values 1 to d - 1. This function is called within another function that keeps track of "space" array and the 2d "board"array.
This function works however, I feel that I might be using too many constants? How can I make this better?
/**
* If tile borders empty space, moves tile and returns true, else
* returns false.
*
* @param int tile The tile the user wants to move
* @param int[] space Space keeps track of where the space is on the board
* @return bool
*/
bool move(int tile, int space[])
{
//check the tile to the left of the space tile so we can swap the space tile with the tile the user wanted
if ( board[ space[0] ][ space[1] + 1 ] == tile ) {
board[ space[0] ][ space[1] + 1 ] = 0;
board[ space[0] ][ space[1] ] = tile;
space[1]++;
return true;
//check the tile to the right of the space tile so we can swap the space tile with the tile the user selected
}else if ( board[ space[0] ][ space[1] - 1] == tile ) {
board[ space[0] ][ space[1] - 1 ] = 0;
board[ space[0] ][space[1] ] = tile;
space[1]--;
return true;
//check the tile to the top of the space tile so we can swap the space tile with the tile the user selected
}else if ( board[ space[0] + 1 ][ space[1] ] == tile ) {
board[ space[0] + 1 ][ space[1] ] = 0;
board[ space[0] ][space[1] ] = tile;
space[0]++;
return true;
//check the tile to the bottom of the space tile so we can swap the space tile with the tile the user selected
}else if ( board[ space[0] - 1 ][ space[1] ] == tile ) {
board[ space[0] - 1 ][ space[1] ] = 0;
board[ space[0] ][space[1] ] = tile;
space[0]--;
return true;
} else {
//the tile does not border the space tile
return false;
}
}
board
? How do you know you aren't reading past the array bounds ofboard
when you do something likeboard[space[0]+1][space[1]]
? \$\endgroup\$