0

I have finished my move function and things. Still, the problem here is that sometimes the function works (either move and swap blank tiles correctly/ return false when appropriate) but sometimes it just add more blank spaces, especially when I try moving the tiles that are 2 tiles away from the blank (Adjacent tiles work fine, return false correctly)

Here is my move code:

bool move(int tile)
{

    if (tile <= 0 || tile > d*d-1)
    {
        return false;
    }
    //find and return tile position
    for(int i = 0; i < d; i++)
    {
        for(int j = 0; j < d; j++)
        {
            //find and return tile position
            if (board[i][j] == tile)
            {
                int left = i -1;
                int down = j -1;
                int right = i +1;
                int up = j +1;
                //check and swap blank cell to the left
                if (left >= 0 && board[left][j] == 0)
                {
                    board[i][j] = 0; 
                    board[left][j] = tile;
                    return true;
                }
                //check and swap blank cell to the right
                else if (right <= d-1 && board[right][j] == 0)
                {
                    board[i][j] = 0;
                    board[right][j] = tile;
                    return true;
                }
                //check and swap blank cell up
                else if (up >= 0 && board[i][up] == 0)
                {
                    board[i][j] = 0; 
                    board[i][up] = tile;
                    return true;
                }
                else if (down <= d-1 && board[i][down] == 0)
                {
                    board[i][j] = 0; 
                    board[i][down] = tile;
                    return true;
                }
                else
                {
                    return false;   
                }
            }
        }
    }
    return false;
}

Thank you for any help you can offer.

1

If i is row and j is column (as evidenced by board[i][j]), then your "directional" variables are slightly off. left (previous column) would be at board position board[i][j-1]; down (next row) at board position board[i+1][j]; &tc. You get the idea.

| improve this answer | |
  • This is it! I just keep thinking of the arrays in terms of "width" and "height" but not "rows" and "columns" and that cause confusion! – Ha Tran Jun 18 '17 at 14:21

You must log in to answer this question.

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