Last active
July 19, 2019 20:09
-
-
Save stevensona/a34da972f44755ce78afc33c3194c907 to your computer and use it in GitHub Desktop.
React TicTacToe Functional Component
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
// Working demo: https://jsfiddle.net/1r5f2cey/1/ | |
/* CSS | |
#board { | |
display: grid; | |
grid: repeat(3, 1fr) / repeat(3, 1fr); | |
grid-gap: 5px; | |
} | |
.space { | |
background-color: darkslategray; | |
width: 100px; | |
height: 100px; | |
font-size: 2.5em; | |
cursor: pointer; | |
} | |
*/ | |
import React, { useState } from "react"; | |
export default () => { | |
const [board, setBoard] = useState(" "); | |
const [nextPiece, setNextPiece] = useState("X"); | |
const wins = [ | |
[0, 1, 2], | |
[3, 4, 5], | |
[6, 7, 8], | |
[0, 3, 6], | |
[1, 4, 7], | |
[2, 5, 8], | |
[0, 4, 8], | |
[2, 4, 6] | |
].filter( | |
w => | |
board[w[0]] === board[w[1]] && | |
board[w[1]] === board[w[2]] && | |
board[w[0]] !== " " | |
); | |
const winner = wins.length > 0 ? board.split("")[wins[0][0]] : false; | |
return ( | |
<> | |
{winner && <p>{winner} wins!</p>} | |
<div id="board"> | |
{board.split("").map((p, i) => ( | |
<div | |
className="space" | |
key={i} | |
onClick={() => { | |
if (board[i] === " " && !winner) { | |
setBoard(board.substr(0, i) + nextPiece + board.substr(i + 1)); | |
setNextPiece(nextPiece === "X" ? "O" : "X"); | |
} | |
}} | |
> | |
{p} | |
</div> | |
))} | |
</div> | |
<button | |
onClick={() => { | |
setBoard(" "); | |
setNextPiece("X"); | |
}} | |
> | |
Reset | |
</button> | |
</> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment