0

Every tile I try to move, it return "Illegal move", I was quite sure the code was right, but I can't find where is the mistake. :( Any tip you can give me is appreciated!

bool move(int tile)
{
int blank_x, blank_y;
int pos_x, pos_y, swap;

if (tile > dmax + 1)
{
    return false;
}

for (int i = 0, j; i < d; i++)
{
    for (j = 0; j < d; j++)
    {
        if (board[i][j] == tile)
        {
            pos_x = i;
            pos_y = j;
        }
        if (board[i][j] == 0)
        {
            blank_x = i;
            blank_y = j;
        }
    }
}

if (pos_x == (blank_x - 1) || pos_x == (blank_x + 1) || pos_y == (blank_y - 1) || pos_y == (blank_y + 1))
{
        swap = board[pos_x][pos_y];
        board[blank_x][blank_y] = swap;
        board[pos_x][pos_y] = 0;
        return true;
}
return false;
}

btw, dmax = d * d - 1.

1

This code is half-right. It does work, but it allows for diagonal swaps. You need to check for the condition where posx = blankx AND posy=blanky.

If you are getting illegal move for valid moves, then you need to check elsewhere. Did you alter the call to move that is in main? Is it possible that you are running an earlier or different build? Maybe the compile failed and you are executing a previous build?

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

2
  • Thanks, I'll add a fix for the corner cases. I found that if I commented this line, the code works again, I can move tiles: if (tile > dmax + 1) { return false; } Any idea why?
    – Carlos C
    Jul 19 '16 at 3:06
  • Oh, never mind, I found the error in the init() function. Thanks for your answer!
    – Carlos C
    Jul 19 '16 at 3:09

You must log in to answer this question.

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