代码之家  ›  专栏  ›  技术社区  ›  Joseph

如何移动二维阵列中的空白空间?

  •  -1
  • Joseph  · 技术社区  · 3 年前

    我正在做一个滑块益智游戏,我不确定如何在数组中移动一个“空白”。谜题应该是这样的,但随机的。每种方法都有一个先决条件,指示它是否可以朝某个方向移动。

    - 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() {
          
       }
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   anqit    3 年前

    下面是一个如何实现的示例 right() ,其他的方法也一样。正如你的评论所暗示的那样,我假设这一举动的合法性已经得到证实。

    /*
    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
    }