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

React-使用.map函数和new array.fill更新2D数组的状态并用随机数填充它

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

    我正在开发一个johnconway的游戏应用程序,我还在学习React。

    Here is what I have so far App.js 的状态。我在构造器中使用新数组和.fill方法来最初创建电路板的正方形。稍后在 应用程序.js 我有一个名为isSquareAlive的函数,它处理onClick功能,并在用户单击相应的方块时将其更改为不同的颜色(它们在生命意义的游戏中是“活着的”)。

    getRandomNumber 现在我想创建另一个函数,它将在componentDidMount上被调用,这个函数将在用户加载应用程序并调用它时创建一个初始的游戏板 并用1填充2d数组的一些元素(正方形),用0填充其他元素。有1的方块会“活着”,有0的方块不会。

    获取随机数

    这是我的 :

    import React, { Component } from 'react';
    import './App.css';
    import GameBoard from './GameBoard.js';
    import Controls from './Controls.js';
    import update from 'immutability-helper';
    import Info from './Info.js';
    
    class App extends Component {
      constructor(props){
        super(props);
    
        this.state = {
          boardHeight: 50,
          boardWidth: 30,
          iterations: 10,
          reset: false,
          alive: false,
          board: [],
          randomNum: ''
        };
    
        this.state.board = new Array(this.state.boardHeight).fill(new Array(this.state.boardWidth).fill(0));
      }
    
      // Allows user to click button and change size of game board
      selectBoardSize = (width, height) => {
        this.setState({
          boardHeight: height,
          boardWidth: width,
          board: new Array(this.state.boardHeight).fill(new Array(this.state.boardWidth).fill(0))
        });
      }
    
      // Resets game board back to blank when user clicks reset button
      onReset = () => {
        this.setState({ board: new Array(this.state.boardHeight).fill(new Array(this.state.boardWidth).fill(0)) })
      }
    
      // Generates random number
      getRandomNumber = (max) => {
        return Math.floor(Math.random() * Math.floor(max));
      }
    
      /* This is the function I am trying to build and generate a random starting game board with
      componentDidMount = () => {
        // Stores random number 1 or 2
        const number = this.getRandomNumber(2);
        const data = this.state.board;
    
        // This is what I need help on
        const startingBoard = data.map((row, y) => {
                                row.map((ea, x) => {
                                  return 1;
                                })
        })
    
        // After startingBoard is working I can set state with startingBoard
        this.setState({
          board: startingBoard
        });
      }
    */
    
    
      // Called when user clicks on specific square. Changes color of square depending on if it's alive or not
      isSquareAlive = (x, y) => {
        const data = this.state.board;
        const ySquare = y;
        const xSquare = x;
    
        const newData = data.map((row, y) => {
          return y === ySquare ? (
            row.map((cell, x) => x === xSquare ? (cell + 1) % 2 : cell)
          ) : (
            row
          )
        })
    
        this.setState({ board: newData });
    
      }
    
    
    
      render() {
        /*console.log('Random number is : ' + this.state.randomNum);*/
        return (
          <div>
          <div className="game-container">
    
          <GameBoard
            height={this.state.boardHeight}
            width={this.state.boardWidth}
            reset={this.onReset}
            board={this.state.board}
            alive={this.isSquareAlive}
            isAlive={this.state.alive}
          />
    
          <Controls
            selectBoardSize={this.selectBoardSize}
            iterations={this.state.iterations}
            onReset={this.onReset}
          />
    
          </div>
    
          <div className="info-container">
            <Info />
          </div>
          </div>
        );
      }
    }
    
    export default App;
    

    返回1英寸 startingBoard 我只是个笨蛋,想用它来回报什么。

    重申一下:董事会是这样创建的:

    this.state.board = new Array(this.state.boardHeight).fill(new Array(this.state.boardWidth).fill(0));
    

    如何将随机数推入二维数组?

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

    import React, {Component} from 'react';
    
    const createRandomBoard = (height, width) => {
    
      const randomCellValue = () => (Math.random() < 0.5 ? 1 : 0);
    
      // thank you @simonbor on StackOverflow:
      // https://stackoverflow.com/questions/5836833/create-a-array-with-random-values-in-javascript
      const createRow = () => Array.from({length: width}, randomCellValue);
    
      return Array.from({length: height}, createRow);
    };
    
    
    class App extends Component {
      constructor(props){
        super(props);
        const boardHeight = 50;
        const boardWidth = 30;
    
        this.state = {
          boardHeight,
          boardWidth,
          board: createRandomBoard(boardHeight, boardWidth),
        };
      }
    
      render() {
    
        return (
          <div>
    
          </div>
        );
      }
    }
    
    export default App;
    

    https://stackblitz.com/edit/so-gol-answer?file=App.js