diff --git a/src/index.css b/src/index.css index ab1750a..0ce9c97 100644 --- a/src/index.css +++ b/src/index.css @@ -36,6 +36,10 @@ ol, ul { outline: none; } +.square.in-win-line { + background-color: #fff300; +} + .kbd-navigation .square:focus { background: #ddd; } diff --git a/src/index.js b/src/index.js index 8e104d2..a861be0 100644 --- a/src/index.js +++ b/src/index.js @@ -3,13 +3,17 @@ import ReactDOM from 'react-dom'; import './index.css'; /*TODO - When someone wins, highlight the three squares that caused the win. + When no one wins, display a message about the result being a draw. */ function Square(props) { + const classNames = ['square']; + if (props.isInWinLine) { + classNames.push('in-win-line'); + } return ( - ); @@ -26,6 +30,7 @@ function Board(props) { key={index} value={props.squares[index]} onClick={() => props.handleClick(index)} + isInWinLine={props.winLine?.indexOf(index) >= 0} /> ); } @@ -55,7 +60,7 @@ class Game extends React.Component { 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)) { + if (currentState.squares[i] || calculateWinState(currentState.squares)) { return; } @@ -91,9 +96,9 @@ class Game extends React.Component { const history = this.state.history; const currentState = history[this.state.currentMoveIndex]; let status; - const winner = calculateWinner(currentState.squares); - if (winner) { - status = `Winner: ${winner}`; + const winState = calculateWinState(currentState.squares); + if (winState) { + status = `Winner: ${winState.winner}`; } else { const nextPlayer = this.state.xIsNext ? 'X' : 'O'; status = `Next player ${nextPlayer}`; @@ -121,6 +126,7 @@ class Game extends React.Component { squares={currentState.squares} handleClick={(i) => this.playTurn(i)} xIsNext={this.state.xIsNext} + winLine={winState?.line} />
@@ -133,7 +139,7 @@ class Game extends React.Component { } } -function calculateWinner(squares) { +function calculateWinState(squares) { const lines = [ [0, 1, 2], [3, 4, 5], @@ -147,7 +153,7 @@ function calculateWinner(squares) { 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 {winner: squares[a], line: lines[i]}; } } return null;