Skip to content

Instantly share code, notes, and snippets.

@viniciusCamargo
Last active February 24, 2021 15:59
Show Gist options
  • Save viniciusCamargo/4d834b9695d25c1657d28ce662c068f3 to your computer and use it in GitHub Desktop.
Save viniciusCamargo/4d834b9695d25c1657d28ce662c068f3 to your computer and use it in GitHub Desktop.
tic tac toe
import React from "react";
import ReactDOM from "react-dom";
const initialBoard = {
a: {
a1: { value: "" },
a2: { value: "" },
a3: { value: "" },
},
b: {
b1: { value: "" },
b2: { value: "" },
b3: { value: "" },
},
c: {
c1: { value: "" },
c2: { value: "" },
c3: { value: "" },
},
};
const wins = [
["a1", "a2", "a3"],
["b1", "b2", "b3"],
["c1", "c2", "c3"],
["a1", "b1", "c1"],
["a2", "b2", "c2"],
["a3", "b3", "c3"],
["a1", "b2", "c3"],
["a3", "b2", "c1"],
];
const checkBoard = (board) => {
const kv = Object.keys(board).reduce((acc, rowId) => {
const row = board[rowId];
Object.keys(row).map((squareId) => {
const { value } = row[squareId];
acc[squareId] = value;
}, {});
return acc;
}, {});
return wins.filter((win) => {
const [a, b, c] = win;
if (kv[a] && kv[b] && kv[c]) {
return kv[a] === kv[b] && kv[b] === kv[c];
}
}).length;
};
const Board = () => {
const [isX, setIsX] = React.useState(true);
const [board, setBoard] = React.useState(initialBoard);
React.useEffect(() => {
if (checkBoard(board)) {
alert(`"${!isX ? "x" : "o"}" has won!`);
setBoard(initialBoard);
}
}, [board]);
const handleClick = (row, squareId, rowId, square) => {
if (square.value) {
return;
}
setBoard((board) => {
const value = isX ? "x" : "o";
const newRow = { ...row, [squareId]: { value } };
const newBoard = { ...board, [rowId]: newRow };
return newBoard;
});
setIsX((x) => !x);
};
return (
<div className="mx-auto max-w-xs p-5">
{Object.keys(board).map((rowId) => {
const row = board[rowId];
return (
<div key={rowId} className="grid grid-cols-3 gap-4 h-20 pb-4">
{Object.keys(row).map((squareId) => {
const square = row[squareId];
const squareStyle = square.value
? "flex items-center justify-center border-4 border-indigo-600 text-center text-white text-4xl font-extrabold bg-indigo-600 "
: "border-4 border-indigo-600";
return (
<div
className={squareStyle}
key={squareId}
onClick={() => handleClick(row, squareId, rowId, square)}>
{square.value}
</div>
);
})}
</div>
);
})}
<button
className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
onClick={() => setBoard(initialBoard)}>
Reset Board
</button>
</div>
);
};
ReactDOM.render(<Board />, document.getElementById("app"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment