Skip to content

Instantly share code, notes, and snippets.

@siamak
Created October 3, 2020 12:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save siamak/60e0b50b252e99fae0e7be20fae78bb4 to your computer and use it in GitHub Desktop.
Save siamak/60e0b50b252e99fae0e7be20fae78bb4 to your computer and use it in GitHub Desktop.
Tic Tac Toe (React Hook Simple) Codesandbox: https://codesandbox.io/s/tic-tac-toe-z8wo7
import React from "react";
import { createGlobalStyle } from "styled-components";
import Board from "./components/Board/Board";
const GlobalStyle = createGlobalStyle`
body {
margin: 0;
padding: 0;
background: #f4f1de;
letter-spacing: -0.04em;
font-family: Inter, Open-Sans, Helvetica, Sans-Serif;
}
`;
export default function App() {
return (
<>
<Board />
<GlobalStyle />
</>
);
}
import React, { useState } from "react";
import Cell from "../Cell/Cell";
import { Gameboard, Turn, Button, Winner } from "./Board.styles";
const Board = () => {
const [cell, setCell] = useState(Array(9).fill(null));
const [player, setPlayer] = useState("X");
const [isEnd, setEnd] = useState(false);
const checkWin = () => {
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 (const line of lines) {
const [a, b, c] = line;
if (cell[a] && cell[a] === cell[b] && cell[a] === cell[c]) {
return cell[a];
}
}
};
const handleOnClick = (i) => {
if (isEnd) return;
cell[i] = player;
setPlayer(player === "X" ? "O" : "X");
setCell(cell);
if (checkWin()) {
setEnd(true);
}
};
const resetGame = () => {
setCell(Array(9).fill(null));
setPlayer("X");
setEnd(false);
};
return (
<>
{(isEnd && <Winner>Winner game is: {player === "X" ? "O" : "X"}</Winner>) || (
<Turn sign={player}>It's {player} turn</Turn>
)}
<Gameboard>
{cell.map((_, i) => (
<Cell onClick={() => handleOnClick(i)} sign={cell[i]} key={i} />
))}
</Gameboard>
{isEnd && <Button onClick={resetGame}>Reset Game</Button>}
</>
);
};
export default Board;
import React, {useState} from 'react';
import { CellBox } from "./Cell.styles";
const Cell = ({onClick, sign}) => {
return <CellBox sign={sign} onClick={() => onClick()}>{sign}</CellBox>;
};
export default Cell;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment