Just in case, I'll put the code of the other functions, but they, like, are successfully tested.
void init(void)
{
int value = d*d - 1, c;
for(int i = 0; i < d; i++)
{
for(int j = 0; j < d; j++)
{
board[i][j] = value;
value--;
}
}
if(d % 2 == 0)
{
c = board[d - 1][d - 2];
board[d - 1][d - 2] = board[d - 1][d - 3];
board[d - 1][d - 3] = c;
}
}
/**
* 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] == 0)
{
printf(" _ ");
}
else
{
printf("%2i ", board[i][j]);
}
}
printf("\n");
}
}
/**
* If tile borders empty space, moves tile and returns true, else
* returns false.
*/
bool move(int tile)
{
int c;
for(int i = 0; i < d; i++)
{
for(int j = 0; j < d; j++)
{
if(board[i][j] == 0)
{
y = i;
x = j;
}
}
}
for(int i = 0; i < d; i++)
{
for(int j = 0; j < d; j++)
{
if(board[i][j] == tile)
{
if(abs((i + j) - (x + y)) == 1)
{
c = board[i][j];
board[i][j] = board[y][x];
board[y][x] = c;
return true;
}
}
}
}
return false;
}
Yes, I have a small bug in the move() function. But I think that it's even funny, although a bit chitty because I can sometimes change the values as it were through restrictive fields. Nevertheless, it passes the test, and if the player does not know about this bug, then everything works as it should.
I use 0 to indicate an empty field, so I came up with a function that would go up to d * d - 1 in ascending order, and then become zero on the last field, which should be empty.
bool won(void)
{
int counter = 1;
for(int i = 0; i < d; i++)
{
for(int j = 0; j < d; j++)
{
int index = counter % d*d;
if(board[i][j] != index)
{
return false;
}
counter++;
}
}
return true;
}
For this, I used the modulo operation. What do I suppose happens inside the function: it will check the numbers in ascending order from 1, 2, 3 ... d * d - 1, 0. But, as practice showed, this did not work.
What am I doing wrong?