Winning Square井字游戏ReactJs

时间:2020-10-25 06:46:58

标签: reactjs tic-tac-toe

class Game extends Component {   
  constructor(props)
 {
    super(props);

    this.state = {
      history: [
        {
          squares: Array(9).fill(null),
        },
      ],
      xIsNext: true,
      stepNo: 0,
    };
  }
  handleClick(i)
 {
    const history = this.state.history.slice(0,this.state.stepNo + 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,
        },
      ]),
      stepNo : history.length,
      xIsNext: !this.state.xIsNext,
    });
  } 
  jumpTo(step) {
    this.setState({
      stepNo : 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 decs = move ? "DESC: go to move # " + move :
       "DESC: go to the game start";
      return (      
          <li key={move}>
            <button
            className = "focus-buttons"
            onClick={() => this.jumpTo(move)}
            >{decs}</button>
          </li>
      );
    });
    let status;
    if (winner) {
      status = "Winner: " + winner;
      } else if ((this.state.xIsNext ? "X" : "O")){
      status = "Next player: " + (this.state.xIsNext ? "X" : "O")}
    return (
        <div>
          <Board
            squares={current.squares}
            onClick={(i) => this.handleClick(i)}
          /> 
      {status}
      {moves}
      </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;}

在上面的部分中,我想以某种方式对获胜的正方形进行样式设置,但无法访问那些正方形。如何捕获那些动态获胜平方,以便可以突出显示它们以显示“ x”或“ o”的获胜平方?我尝试使用不同的方法,但是通常最终会设计整个正方形的样式,而不是必需的样式?

0 个答案:

没有答案