为什么我的游戏的checkWinner函数不能按预期工作?

时间:2019-08-27 14:20:23

标签: reactjs

我已经将TicTacToe游戏构建为可以在react.js中放入“ X”和“ O”的部分,但是某些代码部分存在问题。当我尝试使用checkWinner()函数确定获胜条件时,问题是我可以点击继续进行记录,但是它应该已执行警报功能并显示消息“ You won”。

我执行以下操作:

function checkWinner() {
  let winLines = [
    ["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 index = 0; index < winLines.length; index++) {
    const [a, b, c] = winLines[index];

    if (
      this.state.board[a] &&
      this.state.board[a] === this.state.board[b] &&
      this.state.board[a] === this.state.board[c]
    ) {
      alert("You won");

      this.setState({
        winner: this.state.player
      });
    }
  }
}

我查看了代码,但没有发现任何问题,所以我将不胜感激,因为这越来越令人沮丧。

2 个答案:

答案 0 :(得分:0)

看看下面的代码,尤其是底部的calculateWinner函数:

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)
        }
      ],
      stepNumber: 0,
      xIsNext: 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) || 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;
    } 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) { /* accepts an array of 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 we have a winner, return that square,
      otherwise, return `null` to indicate no winner yet.
    */
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a]; 
    }
  }
  return null;
}

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

ReactDOM.render(<Game />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

参考

答案 1 :(得分:0)

假设this.state.board是一个数组,其中包含玩家放置其标记的位置:例如[1, 5, 2, 0]

可以使用带有everysome函数的以下函数来总结获胜条件:

if(winlines.some(line => line.every(square => this.state.board.includes(square)))){
  //WIN !
}

因此,如果对于任何一行,this.state.board中都包含其中的每个平方数,则玩家获胜。

const player = ["0", "2", "8", "1"];

function checkWinner() {
  let winLines = [
    ["0", "1", "2"],

    ["3", "4", "5"],

    ["6", "7", "8"],

    ["0", "3", "6"],

    ["1", "4", "7"],

    ["2", "5", "8"],

    ["0", "4", "8"],

    ["2", "4", "6"]
  ];

    if(winLines.some(line => line.every(square => player.includes(square)))){
      console.log('WIN !')
    }
}

checkWinner();

const player = ["0", "8", "1"];

function checkWinner() {
  let winLines = [
    ["0", "1", "2"],

    ["3", "4", "5"],

    ["6", "7", "8"],

    ["0", "3", "6"],

    ["1", "4", "7"],

    ["2", "5", "8"],

    ["0", "4", "8"],

    ["2", "4", "6"]
  ];

    if(winLines.some(line => line.every(square => player.includes(square)))){
      console.log('WIN !')
    }
}

checkWinner();