【发布时间】:2016-06-08 02:21:23
【问题描述】:
首先我想拉一个随机的棋盘,以便游戏在渲染后立即开始运行,但对于这种情况,我有一个预先分配的布局用于调试。这三个正方形排列将从水平切换到垂直并无限切换。
getInitialState: function() {
var state = {
rows: 5,
cols: 5,
generation: 0,
active: false
};
var cellMatrix = [];
var cellRow = [];
/* for (var i = 0; i < state.rows; i++) {
for (var j = 0; j < state.cols; j++) {
cellRow.push(Math.round(Math.random()));
}
cellMatrix.push(cellRow);
cellRow = [];
}*/
cellMatrix = [
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
];
state.board = cellMatrix;
return state;
},
到目前为止非常简单。我使用一个按钮渲染页面,该按钮允许我执行 this.gameStep,它模拟了另一代。更新的值被分配给 newBoard 并且 state.board 在循环之后被更新。问题是 state.board 每次循环时都会更新到当前的板状态(在这种情况下为 25 次)。如果我要插入一个 (newBoard == this.state.board) 布尔值,它会在循环的每次迭代中返回 true。
gameStep: function() {
var newBoard = this.state.board;
for (var i = 0; i < this.state.rows; i++) {
for (var j = 0; j < this.state.cols; j++) {
console.log(this.state.board);
var check = this.checkNeighborSum(i, j, this.state.board);
if (check == 3) {
newBoard[i][j] = 1;
} else if (check == 4) {
newBoard[i][j] = this.state.board[i][j];
} else {
newBoard[i][j] = 0;
}
}
}
this.setState({
board: newBoard
});
},
作为参考,checkNeighborSum 只是实际的数学函数。 3 是保证生命,4 只有当它已经活着(也就是复制状态)时才是生命,其他任何东西都是死的。
checkNeighborSum: function(x, y, board) { // x is row index, y is column index
var xMinus = x - 1;
var xPlus = x + 1;
var yMinus = y - 1;
var yPlus = y + 1;
if (x === 0) {
xMinus = this.state.cols - 1;
}
if (x === this.state.cols - 1) {
xPlus = 0;
}
if (y === 0) {
yMinus = this.state.rows - 1;
}
if (y === this.state.rows - 1) {
yPlus = 0;
}
return (board[xMinus][yMinus] +
board[xMinus][y] +
board[xMinus][yPlus] +
board[x][yMinus] +
board[x][y] +
board[x][yPlus] +
board[xPlus][yMinus] +
board[xPlus][y] +
board[xPlus][yPlus]);
},
如果您希望看到整个页面,请链接:link
【问题讨论】:
标签: javascript reactjs