I've managed to get a thumbs up from check50 in the Game of Fifteen, but I have no idea why. It's really eating at me and I refuse to go forward until I understand it.
Here's my less than eloquent function:
bool won(void)
{
int i,j;
int y = d*d;
int x;
if (board[d-1][d-1] != 0)
{
return false;
}
for (i = 0, x = 1; i < d && x < y-1; i++)
{
for (j = 0; j < d; j++)
{
if (board[i][j] == x)
{
x++;
}
else if (board[i][j])
{
return false;
}
}
}
return true;
}
My issue is with the else if statement, which seems to be needed in order to appease the check50 gods. When completely removed, the very first call to won() seems to return true and the game ends immediately. When changed to just "else" rather than "else if", the final check returns false and the game expects another move.
Running the program through gdb I saw that board[i][j] contains 0 on that final check, so I thought it might have something to do with returning true or false. I changed it to "else if (0)" and the game ends at "ftw" without ever running. I tried "else if (1)" and the game runs, but the function returns false.
It was just dumb luck that I had the "else if (board[i][j])" there when I compiled it; to be honest, I never meant to test it that way. I just forgot to delete that snippet of code. So why does it only work with that bit of code? Obviously I'm missing something. If someone can point me in the right direction I'd greatly appreciate it. I want to make sure I understand WHY.
Thank ya!