嗨,我目前正在用javafx canvas开发生活游戏。但是,我的算法似乎有一个错误。静物在起作用,而其余部分则没有,像滑翔机这样的模式并没有按照应有的方式运转。我使用的是2d int数组,ALIVE为1,DEAD为0。这是我的算法:

    private void checkRules() {
        int[][] newBoard = board;
        int amountOfAliveNeighbours;
        for (int y = 0; y < board.length; y++) {
            for (int x = 0; x < board[y].length; x++) {
                amountOfAliveNeighbours = getAmountOfAliveNeighbours(x, y);
                if (board[y][x] == ALIVE) {
                    if (amountOfAliveNeighbours == 2 || amountOfAliveNeighbours == 3) {
                        newBoard[y][x] = ALIVE;
                    }else{
                        newBoard[y][x] = DEAD;
                    }
                } else if (board[y][x] == DEAD){
                    if (amountOfAliveNeighbours == 3) {
                        newBoard[y][x] = ALIVE;
                    }else{
                        newBoard[y][x] = DEAD;
                    }
                }
            }
        }
        board = newBoard;
    }

    private int getAmountOfAliveNeighbours(int x, int y) {
        int neighbours = 0;
        // top left
        if (x - 1 >= 0 && y - 1 >= 0) {
            if (board[y - 1][x - 1] == ALIVE)
                neighbours++;
        }
        // top center
        if (y - 1 >= 0) {
            if (board[y - 1][x] == ALIVE)
                neighbours++;
        }
        // top right
        if (x + 1 < board[0].length && y - 1 >= 0) {
            if (board[y - 1][x + 1] == ALIVE)
                neighbours++;
        }
        // middle left
        if (x - 1 >= 0) {
            if (board[y][x - 1] == ALIVE)
                neighbours++;
        }
        // middle right
        if (x + 1 < board[0].length) {
            if (board[y][x + 1] == ALIVE)
                neighbours++;
        }
        // bottom left
        if (x - 1 >= 0 && y + 1 < board.length) {
            if (board[y + 1][x - 1] == ALIVE)
                neighbours++;
        }
        // bottom center
        if (y + 1 < board.length) {
            if (board[y + 1][x] == ALIVE)
                neighbours++;
        }
        // bottom right
        if (x + 1 < board[0].length && y + 1 < board.length) {
            if (board[y + 1][x + 1] == ALIVE)
                neighbours++;
        }
        return neighbours;
    }

最佳答案

这样为临时板分配内存:

int[][] newBoard = new int[board.length][board[0].length];


我建议重构邻居的计算:

  private int getAmountOfAliveNeighbours(int x, int y) {
    int neighbours = 0;
    for (int dx = -1; dx <= 1; dx++) {
      for (int dy = -1; dy <= 1; dy++) {
        if ((dx !=0 || dy != 0) && isAlive(x + dx, y + dy)) {
          neighbours++;
        }
      }
    }
    return neighbours;
  }

  private boolean isAlive(int x, int y) {
    return (x >= 0) && (x < board.length) &&
        (y >= 0) && (y < board[0].length) &&
        (board[x][y] == ALIVE);
  }

关于java - 生活游戏振荡器和宇宙飞船无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60654408/

10-10 16:53