1

I tried to implement a leftward movement in game of 15. I encountered a problem. The program can only call move function once and it doesn't work after that. I use 0 to as the representation for the blank space. I found out the problem was that each time the move function is called, it initializes my variables for storing the blank space back to d - 1 and this is a bug. I've been thinking of solutions and the only one i've come up with is to declare hori and verti as global variables first but I don't know if this is a good way to implement this function. Are there other good ways to do so?

// if legal move, check left position for tile
if (verti - 1 >= 0 && board[hori][verti - 1] == tile)
{
    // swap with left tile
    board[hori][verti] = tile;
    verti = verti - 1;
    board[hori][verti] = 0;
    return true;
}
// if legal move, check right position for tile
else if (verti + 1 <= d - 1 && board[hori][verti + 1] == tile)
{
    // swap with right tile
    board[hori][verti] = tile;
    verti = verti + 1;
    board[hori][verti] = 0;
    return true;
}
5
  • The blank tile is NOT ALWAYS at d - 1, d - 1. Everything you need to know about the move function, you'll probably find it here! – kzidane Nov 12 '14 at 11:32
  • Yes, but my code updates to store the new location of the blank space. I managed to solve this by declaring hori and verti as global variables and then initializing them as d - 1 just after init(). I've updated my code to show the next section. So when completed, it does not have to check all 4 positions for the correct tile. It exits once the correct tile is found. My question is if declaring hori and verti as blank variables is a good stylistic way to do this? – Lucas Nov 12 '14 at 15:54
  • Well, you'll still need to check whether the location of the blank tile lies immediately above, below, on the right, or on the left of the tile to be moved. – kzidane Nov 12 '14 at 16:04
  • Oh I did it differently. I store the position of the blank space and search the surrounding positions for the tile. This way, I don't have to implement a search. – Lucas Nov 12 '14 at 16:19
  • Sure! I think that's a good approach! :) – kzidane Nov 12 '14 at 19:11
2

Declare hori and verti as global variables and initialize them to d - 1 just after init().

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .