gpt4 book ai didi

java - Java 中的二维数组未正确更改

转载 作者:行者123 更新时间:2023-11-29 04:59:37 25 4
gpt4 key购买 nike

在我正在从事的 Game Of Life 项目中,我有一个二维字节数组。该数组代表一个游戏板。问题是当我尝试访问数组时,它返回全零。但是,在我设置单元格的函数中,更改保存得很好。

这是类:

public class Game {
int boardW;
int boardH;
Board board;
public Game(int bW) {
boardW = bW;
boardH = bW;
this.board = new Board(boardH, boardW);
}

private byte updateCell(int x, int y) {
byte neighbors = 0;
// Loop through 8 neighbors and count them
for (byte offset_y = -1; offset_y < 2; offset_y++) {
for (byte offset_x = -1; offset_x < 2; offset_x++) {
// Make sure we don't check our current cell
if (offset_x != 0 || offset_y != 0) {
byte newY = (byte) (y + offset_y);
byte newX = (byte) (x + offset_x);
// Roll over edge of board
if (y + offset_y < 0) {
newY = (byte) (boardH - 1);
}
else if (y + offset_y >= boardH) {
newY = 0;
}
if (x + offset_x < 0) {
newX = (byte) (boardW - 1);
}
if (x + offset_x >= boardW) {
newX = 0;
}
neighbors += this.board.getState(newX, newY);
}
}
}
if (neighbors < 2) {return 0;}
if (neighbors > 3) {return 0;}
if (neighbors == 3) {return 1;}
return this.board.getState(x, y);
}

public Board gameTick() {
Board nextTick = new Board(boardH, boardW);
// Go through next iteration of cells
for (int h = 0; h < boardH; h++) {
for (int w = 0; w < boardW; w++) {
nextTick.setState(w, h, updateCell(w, h));
}
}
return nextTick;
}

public Board getBoard() {

return this.board;
}

public void toggleCell(int x, int y, byte state) {
this.board.setState(x, y, state);
}
}

class Board {
private final byte[][] board;
final int height;
final int width;

public Board(int h, int w) {
width = w;
height = h;
board = new byte[height][width];
}

public void setState(int x, int y, byte state) {
board[y][x] = state;
}

public byte getState(int x, int y) {
return board[y][x];
}

public byte[][] getData() {
return board;
}

public void setData(byte[][] newBoard) {
for (int x = 0; x<newBoard.length; x++) {
for (int y = 0; y<newBoard.length; y++) {
setState(x, y, newBoard[y][x]);
}
}
}
}

这是怎么回事?

编辑:事实证明这是访问板的代码中的另一个问题,我已经解决了。感谢大家的帮助。

最佳答案

完全改变代码的设计。有一个包装类 Board,它封装(和隐藏)里面的二维数组(如果它必须是一个数组的话)。

public class Board {
private final byte[][] board;

public Board(int height, int width) {
board = new byte[height][width];
}

public void setState(int x, int y, byte state) {
board[y][x] = state;
}

public byte getState(int x, int y) {
return board[y][x];
}
}

然后创建 Board 类的实例并仅通过该实例访问状态。

因此,您可以安全地访问您的数据,并且您的设计可以在未来进行修改。你是例如免费开始添加有用的方法,例如

boolean isRowEmpty(int x)
boolean isColumnEmpty(int y)
void resetRow(int x)
void resetColumn(int y)
void reset()

所有这些都将在 Board 类的实例上很好地调用。您不会直接从业务逻辑代码访问数组,这是一种令人讨厌的做法。

关于java - Java 中的二维数组未正确更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32527901/

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