Skip to content

Instantly share code, notes, and snippets.

@aq2bq
Created January 13, 2022 11:23
Show Gist options
  • Save aq2bq/8afe59f07265c7a7fea255d40af1d678 to your computer and use it in GitHub Desktop.
Save aq2bq/8afe59f07265c7a7fea255d40af1d678 to your computer and use it in GitHub Desktop.
ox
<html>
<head>
<title>ox</title>
<style type="text/css">
#app {
width: 90px;
}
.cell {
border: 1px solid #000;
float: left;
width: 30px;
height: 30px;
box-sizing: border-box;
list-style: none;
padding: 0;
margin: 0;
cursor: pointer;
text-align: center;
}
.win {
background-color: #f00;
color: #fff;
font-weight: bold;
}
</style>
</head>
<body>
<div id="app"></div>
<script>
const game = () => {
const length = 3;
const cells = [];
const container = document.getElementById("app");
const checkResult = (x, y) => {
const findCell = () => cells.find((cell) => cell.x === x && cell.y === y);
const filterCol = () => cells.filter((cell) => cell.x === x);
const filterRow = () => cells.filter((cell) => cell.y === y);
const filterDiagonal1 = () => cells.filter((cell) => cell.x === cell.y);
const filterDiagonal2 = () => cells.filter((cell) => cell.x + cell.y === length - 1);
const isWin = (candidates) => candidates.every((cell) => cell.value === findCell().value && cell.value !== null)
for(const filter of [filterRow, filterCol, filterDiagonal1, filterDiagonal2]) {
const candidates = filter();
if (isWin(candidates)) {
candidates.forEach((cell) => cell.win());
cells.forEach((cell) => cell.freeze());
break;
}
}
}
const start = () => {
for (let y = 0; y < length; y++) {
for (let x = 0; x < length; x++) {
const cell = Cell(x, y);
cells.push(cell)
container.appendChild(cell.node)
}
}
}
const nextValue = () => {
let state = false;
const get = () => {
state = !state
return (state ? "o" : "x")
}
return get;
}
const getNextValue = nextValue();
const Cell = (x, y) => {
const node = document.createElement("li");
node.className = "cell";
const win = () => node.classList.add('win');
const freeze = () => node.removeEventListener('click', handleOnClick)
const state = { node, x, y, win, freeze, value: null };
const handleOnClick = () => {
state.value = getNextValue();
node.innerText = state.value;
checkResult(x, y);
freeze();
}
node.addEventListener('click', handleOnClick)
return state;
}
start();
}
game();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment