0

I have been changing and trying a bunch of stuff but it won't work. Could any of you see what is wrong with my code? I already have read a lot of answers for the same function but I still can't find the solution for my code. Thanks in advance!

bool move(int tile)
{

    int swap;
    // search tile which must be moved
    for (int i = 0; i < d; i++)
    {
        for (int j = 0; j < d; j++)
        {
            // swap tile with blank tile
            if (tile == board[i][j])
            {
                // Prevents moving a tile above the top of the 2D-array
                if (i > 0)
                {
                    if (board[i - 1][j] == 0)
                    {
                        swap = tile;
                        board[i][j] = board[i - 1][j];
                        board[i - 1][j] = swap;
                        return true;  
                    }
                }

                // Prevents moving a tile left of the 2D-array
                else if (j > 0)
                {
                    if (board[i][j - 1] == 0)
                    {
                        swap = tile;
                        board[i][j] = board[i][j - 1];
                        board[i][j - 1] = swap;
                        return true; 
                    }
                }

                // Prevents moving a tile under the 2D-array
                else if (i < d)
                {
                    if (board[i + 1][j] == 0)
                    {
                        swap = tile;
                        board[i][j] = board[i + 1][j];
                        board[i + 1][j] = swap;
                        return true;  
                    }
                }

                // Prevents moving a tile right of the 2D-array
                else if (j < d)
                {
                    if (board[i][j + 1] == 0)
                    {
                        swap = tile;
                        board[i][j] = board[i][j + 1];
                        board[i][j + 1] = swap;
                        return true;  
                    }
                }
            }
        }
    }
    return false;
}    

1 Answer 1

1

It's the else ifs. Let's take a 3x3 board, first move, tile 1. It gets here if (tile == board[i][j]) when i = 2 and j = 1. if (i > 0) evaluates to true, so it goes into the code block. It doesn't do the swap (because board[i - 1][j] holds tile 4). Then what? Control returns to the j-loop. Since you want to test each of the neighboring tiles, as long as they are within the board, you would use if instead of else if.

1
  • Thanks, this worked for some steps!
    – Robinj1
    Commented Mar 10, 2017 at 9:21

You must log in to answer this question.

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