# Game of Fifteen Not Swapping Tiles and Allowing Illegal Movies

I have two issues with my code. First, while the code correctly moves the underscore to the new space, it does not move the tile to the space where the underscore once was. So I end up with a bunch of underscores each time I select a new tile. Secondly, my code seems to be allowing me to move tiles even when there is no open space. Here is what I have so far:

``````void init(void)
{
int tile = (d*d) - 1;
//Check if d is odd
if (d%2)
{
for (int i = 0; i<d; i++)
{
for (int j = 0; j<d; j++)
{
if (tile > 0)
{
board[i][j] = tile;
tile-=1;
}
}
}
}
else
{
for (int i = 0; i<d; i++)
{
for (int j = 0; j<d; j++)
{
if (tile>2 || tile==0)
{
board[i][j] = tile;
tile-=1;
}
else if (tile==2)
{
board[i][j] = 1;
tile-=1;
}
else if (tile==1)
{
board[i][j] = 2;
tile-=1;
}
}
}
}
}

/**
* 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 (d==i+1 && d==j+1)
if (board[i][j]==0)
{
printf(" _\n");
}
else if (d==j+1)
{
printf("%2i\n", board[i][j]);
}
else
{
printf("%2i ", board[i][j]);
}
}
}
}

/**
* If tile borders empty space, moves tile and returns true, else
* returns false.
*/
bool move(int tile)
{
int blank_tile;
for (int i = 0; i<d; i++)
{
for (int j = 0; j<d; j++)
{
if (board[i][j]==0)
{
blank_tile = board[i][j];
break;
}
}
}

for (int i = 0; i<d; i++)
{
for (int j = 0; j<d; j++)
{
if (board[i][j]==tile)
{
if (board[i][j+1]==blank_tile)
{
board[i][j] = blank_tile;
board[i][j+1] = tile;
return true;
}
else if (board[i][j-1]==blank_tile)
{
board[i][j] = blank_tile;
board[i][j-1] = tile;
return true;
}
else if (board[i+1][j]==blank_tile)
{
board[i][j] = blank_tile;
board[i+1][j] = tile;
return true;
}
else if (board[i-1][j]==blank_tile)
{
board[i][j] = blank_tile;
board[i-1][j] = tile;
return true;
}
return false;
}
}
}
return false;
}

/**
* Returns true if game is won (i.e., board is in winning configuration),
* else false.
*/
bool won(void)
{
int tile = 1;
for (int i = 0; i<d-1; i++)
{
for (int j = 0; j<d-1; j++)
{
if (board[i][j]==tile)
{
tile+=1;
if (tile==(d*d)-1)
{
return true;
}
}
return false;
}
}
return false;
}
``````