I'm making a sliding tile puzzle using C++, and have code that exchanges the blank tile for one adjacent to it.
Using user input, the program takes the input and puts it in the function which uses a switch
statement to determine which direction the user wants to switch, then preforms the switch if applicable.
I was simply wondering if it's better coding to have 4 separate functions, one for each direction like this:
void puzzle::swapLeft()
{
if (X == 0)
{
return;
}
temp = grid[X - 1][Y]; //swapping positions
grid[X - 1][Y] = grid[X][Y];
grid[X][Y] = temp;
X -= 1;
return
}
Or is my current code with its switch
statement?
Note: X
is where the empty tile's X position is and Y is empty tile's Y position.
void puzzle::swap(int d) //d where 1 = up, 2 = left, 3 = down, 4 = right
{
int temp = 0;
switch (d) //determines direction
{
case 1://swaps empty with upward tile
if (Y == 0) //checks if null is on upper border, if true returns to prevent error
{
return;
}
temp = grid[X][Y - 1]; //swapping positions
grid[X][Y - 1] = grid[X][Y];
grid[X][Y] = temp;
Y -= 1;//null tile's new position
break;
case 2://swaps empty with left tile
if (X == 0)//checks if null is on left border, if true returns to prevent error
{
return;
}
temp = grid[X - 1][Y]; //swapping positions
grid[X - 1][Y] = grid[X][Y];
grid[X][Y] = temp;
X -= 1;
break;
case 3: //swaps empty with downward tile
if (Y == 3) //checks if null is on bottom border, if true returns to prevent error
{
return;
}
temp = grid[X][Y + 1]; //swapping positions
grid[X][Y + 1] = grid[X][Y];
grid[X][Y] = temp;
Y += 1; //null tile's new position
break;
case 4: //swaps null with rightward tile
if (X == 3) //checks if null is on right border, if true returns to prevent error
{
return;
}
temp = grid[X + 1][Y]; //swapping positions
grid[X + 1][Y] = grid[X][Y];
grid[X][Y] = temp;
X += 1; //empty tile's new position
break;
}
return;
}