-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
84 lines (65 loc) · 2 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/* Lucas Birkert - TicTacToe */
/* _ _ _ _ */
/* | | (_) | | | | */
/* | |_ _ ___| |_ __ _ ___| |_ ___ ___ */
/* | __| |/ __| __/ _` |/ __| __/ _ \ / _ \ */
/* | |_| | (__| || (_| | (__| || (_) | __/ */
/* \__|_|\___|\__\__,_|\___|\__\___/ \___| */
/* https://github.com/lbirkert/tictactoe/tree/main/LICENSE */
/* (c) Copyright 2024 Lucas Birkert, all rights reserved */
const btns = [];
const field = [];
let player = 1;
// handles button click
function onBtnClick(id) {
return () => {
if (field[id] != 0) return;
btns[id].className = player == 1 ? "x" : "o";
btns[id].disabled = "true";
field[id] = player;
player *= -1;
const win = checkWin();
if (win != 0) {
winner.className = win == 1 ? "x" : "o";
document.body.className = "gameover";
splash.className = "win";
}
if (checkTie()) {
document.body.className = "gameover";
splash.className = "tie";
}
};
}
// resets the playing field
function reset() {
document.body.className = "";
for (id in btns) {
btns[id].className = "";
btns[id].disabled = "";
field[id] = 0;
}
}
// checks whether current state is win and returns winner
function checkWin() {
for (let i = 0; i < 3; i++) {
if (Math.abs(field[i] + field[i + 3] + field[i + 6]) == 3) return field[i];
if (Math.abs(field[i * 3] + field[i * 3 + 1] + field[i * 3 + 2]) == 3) return field[i * 3];
}
if (Math.abs(field[0] + field[4] + field[8]) == 3) return field[0];
if (Math.abs(field[2] + field[4] + field[6]) == 3) return field[2];
return 0;
}
// checks whether current state is tie
function checkTie() {
return field.every((e) => e != 0);
}
// initialize field and btn array
for (row of game.childNodes) {
if (row.nodeType != Node.ELEMENT_NODE) continue;
for (btn of row.childNodes) {
if (btn.nodeType != Node.ELEMENT_NODE) continue;
btn.addEventListener("click", onBtnClick(btns.length));
btns.push(btn);
field.push(0);
}
}