From f04e8ab138e3c4b326f8ddebcfbdfcd66a09ffcc Mon Sep 17 00:00:00 2001 From: Alice Gaudon Date: Sun, 13 Mar 2022 17:21:52 +0100 Subject: [PATCH] Finish tutorial's guided part --- src/index.js | 115 ++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 99 insertions(+), 16 deletions(-) diff --git a/src/index.js b/src/index.js index 70f7c67..6727202 100644 --- a/src/index.js +++ b/src/index.js @@ -2,27 +2,26 @@ import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; -class Square extends React.Component { - render() { - return ( - - ); - } + +function Square(props) { + return ( + + ); } class Board extends React.Component { renderSquare(i) { - return ; + return this.props.handleClick(i)} + />; } render() { - const status = 'Next player: X'; - return (
-
{status}
{this.renderSquare(0)} {this.renderSquare(1)} @@ -44,24 +43,108 @@ class Board extends React.Component { } class Game extends React.Component { + constructor(props) { + super(props); + this.state = { + history: [{ + squares: Array(9).fill(null), + }], + xIsNext: true, + currentMoveIndex: 0, + } + } + + playTurn(i) { + const history = this.state.history.slice(0, this.state.currentMoveIndex + 1); + const currentState = history[history.length - 1]; + if (currentState.squares[i] || calculateWinner(currentState.squares)) { + return; + } + + const newSquares = [...currentState.squares]; + newSquares[i] = this.state.xIsNext ? 'X' : 'O'; + + this.setState({ + history: [...history, { + squares: newSquares, + }], + xIsNext: !this.state.xIsNext, + currentMoveIndex: history.length, + }); + } + + jumpTo(moveIndex) { + this.setState({ + currentMoveIndex: moveIndex, + xIsNext: moveIndex % 2 === 0, + }); + } + render() { + const history = this.state.history; + const currentState = history[this.state.currentMoveIndex]; + let status; + const winner = calculateWinner(currentState.squares); + if (winner) { + status = `Winner: ${winner}`; + } else { + const nextPlayer = this.state.xIsNext ? 'X' : 'O'; + status = `Next player ${nextPlayer}`; + } + + const moves = history.map((state, index) => { + const description = index === 0 ? + 'Go to game start' : + `Go to move #${index}`; + return ( +
  • + +
  • + ); + }); + return (
    - + this.playTurn(i)} + xIsNext={this.state.xIsNext} + />
    -
    {/* status */}
    -
      {/* TODO */}
    +
    {status}
    +
      {moves}
    ); } } +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( - , + , document.getElementById('root') ); +