模仿React官网小游戏

163 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第22天,点击查看活动详情

今天简单了模仿react官网上的demo进行学习,官网给的是一个井字棋的游戏,游戏的功能主要有几个

  • 生成九宫格
  • 点击九宫格下棋
  • 轮流切换下棋
  • 下棋记忆功能

我们先从整个Game的Class类开始,通过ReactDOM.render绑定到root上面,通过state定义了几个数据,分别是history,stepNumber,xIsNext,history主要是记录历史下棋记录,stepNumber是下棋的步数,xIsNext是轮流切换角色下棋
在render函数中,通过moves返回一个历史记录列表,并绑定步数的跳转函数

class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [
        {
          squares: Array(9).fill(null)
        }
      ],
      stepNumber: 0,
      xIsNext: true
    };
  }

  
  render() {
    const history = this.state.history;
    const current = history[this.state.stepNumber];
    const winner = calculateWinner(current.squares);

    const moves = history.map((step, move) => {
      const desc = move ?
        'Go to move #' + move :
        'Go to game start';
      return (
        <li key={move}>
          <button onClick={() => this.jumpTo(move)}>{desc}</button>
        </li>
      );
    });

    let status;
    if (winner) {
      status = "Winner: " + winner;
    } else {
      status = "Next player: " + (this.state.xIsNext ? "X" : "O");
    }

    return (
      <div className="game">
        <div className="game-board">
          <Board
            squares={current.squares}
            onClick={i => this.handleClick(i)}
          />
        </div>
        <div className="game-info">
          <div>{status}</div>
          <ol>{moves}</ol>
        </div>
      </div>
    );
  }
}

ReactDOM.render(<Game />, document.getElementById("root"));

Board组件通过接受Game组件的值进行渲染,这里需要给每个格子定义下标,到后面可以用于记录下棋下到了哪个格子上,例如(3,4)
Board的render返回中出现一个this.renderSquare,这是因为我们将renderSquare组件当成一个函数写,而不是当成一个类写

class Board extends React.Component {
  renderSquare(i) {
    return (
      <Square
        value={this.props.squares[i]}
        onClick={() => this.props.onClick(i)}
      />
    );
  }

  render() {
    return (
      <div>
        <div className="board-row">
          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}
        </div>
        <div className="board-row">
          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}
        </div>
        <div className="board-row">
          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}
        </div>
      </div>
    );
  }
}
function Square(props) {
  return (
    <button className="square" onClick={props.onClick}>
      {props.value}
    </button>
  );
}

到这里基本就可以有一个游戏的框架了,接下来是定义一些方法,比如点击函数和切换的轮流下棋的函数,比如通过handclick函数去触发下棋,然后每次下棋都会判断是否已经有一方胜利,这里的判定胜利我们通过一个函数进行calculateWinner函数判定,还有一个记录跳转的函数,可以通过点击下棋记录,返回到那一步下棋的落子

handleClick(i) {
    const history = this.state.history.slice(0, this.state.stepNumber + 1);
    const current = history[history.length - 1];
    const squares = current.squares.slice();
    if (calculateWinner(squares) || squares[i]) {
      return;
    }
    squares[i] = this.state.xIsNext ? "X" : "O";
    this.setState({
      history: history.concat([
        {
          squares: squares
        }
      ]),
      stepNumber: history.length,
      xIsNext: !this.state.xIsNext
    });
  }

  jumpTo(step) {
    this.setState({
      stepNumber: step,
      xIsNext: (step % 2) === 0
    });
  }

判断胜利的方法比较简单,是通过定义九宫格上的三连子的数组进行判断,如果有一条相同的话就会判定为成功

function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6]
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a];
    }
  }
  return null;
}