1

Keep getting illegal move on following code and can't figure out why it won't swap. I am selecting the tile above the blank in testing.

/**
 * Prints the board in its current state.
 */
void draw(void)
{
for (int i = 0; i < d; i++)
{
    for (int j = 0; j < d; j++)
    {
        if(board[i][j] < 10)
        {
            if(board[i][j] == 0)
            {
                printf(" | %s|", "_");
            }                
            else
            {
                printf(" | %i|", board[i][j]);
            }
        }
        else
        {
            printf(" |%i|", board[i][j]);    
        }
    }
    printf("\n\n");
}
}

/**
* If tile borders empty space, moves tile and returns true, else
* returns false. 
*/
bool move(int tile)
{
if (tile == 0)
{
    return false;
}

for (int i = 0; i < d; i++)
{
    for (int j = 0; j < d; j++)
    {
        if (tile == board[i][j])
        {
            // make move if tile chosen is above blank
            if (i > 0)
            {
                if (board[i - 1][j] == 0)
                {
                    int swap = tile;
                    board[i][j] = board[i - 1][j];
                    board[i - 1][j] = swap;
                    return true;
                }
            }


        }
    }
}


return false;    
}
-1

Here if (board[i - 1][j] == 0) it is testing if the 0 tile is above the one selected. Let's assume 3 in a 3x3 board. 3 is in board[1][2]. It is testing board[0][2].

1
  • Wow, I must have been looking at this too long today.
    – BoBbY
    May 10 '17 at 21:40

You must log in to answer this question.

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