finished game

This commit is contained in:
Wyatt J. Miller 2022-10-01 13:28:23 -04:00
parent 63904870e0
commit 3a73c2fe79

View File

@ -2,29 +2,78 @@ import React from 'react';
import ReactDOM from 'react-dom'; import ReactDOM from 'react-dom';
import './App.css'; 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() { function App() {
return ( return (
<Game /> <Game />
); );
} }
class Square extends React.Component { class Square extends React.Component<SquareGameProps, SquareGameState> {
render() { render() {
return( return(
<button className='square'> <button className='square' onClick={() => { this.props.onClick() }}>
{ this.props.value } { this.props.value }
</button> </button>
); );
} }
} }
class Board extends React.Component { class Board extends React.Component<BoardGameProps, BoardGameState> {
renderSquare(i: any) { constructor(props: any) {
return <Square value={i} /> 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 <Square value={this.state.squares[i]} onClick={() => this.handleClick(i)}/>
} }
render() { 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( return(
<div> <div>
@ -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; export default App;