代码之家  ›  专栏  ›  技术社区  ›  Nick Kinlen

反应-遍历嵌套数组并检查数组中索引的值

  •  0
  • Nick Kinlen  · 技术社区  · 6 年前

    我正在学习React,并在康威的生活游戏项目中工作。这个项目基本上已经完成了,但是我在实现游戏逻辑方面遇到了困难。我有一个表示游戏板的二维数组。二维数组中的每个索引表示板中的一个正方形。我已经把它设置好了,以便功能部件能够处理板的显示,以及哪些方块在生命意义的游戏中是“活的”。在我的App.js中,我有一个 componentDidMount timer 每隔几秒钟创建一个新板的函数。

    componentDidUpdate 要在每次更改棋盘时检查棋盘并应用生活游戏规则,请执行以下操作:

    任何有少于两个邻居的活细胞都会死亡,就好像人口不足一样。

    任何有两三个邻居的活细胞都会延续到下一代。

    任何有三个以上邻居的活细胞都会死亡,就好像人口过剩一样。

    任何只有三个活邻居的死细胞都会变成活细胞,就像是通过繁殖一样。

    我的逻辑是 组件更新 运行我将循环通过二维数组(游戏板)和检查相邻的方块,看看它们是否已填充。然后,应用游戏规则,并确定特定的方块是生是死还是再生。然后在每一个方块被检查并确定它是活的还是死后,我将用新游戏板的值更新状态。那么 再次运行,创建下一轮,然后 组件更新 将再次评估下一次对板的更改。

    这不管用。这是密码 组件更新

    // Should apply Game of Life rules and decide with squares are alive/dead every time the board is updated
      componentDidUpdate = (prevProps, prevState) => {
        //console.log('PrevState is : ' + prevProps, prevState);
        const oldBoard = this.state.board;
        const newBoard = this.state.nextBoard;
    
        console.log('oldBoard ' + oldBoard);
    
    /*    // Checks that board has changed and prevents infinite loop in componentDidUpdate
          for(let x = 0; x < this.state.boardHeight; x++) {
            for(let y = 0; y < this.state.boardWidth; y++) {
              let neighborCount = 0;
              // Game of Life logic pertaining to squares being alive/dead
              neighborCount += oldBoard[x - 1][y - 1];
              neighborCount += oldBoard[x][y - 1];
              neighborCount += oldBoard[x + 1][y - 1];
              neighborCount += oldBoard[x - 1][y];
              neighborCount += oldBoard[x + 1][y];
              neighborCount += oldBoard[x - 1][y + 1];
              neighborCount += oldBoard[x][y + 1];
              neighborCount += oldBoard[x + 1][y + 1];
    
              // If square has 2 live neighbors it stays alive
              if(neighborCount == 2) {
                newBoard[x][y] = oldBoard[x][y];
              }
              // If square has exactly 3 neighbors a new life square is born
              else if (neighborCount == 3) {
                newBoard[x][y] = 1;
              }
              // Is square has more than 3 live neighbors it dies
              else if(neighborCount > 3){
                newBoard[x][y] = 0;
              }
            }
          }
    
          if(newBoard !== oldBoard) {
            // after applying rules set the nextBoard
            this.setState({ board: newBoard });
          }
        */
    
      }
    

    在上面查看整个App.js可能会更容易 CodeSandbox . 我认为我的逻辑是正确的,但是我循环和计算数组值的方式可能是不正确的,或者我使用 组件更新

    1 回复  |  直到 6 年前
        1
  •  0
  •   mindlis    6 年前

    我认为你的问题是 newBoard 新船 完全从状态开始检查

    const oldBoard = prevState.board;
    const newBoard = this.state.board;
    

    在你的 componentDidUpdate 功能。