To implement the move() function I divided it into three functions, one to find the tile inputted by the user, one to check if the move is legal, and one to actually move the tiles.
At first it looked like it worked but it is allowing invalid moves, on the first move it works only valid moves can be made. But after the 2nd move it allows some invalid moves such as:
8 7 6 8 7 6 8 7 6 8 7 6
5 4 3 -> 5 4 3 -> _ 4 3 -> 3 4 _
2 1 _ 2 _ 1 2 5 1 2 5 1
Taking the last picture as an example, it does not allow moves: 8, 7
But allows everything else: 6, 3, 4, 2, 5, 1
Here's the code: Finds the inputted tile
// declare tile location variables
int tile_locr;
int tile_locc;
// searches for location of inputted tile
int tile_search(int tile)
{
for (int i = 0; i < d; i++)
{
for (int j = 0; j < d; j++)
{
if (board[i][j] == tile)
{
tile_locr = i;
tile_locc = j;
}
}
}
return 1;
}
Checks if the move is legal
// checks is move is legal
bool islegal(void)
{
// check top
if (board[tile_locr - 1][tile_locc] == 0)
{
return true;
}
// check bottom
else if (board[tile_locr + 1][tile_locc] == 0)
{
return true;
}
//check right
if (board[tile_locr][tile_locc + 1] == 0)
{
return true;
}
// check left
else if (board[tile_locr][tile_locc - 1] == 0)
{
return true;
}
else
{
return false;
}
}
Moves the tile
blank_locr and blank_locc have been declared as d - 1 in the init() function
bool move(int tile)
{
tile_search(tile);
if (islegal())
{
// back up vars
int temp = board[tile_locr][tile_locc];
int temp_r = tile_locr;
int temp_c = tile_locc;
//move the blank
board[tile_locr][tile_locc] = board[blank_locr][blank_locc];
// move tile
board[blank_locr][blank_locc] = temp;
// update location of blank
blank_locr = temp_r;
blank_locc = temp_c;
return true;
}
else
{
return false;
}
}
I can't figure out what's wrong, any help is appreciated! :)