I’m working on a Slider puzzle game and I’m not sure how I would go about moving a “blank” around the array. The puzzle would something like this but randomized. Each method has a prerequisite indicating if it can move a certain direction or not.
- 2 3 4 5 6 7 8 9
// Modifies the puzzle by moving the blank up // pre: canMoveUp() public void up() { } // Modifies the puzzle by moving the blank down // pre: canMoveDown() public void down() { } // Modifies the puzzle by moving the blank left // pre: canMoveLeft() public void left() { } // Modifies the puzzle by moving the blank right // pre: canMoveRight() public void right() { }
Advertisement
Answer
Here is an example of how you could implement right()
, the rest of the methods would follow very similarly. I am assuming, as your comments imply, that the legality of the move has already been verified.
/* represent the board in a 2-dimensional array with the following coordinate system x ---> y | / */ int x, y = 0; // keeping track of the blank position int[][] board = ... // initialize the board as needed (sequentially? randomly?), assume -1 represents the blank space public void right() { // move the blank in the positive x direction // get the value currently in the position that the blank must move to, as it will need to be swapped int tmp = board[x + 1][y]; board[x + 1][y] = -1; // move the blank here board[x][y] = tmp; // complete the swap x = x + 1; // the new x position of the blank needs to be updated }