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 './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 (
<Game />
);
}
class Square extends React.Component {
class Square extends React.Component<SquareGameProps, SquareGameState> {
render() {
return(
<button className='square'>
<button className='square' onClick={() => { this.props.onClick() }}>
{ this.props.value }
</button>
);
}
}
class Board extends React.Component {
renderSquare(i: any) {
return <Square value={i} />
class Board extends React.Component<BoardGameProps, BoardGameState> {
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 <Square value={this.state.squares[i]} onClick={() => 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(
<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;