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

反应-生命游戏-根据用户点击的元素更新2D数组中特定元素的状态

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

    我仍在学习和编写约翰康威的生活游戏。我已经创建了一个游戏板的游戏中使用的二维阵列状态。我把这个二维数组存储在我的 App.js . 我还有两个功能部件, Gameboard.js Square.js 接收道具和创建游戏板。

    创建表并将道具传递给 方块字.js 让它知道哪些方块应该突出显示,哪些不应该突出显示。换句话说,它让每个方块都知道用户是否点击了它,以及它是否在生命意义的游戏中“活着”。

    方块字.js aliveCallback ,将单击的特定正方形的X和Y坐标传递回 . 应用程序.js alive

    什么时候? 活着的 调用时,我需要更新2D数组的状态,以便将特定的正方形(它是X和Y坐标,例如[0,0]或[0,1]等…)设置为存储在状态中的布尔值。然后,这个布尔值可以传递给 游戏板.js 作为 isAlive . 然后游戏板通过了 价值 有条件渲染,告诉每个正方形亮显为浅蓝色。

    check out the Codesandbox and see the structure of the project . 这也有助于提到,我正在遵循的建议,所以海报给了我 this post .

    在阅读了React文档之后,使用 immutability-helper 而且它是 update 功能。这是我已经采取的方法,但我似乎不能正确地更新状态的具体广场点击使用它的X和Y坐标。

    活着的

    以下是我尝试过的:

    alive = (x, y) => {
        console.log(x, y);
    
        const data = this.state.board;
        const ySquare = y;
        const xSquare = x;
        console.log("X square is : " + xSquare);
        console.log("Y square is : " + ySquare);
    
        const updateData = update(data, {
          xSquare: {$set: this.setState({ alive: !this.state.alive })}
        });
    
      }
    

    更新 然后试着为那个特定的正方形设置为真。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Henry Woody    6 年前

    我认为问题是你有一个状态变量 alive 在应用程序上,每个细胞的生命状态都很混乱。

    update from 'immutability-helper' 因为我不熟悉它,但是我的解决方案中的逻辑非常简单。

    这里是 App.alive

    alive = (x, y) => {
      console.log(x, y);
    
      const data = this.state.board;
      const ySquare = y;
      const xSquare = x;
      console.log("X square is : " + xSquare);
      console.log("Y square is : " + ySquare);
    
      const newData = data.map((row, y) => {
        return y === ySquare ? (
          row.map((cell, x) => x === xSquare ? 1 : cell)
        ) : (
          row
        )
      })
    
      this.setState({ board: newData });
    }
    

    newData 如果当前单元格的坐标匹配 xSquare, ySquare 它将单元格的值设置为 1 ,否则保持不变。

    makeCellAlive 更清楚的是,它是一种做某事的方法。

    编辑

    row.map((cell, x) => x === xSquare ? 1 : cell)
    

    row.map((cell, x) => x === xSquare ? (cell + 1) % 2 : cell)
    

    看起来是个很酷的应用。