tic-tac-toe(三连棋)游戏改进

react网站实战入门教程有一个游戏,供大家熟悉react知识。游戏的基本功能如下。

  • tic-tac-toe(三连棋)游戏的所有功能
  • 能够判定玩家何时获胜
  • 能够记录游戏进程
  • 允许玩家查看游戏的历史记录,也可以查看任意一个历史版本的游戏棋盘状态

react网址:https://zh-hans.reactjs.org/tutorial/tutorial.html#why-immutability-is-important

文后附有几个改进游戏的想法,但是没有看到相关后续代码。

  1. 在游戏历史记录列表显示每一步棋的坐标,格式为 (列号, 行号)。
  2. 在历史记录列表中加粗显示当前选择的项目。
  3. 使用两个循环来渲染出棋盘的格子,而不是在代码里写死(hardcode)。
  4. 添加一个可以升序或降序显示历史记录的按钮。
  5. 每当有人获胜时,高亮显示连成一线的 3 颗棋子。
  6. 当无人获胜时,显示一个平局的消息。

因此根据上述官网的改进功能提示,完善了一下游戏功能。沿用官网基本代码,简单修改,如下所示:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";

function Square(props) {
  const { onClick, colored } = props;
  return (
    <button
      className="square"
      onClick={onClick}
      style={{ backgroundColor: colored ? "yellow" : "" }}
    >
      {props.value}
    </button>
  );
}

class Board extends React.Component {
  renderSquare(i) {
    const { winnerSquares, squares, onClick } = this.props;
    return (
      <Square
        value={squares[i]}
        onClick={() => onClick(i)}
        key={i}
        colored={winnerSquares.indexOf(i) > -1 ? true : false}
      />
    );
  }

  renderCheckerboard = (numbers) =>
    numbers.map((item, index) => {
      if (Array.isArray(item)) {
        return (
          <div key={index} className="board-row">
            {this.renderCheckerboard(item)}
          </div>
        );
      } else {
        return this.renderSquare(item);
      }
    });

  render() {
    const numbers = [
      [0, 1, 2],
      [3, 4, 5],
      [6, 7, 8],
    ];
    return <div>{this.renderCheckerboard(numbers)}</div>;
  }
}

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

  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).length > 0 || squares[i]) {
      return;
    }
    squares[i] = this.state.xIsNext ? "X" : "O";
    this.setState({
      history: history.concat([
        { squares: squares, coordinate: [Math.floor(i / 3) + 1, (i % 3) + 1] },
      ]),
      stepNumber: history.length,
      xIsNext: !this.state.xIsNext,
    });
  }

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

  // 排序
  sort() {
    const { ascend } = this.state;
    this.setState({
      ascend: !ascend,
    });
  }

  render() {
    const { stepNumber, ascend, history } = this.state;
    const current = history[this.state.stepNumber];
    const winnerSquares = calculateWinner(current.squares);
    let winner = "";
    if (winnerSquares.length > 0) {
      winner = current.squares[winnerSquares[0]];
    }

    const moves = history.map((step, move) => {
      let desc = move ? "go to move #" + move : "go to game start";
      if (move > 0) {
        desc += ", (" + step.coordinate[1] + ", " + step.coordinate[0] + ")";
      }
      return (
        <li key={move}>
          <button
            onClick={() => this.jumpTo(move)}
            style={{ fontWeight: stepNumber === move ? "bold" : "" }}
          >
            {desc}
          </button>
        </li>
      );
    });

    let status;
    if (winner) {
      status = <span style={{ color: "red" }}>{"winner: " + winner}</span>;
    } else {
      if (stepNumber > 8) {
        status = <span style={{ color: "red" }}>平局</span>;
      } 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)}
            winnerSquares={winnerSquares}
          />
        </div>
        <div className="game-info">
          <div>{status}</div>
          <div>
            <span>排列:</span>
            <button onClick={() => this.sort()}>
              {ascend ? "升序" : "降序"}
            </button>
          </div>
          <ol reversed={ascend ? false : true}>
            {ascend ? moves : moves.reverse()}
          </ol>
        </div>
      </div>
    );
  }
}

// ========================================

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

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 lines[i];
    }
  }
  return [];
}

界面显示如下:

tic-tac-toe(三连棋)游戏改进

代码地址:https://gitee.com/themerz/tic-tac-toe

上一篇:Logic Pro X for Mac - 音乐制作软件


下一篇:一、基本概念