使用React做一个井字三关游戏

使用React做一个井字三关游戏(Tic-Tac-Toe)。

使用React和高阶组件实现井字过三关游戏:

import React, { Component } from 'react';

// 高阶组件,用于计算游戏胜者
const withWinnerCalculation = WrappedComponent => {
  return class extends Component {
    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;
    }

    render() {
      const winner = this.calculateWinner(this.props.squares);
      return <WrappedComponent {...this.props} winner={winner} />;
    }
  };
};

// 井字过三关游戏组件
class TicTacToeGame extends Component {
  constructor(props) {
    super(props);
    this.state = {
      squares: Array(9).fill(null),
      xIsNext: true,
    };
  }

  handleClick(i) {
    const squares = this.state.squares.slice();
    if (this.props.winner || squares[i]) {
      return;
    }
    squares[i] = this.state.xIsNext ? 'X' : 'O';
    this.setState({
      squares: squares,
      xIsNext: !this.state.xIsNext,
    });
  }

  renderSquare(i) {
    return (
      <button className="square" onClick={() => this.handleClick(i)}>
        {this.state.squares[i]}
      </button>
    );
  }

  render() {
    const winner = this.props.winner;
    const status = winner ? `Winner: ${winner}` : `Next player: ${this.state.xIsNext ? 'X' : 'O'}`;

    return (
      <div>
        <div className="status">{status}</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>
    );
  }
}

// 使用高阶组件处理游戏胜者计算
const TicTacToeWithWinner = withWinnerCalculation(TicTacToeGame);

export default TicTacToeWithWinner;

在这个示例中,我们创建了一个TicTacToeGame组件,使用withWinnerCalculation高阶组件来处理游戏胜者的计算。withWinnerCalculation高阶组件包装了TicTacToeGame,并通过winner属性将游戏胜者传递给游戏组件。当游戏有胜者时,会显示胜者信息,否则会显示下一个玩家。