I am very new to this, so I am at a loss as to why my code isn't working. I am trying to make my move function work in the game of fifteen, and it works as long as I am not going to the left or right over the two or one. I think this has to do with the fact that they are swapped in itit, but I don't know how to make this problem go away! If I move to the left toward a 2 on an even board, I end up with extra underscores.... Here is my init:
void init(void)
{
// Declares variables
int k = (d * d) - 1;
// Iterates across 2D array
for (int i = 0; i < d; i++)
{
for (int j = 0; j < d; j++)
{
board[i][j] = k;
k--;
}
}
if (d % 2 == 0)
{
int swap = board[d-1][d-2];
board[d-1][d-2] = board[d-1][d-3];
board[d-1][d-3] = swap;
}
}
here is my draw:
// Iterates across 2D array
for (int i = 0; i < d; i++)
{
for (int j = 0; j < d; j++)
{
if (board[i][j] == 0)
{
printf ("__\t");
}
else
{
printf ("%2d\t", board[i][j]);
}
}
printf ("\n");
}
and here is my move function:
for (int i = 0; i < d; i++)
{
for (int j = 0; j < d; j++)
{
if (tile == board[i][j])
{
if (i > 0 && board[i - 1][j] == 0)
{
int swap = board[i][j];
board[i][j] = board[i - 1][j];
board[i - 1][j] = swap;
return true;
}
else if (i < d && board[i + 1][j] == 0)
{
int swap = board[i][j];
board[i][j] = board[i + 1][j];
board[i + 1][j] = swap;
return true;
}
else if (j > 0 && board[i][j - 1] == 0)
{
int swap = board[i][j];
board[i][j] = board[i][j - 1];
board[i][j - 1] = swap;
return true;
}
else if (j < d && board[i][j + 1] == 0)
{
int swap = board[i][j];
board[i][j] = board[i][j + 1];
board[i][j + 1] = swap;
return true;
}
}
}
}
return false;