【问题标题】:New to Reactjs, Building a Game of Life, but the old board is updating with the new boardReactjs 新手,构建人生游戏,但旧板正在更新为新板
【发布时间】: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


    【解决方案1】:

    gameStep 中,您正在更改this.state.board 本身。我建议使用不可变结构,例如不可变的.js。但是,由于您才刚刚开始,您可以尝试使用 Object.assign 将状态克隆到 newState -

    var newBoard = Object.assign({}, this.state.board);

    在将board 添加到newBoard 时,这应该与board 重复。

    【讨论】:

      【解决方案2】:

      也许检查一下:How do I correctly clone a JavaScript object?

      var newBoard = this.state.board 只是创建对同一变量的另一个引用。它不会克隆您的对象

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-09
        • 1970-01-01
        • 2021-05-17
        • 2021-09-21
        • 2011-07-12
        • 1970-01-01
        相关资源
        最近更新 更多