Currently I am on 'Game of Fifteen' part of pset3, and I am having problem with my implementation of the function move
.
The function move
calls a function legalMove
which in turn calls another function searchTile
.
Perhaps a look at the code snippets will make things clearer:
move
function:
bool move(int tile)
{
// TODO
bool result = false;
int tileX = 0;
int tileY = 0;
int emptyX = 0;
int emptyY = 0;
if(legalMove(tile, tileX, tileY, emptyX, emptyY))
{
board[tileY][tileX] = 0;
board[emptyY][emptyX] = tile;
result = true;
}
return result;
}
legalMove
function:
bool legalMove (int tile, int tileX, int tileY, int emptyX, int emptyY)
{
bool result = false;
if(searchTile(tile, tileX, tileY))
{
if(board[tileY-1][tileX] == 0)
{
result = true;
emptyY = tileY-1;
emptyX = tileX;
}
else if ( board[tileY][tileX-1] == 0)
{
result = true;
emptyY = tileY;
emptyX = tileX-1;
}
else if (board[tileY+1][tileX] == 0)
{
result = true;
emptyY = tileY+1;
emptyX = tileX;
}
else if (board[tileY][tileX+1] == 0)
{
result = true;
emptyY = tileY;
emptyX = tileX+1;
}
}
return result;
}
and lastly, the searchTile
function:
bool searchTile(int tile, int tileX, int tileY)
{
bool result = false;
for (int y = 0; y<d; y++)
{
for (int x = 0; x<d; x++)
{
if(board[y][x]==tile)
{
result = true;
tileX=x;
tileY=y;
break;
}
}
}
return result;
}
The problem that I am facing is that the variables that I have passed as arguments in functions, gets modified as I desired, but for some reason, as soon as the function's execution end, the variable are initialized to 0.
Below are the images of GDB for the program:
Here, it can be seen, under "Local variables" that the values if tileX
and tileY
have been changed as required. The current running function is searchTile
.
Here, it can be seen, under "Local variables" that the values if tileX
and tileY
remains 2
and 1
respectively as the function returns it's result
But as soon as the program exits the function searchTile
the values of tileX
and tileY
gets changed to 0
I would really appreciate any help.
Regards,
Uzair.