java - 生命游戏振荡器和宇宙飞船不工作
问题描述
嗨,我目前正在使用 javafx 画布制作一款生活游戏。但是我的算法似乎有一个错误。静物在起作用,但其余的却没有,像滑翔机这样的图案并没有按照应有的方式移动。我使用 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);
}
推荐阅读
- python - 如何将包含操作的字符串转换为数值
- json - JSON 未从 Discord 消息中解析
- r - 如何在 R 中将“year.month”格式更改为“Year-Month”格式
- php - 多个身份验证防护无法正常工作
- python - ProxyError,尝试在代理后面查询普罗米修斯时
- javascript - 使用反应更改另一个元素的样式
- python - 使用天气预报预测销售额,如何在预测时使用未来的天气数据?
- pine-script - PineScript - 双上下确认点(变量)
- excel - 从 SQL Developer 导出数据只提取一半的查询输出 - 是否有增加这个的偏好?
- ms-access - Microsoft Access 的雪花连接字符串