如何在反应中打井字游戏?

问题描述 投票:0回答:1

我正在用 React 做一个井字游戏,所以这里我有我的公式来搜索赢家

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

这就是我实现游戏的地方

import Board from './Board';
import calculateWinner from './calculateWinner';

export default function Game() {
  const [board, setBoard] = useState(Array(9).fill(null));
  const [history, setHistory] = useState(board);
  const [xIsNext, setXIsNext] = useState(true);
  const [step, setStep] = useState(0);
  const winner = calculateWinner(board);

  const handleClick = index => {
    const boardCopy = board.slice();
    if (winner || boardCopy[index]) return;

    boardCopy[index] = xIsNext ? 'X' : 'O';
    setBoard(boardCopy);
    setXIsNext(!xIsNext);
  };

  function startNewGame() {
    setBoard(Array(9).fill(null));
  }

  function whoIsNext() {
    if (winner) {
      return 'Выиграл ' + winner;
    } else if (!winner) {
      return 'Следующий ход: ' + (xIsNext ? 'X' : 'O');
    } else if (!xIsNext) {
      return 'tie';
    }
  }

  return (
    <div className="game">
      <button onClick={startNewGame}> Начать заново</button>

      <Board squares={board} onClick={handleClick} />

      <p>{whoIsNext()}</p>
    </div>
  );
}
import React, { Component } from 'react';
import Square from './Square';

export default function Board({ squares, onClick }) {
  return (
    <div className="game-board">
      {squares.map((square, index) => (
        <Square key={index} value={square} onClick={() => onClick(index)} />
      ))}
    </div>
  );
}

import React from 'react';

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

我不明白我怎样才能抽奖?我是否需要更改计算获胜者的公式中的某些内容?或者我错过了什么 请帮助我了解我哪里有错误

reactjs react-hooks tic-tac-toe
1个回答
0
投票

你将不得不检查是否还有一个可以免费玩的方块。换句话说,如果

board
没有更多的
null
,那么就是平局。你仍然应该先检查是否有赢家,但如果没有,接下来要检查的是棋盘是否已满。

请注意,您的

if...else if...
链应以
else
结尾,后跟一个
if
:它需要是一个“包罗万象”......没有进一步的条件。

这是对您的

whoIsNext
功能的建议更改:

  function whoIsNext() {
    if (winner) {
      return 'Выиграл ' + winner;
    } else if (board.includes(null)) { // Not yet full board
      return 'Следующий ход: ' + (xIsNext ? 'X' : 'O');
    } else { // Board is full -- it is a tie
      return 'tie';
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.