gpt4 book ai didi

java - 生命游戏振荡器和宇宙飞船不工作

转载 作者:行者123 更新时间:2023-12-01 19:28:24 24 4
gpt4 key购买 nike

嗨,我目前正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com