I have an issue with my code in Game of Fifteen. I get "illegal move" when I try to swap the tiles, even if it's a "legal" tile. I tried everything but I really don't understand what's wrong. Does anyone have a hint? Thank you!! Here is my code for the move fonction:
bool move(int tile)
{
int blank;
int tile_move;
for (int i = 0; i < d; i++)
{
for (int j = 0; j < d; j++)
{
if (board[i][j] == 0)
{
blank = board[i][j];
}
else if (board[i][j] == tile)
{
tile_move = board[i][j];
if (board[i-1][j] == blank)
{
blank = tile_move;
tile_move = 0;
return true;
}
else if (board[i+1][j] == blank)
{
blank = tile_move;
tile_move = 0;
return true;
}
else if (board[i][j-1] == blank)
{
blank = tile_move;
tile_move = 0;
return true;
}
else if (board[i][j+1] == blank)
{
blank = tile_move;
tile_move = 0;
return true;
}
}
}
}
return false;
}
And here is my code for the other functions, in case the problem is there:
void init(void)
{
// Compute highest number of the array
int total = d*d;
// iterate over the grid
// for each row
for (int i = 1; i <= d; i++)
{
// for each column
for (int j = 1; j <= d; j++)
{
// Compute the value of that case
board [i][j] = ((total) - j);
}
// compute the number starting the next row
total = (d*d) - (i*d);
}
// if even d, swap 1 and 2
if ((d*d)%2 == 0)
{
board[d][d-2] = 1;
board[d][d-1] = 2;
}
}
/**
* Prints the board in its current state.
*/
void draw(void)
{
// iterate over grid
// for each row
for (int i = 1; i <= d; i++)
{
// for each column
for (int j = 1; j <= d; j++)
{
// print an undescore for empty space
if (board[i][j] == 0)
{
printf(" _");
}
// print the board in its current state
else
{
printf ("%3i", board [i][j]);
}
}
// print a new line
printf ("\n");
}
}
/**
* If tile borders empty space, moves tile and returns true, else
* returns false.
*/
bool move(int tile)
{
int blank;
int tile_move;
for (int i = 0; i < d; i++)
{
for (int j = 0; j < d; j++)
{
if (board[i][j] == 0)
{
blank = board[i][j];
}
else if (board[i][j] == tile)
{
tile_move = board[i][j];
if (board[i-1][j] == blank)
{
blank = tile_move;
tile_move = 0;
return true;
}
else if (board[i+1][j] == blank)
{
blank = tile_move;
tile_move = 0;
return true;
}
else if (board[i][j-1] == blank)
{
blank = tile_move;
tile_move = 0;
return true;
}
else if (board[i][j+1] == blank)
{
blank = tile_move;
tile_move = 0;
return true;
}
}
}
}
return false;
}
/**
* Returns true if game is won (i.e., board is in winning
configuration),
* else false.
*/
bool won(void)
{
int n = 1;
for (int i = 0; i < d; i++)
{
for (int j = 0; j < d; j++)
{
if (board[i][j] == 0)
n = 0;
if (board[i][j] != n)
return false;
n++;
}
}
return true;
}