I have been trying to get the tiles of the move function to switch if any adjacent cells are blank. The initiation and draw functions work fine, I just need to get the move function to make the actual switch instead of giving me "illegal move errors" even though a blank adjacent cell qualifies to be switched. FYI all of this code compiles just fine, only issues are incorrect implementation of the move function.
Here is the code:
// function declarations
void init(void) ;
bool move(int tile) ;
// board, whereby board[i][j] represents row i and column j
int board[MAX][MAX];
// board's dimension
int dimension = 5 ;
int blank = 95;
int main(void)
{
init();
for (int row = 0; row < dimension ; row++)
{
for (int column = 0; column < dimension; column++)
{
if (board[row][column] > 9)
printf("%i ", board[row][column]);
else if (board[row][column] > 0)
printf("%2i ",board[row][column]);
else
printf("%c", blank);
}
printf("\n");
}
// prompt for move
printf("\n");
printf("Tile to move: ");
int tile = GetInt();
// move if possible, else report illegality
if (!move(tile))
{
printf("\nIllegal move.\n");
usleep(500000);
}
}
void init(void)
{
bool even = false;
int size = dimension*dimension ;
if (size % 2 == 0)
{
even = true;
}
for (int row = 0; row < dimension ; row++)// row count
{
for (int column = 0; column < dimension ; column++)// column count
{
board[row][column] = size - 1;
size -- ;
}
}
if (even)
{
board[dimension-1][dimension-2] = 2;
board[dimension-1][dimension-3] = 1;
}
}
bool move(int tile)
{
// TODO
for(int row = 0; row < dimension; row++)
{
for(int column = 0; column < dimension; column++)
{ // the loop to execute the switch should only execute if current x;y coordinates match tile
if (board[row][column] == tile)
{
// if top block is blank ('_' or ACII charachter no 95)
if (board[row-1][column] == blank)
{
// switch blank and tile
board[row-1][column] = tile;
board[row][column] = blank;
return true;
}
// if left block is blank ('_' or ACII charachter no 95)
else if (board[row][column-1] == blank)
{
// switch blank and tile
board[row][column-1] = tile;
board[row][column] = blank;
return true;
}
// if right block is blank ('_' or ACII charachter no 95)
else if (board[row][column+1] == blank)
{
// switch blank and tile
board[row][column+1] = tile;
board[row][column] = blank;
return true;
}
// if bottom block is blank ('_' or ACII charachter no 95)
else if (board[row+1][column] == blank)
{
// switch blank and tile
board[row+1][column] = tile ;
board[row][column] = blank ;
return true ;
}
// in all other cases return false
return false ;
}
}
}
return 0 ;
}