In a Game Of Life project that I'm working on, I have a 2D array of bytes. The array represents a gameboard. The problem is that when I try to access the array, it returns all zeroes. But, in the function where I set a cell, changes save just fine.
Here's the class:
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]);
}
}
}
}
What is going on here?
EDIT: Turns out it was another problem in the code that accessed the board, which I solved. Thanks for all your help guys.