Created
August 15, 2022 10:02
-
-
Save sebinsua/bb9724c8071907d084776ad31e02d9c0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState } from "react"; | |
import "./styles.css"; | |
function createGrid(n = 3) { | |
return Array(n) | |
.fill(() => Array(n).fill(null)) | |
.map((createRow) => createRow()); | |
} | |
const playerPieces = { | |
1: "X", | |
2: "O" | |
}; | |
function evaluateGrid(grid) { | |
const height = grid.length; | |
const width = grid[0].length; | |
for (let y = 0; y < height; y++) { | |
const row = grid[y]; | |
if (row.every((cell) => cell === 1)) { | |
return 1; | |
} | |
if (row.every((cell) => cell === 2)) { | |
return 2; | |
} | |
} | |
for (let x = 0; x < width; x++) { | |
const columns = grid.map((row) => row[x]); | |
if (columns.every((cell) => cell === 1)) { | |
return 1; | |
} | |
if (columns.every((cell) => cell === 2)) { | |
return 2; | |
} | |
} | |
if (grid[0][0] === 1 && grid[1][1] === 1 && grid[2][2] === 1) { | |
return 1; | |
} | |
if (grid[0][0] === 2 && grid[1][1] === 2 && grid[2][2] === 2) { | |
return 2; | |
} | |
if (grid[0][2] === 1 && grid[1][1] === 1 && grid[2][0] === 1) { | |
return 1; | |
} | |
if (grid[0][2] === 2 && grid[1][1] === 2 && grid[2][0] === 2) { | |
return 2; | |
} | |
return null; | |
} | |
function TicTacToe() { | |
const [grid, setGrid] = useState(createGrid); | |
const [player, setPlayer] = useState(1); | |
const winner = evaluateGrid(grid); | |
function handleClick(_, y2, x2) { | |
if (winner !== null) { | |
return; | |
} | |
if (grid[y2][x2] !== null) { | |
return; | |
} | |
setGrid((grid) => { | |
return grid.map((row, y) => | |
y2 === y ? row.map((cell, x) => (x2 === x ? player : cell)) : row | |
); | |
}); | |
setPlayer(player === 1 ? 2 : 1); | |
} | |
return ( | |
<div> | |
<div> | |
{winner | |
? `Player ${winner} won the game!` | |
: `It's player ${player}'s turn!`} | |
</div> | |
<div className="grid"> | |
{grid.map((row, y) => ( | |
<div key={`row-${y}`} className="grid__row"> | |
{row.map((cell, x) => ( | |
<div | |
key={`cell-${y}-${x}`} | |
className="grid__row__cell" | |
onClick={(event) => handleClick(event, y, x)} | |
> | |
{typeof cell === "number" ? playerPieces[cell] : ""} | |
</div> | |
))} | |
</div> | |
))} | |
</div> | |
</div> | |
); | |
} | |
export default function App() { | |
return ( | |
<div className="App"> | |
<TicTacToe /> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment