diff --git a/src/App.tsx b/src/App.tsx index 2cdd87e..684a1d0 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -2,29 +2,78 @@ import React from 'react'; import ReactDOM from 'react-dom'; import './App.css'; +interface SquareGameProps { + value: any + onClick: Function +} + +interface SquareGameState{ + value: any + + // whatever other state we add here +} + +interface BoardGameProps { + +} + +interface BoardGameState { + squares: any + xIsNext: boolean +} + function App() { return ( ); } -class Square extends React.Component { +class Square extends React.Component { render() { return( - ); } } -class Board extends React.Component { - renderSquare(i: any) { - return +class Board extends React.Component { + constructor(props: any) { + super(props); + + this.state = { + squares: Array(9).fill(null), + xIsNext: true, + } + } + + handleClick(i: string | number) { + const squares = this.state.squares.slice(); + if (calculateWinner(squares) || squares[i]) { + return; + } + squares[i] = this.state.xIsNext ? 'X' : 'O'; + this.setState({ + squares: squares, + xIsNext: !this.state.xIsNext, + }); + } + + renderSquare(i: string | number) { + return this.handleClick(i)}/> } render() { - const status = 'Next player: X'; + const winner = calculateWinner(this.state.squares); + let status; + + if (winner) { + status = 'Winner: ' + winner; + } + else { + status = `Next player: ${this.state.xIsNext ? 'X' : 'O'}`; + } return(
@@ -64,4 +113,28 @@ class Game extends React.Component { ); } } + +function calculateWinner(squares: any) { + 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], + ]; + + lines.forEach((i: any) => { + const [a, b, c] = i; + + if (squares[a] && squares[b] === squares[a] && squares[c]) { + return squares[a]; + } + }); + + return null; +} + export default App;