determine a winner

This commit is contained in:
Paul Trowbridge 2021-04-18 22:38:28 -04:00
parent 3c5e012444
commit d3f8ad21a1

View File

@ -22,7 +22,12 @@ function Square(props){
handleClick(i) {
const squares = this.state.squares.slice();
squares[i] = this.state.xIsNext ? 'X' : 'O';
this.setState({squares: squares,xIsNext: !this.state.xIsNext});
this.setState(
{
squares: squares,
xIsNext: !this.state.xIsNext
}
);
}
renderSquare(i) {
@ -39,7 +44,13 @@ function Square(props){
}
render() {
const status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
const winner = calculateWinner(this.state.squares);
let status;
if (winner) {
status = 'Winner: ' + winner;
} else {
status = 'Next Player: ' + (this.state.xIsNext ? 'X' : 'O')
}
return (
<div>
@ -87,3 +98,22 @@ function Square(props){
document.getElementById('root')
);
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;
}