0
   bool move(int tile)
{
for(int row=0;row<d;row++)
{
    for(col=0;col<d;col++)
    {    
        if(board[row][col]==tile)
        { 
            if(board[row+1][col]==0 || board[row-1][col]==0 || board[row][col+1]==0 || board[row][col-1]==0)
            {
                if(board[row+1][col]==0)
                {
                board[row+1][col]=tile;
                }
                else if(board[row-1][col]==0)
                {
                    board[row-1][col]=tile;
                }
                else if(board[row][col+1]==0)
                {
                    board[row][col+1]=tile;
                }
                else
                {
                    board[row][col-1]=tile;
                }

                board[row][col]=0;

                return true;
            }

        } 

    }

}    
// TODO
return false;

}

1

This looks like the same problem I had to start with.

As well as making sure that tile is next to the 0 tile, you also need to make sure that you are not telling it to move off the edge of the board. The board is a 9x9 array, so if you are not using the whole of this, e.g. with a 3x3 or 4x4 board, you can spill off the end, using row + 1 for example. I added an additional clause to my conditional statements regarding the relative position to d which solved it.

I also think you could lose the nested if statement to streamline!

| improve this answer | |

You must log in to answer this question.

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