javascript - React tic tac toe - 显示平局发生的时间

标签 javascript reactjs

I'm following the tic tac toe tutorial.

我现在想添加一个功能,如果有平局(没有人获胜),那么它会用“有平局”更新消息。请参阅下面的完整代码片段:

function Square(props) {
  return (
    <button className="square" onClick={props.onClick}>
      {props.value}
    </button>
  );
}

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>
    );
  }
}

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

  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,
    });
  }

  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;
    } elseif (winner === null) {
      status = 'There has been a draw'
    }
    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>
    );
  }
}

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;
}


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

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

我试图通过 Game 类来做到这一点。在实际检查获胜者的代码中 - 如果我理解正确的话 - 如果没有满足任何条件,它会返回 null 值。相关的代码是这样的:

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;
}

我现在想做的是在引用上述函数的代码中,并显示一条关于谁获胜的消息,我设置一个 elseif 来查看该函数是否抛出 null,如果抛出 null,则显示一个发生平局的消息。该代码如下所示:

 let status;
    if (winner) {
      status = 'Winner: ' + winner;
    } elseif (winner === null) {
      status = 'There has been a draw'
    }
    else {
      status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
    }

calculateWinner 函数中 return null; 的用途是什么?在此应用程序的上下文中,我如何才能最好地检查平局?有更好的方法吗?

问题代码笔:https://codepen.io/anon/pen/OOQxmw?editors=0010

最佳答案

calculateWinner() 在每次渲染时都会被调用,如果在此渲染中没有找到获胜线,则返回 null,这并不一定是游戏结束。您需要检查是否没有找到获胜者以及整个董事会是否已满。这将是平局的条件。

关于javascript - React tic tac toe - 显示平局发生的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47401052/

相关文章:

javascript - 如何在单击链接时获取行值

ios - 为什么 React Native iOS 模拟器的重新加载快捷方式有时会停止工作?

javascript - 渲染后将状态变量设置为 false

javascript - 创建新事件时更新react-big-calendar组件

javascript - 将 JS var 传递到选择器不起作用

javascript - 如何将 JavaScript 对象的值设置为 null

javascript - 简单的 Canvas 动画: 50x50 image moving across

javascript - screenX/Y、clientX/Y和pageX/Y有什么区别?

javascript - 为什么 componentDidMount 没有被解雇?

javascript - 为最初不在商店中的按需组件或组合 reducer 注入(inject) reducer