0

I tried to change the code but it still won't swap tiles and blank_tile this is my code

bool move(int tile) {

int blanktile_X, blanktile_Y;
for(int i = 0; i < d; i++)
{
    for(int j = 0; j < d; j++)
    {
        if(board[i][j] == 0)
        {
            blanktile_X = i;
            blanktile_Y = j;
        }
        if((board[i][j] == tile) && 
            ((i + 1 == blanktile_X && j == blanktile_Y) ||
            (i - 1 == blanktile_X && j == blanktile_Y) ||
            (i == blanktile_X && j + 1 == blanktile_Y) ||
            (i == blanktile_X && j - 1 == blanktile_Y)))
            {
                int swap = tile;
                tile = board[blanktile_X][blanktile_Y];
                board[blanktile_X][blanktile_Y] = swap;
                return true;
            }

    }
}

return false;

}

1

It looks like your problem is in your decision to put everything inside the same nested for loops. Your swap depends on setting blanktile_X and blanktile_Y, the location of the blank tile. If the blank tile is in a position that follows the position of tile, then one or both of the coordinates of the blank tile (X or Y) will not yet have been set and will still be 0 when the swap is attempted, causing the swap to fail.

You need to set the position of the blank tile before starting the nested for loops for the swap. Or, you could establish the positions of both the blank tile and tile in the loop and then attempt the swap outside/after the for loops. That will assure that the positions of both will be known. In fact, it should be possible to establish the position coordinates with a single loop, since you're only looking for the coordinates, but I'll leave the 'how' for you to think about. ;-)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .