Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
87 lines (76 loc) · 2.25 KB
/
Copy pathscript.js
File metadata and controls
87 lines (76 loc) · 2.25 KB
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
85
86
87
const COLORS = ["white", "blue", "red"];
let board = [0, 0, 0, 0, 0, 0, 0, 0, 0];
let turn = 0;
const make_div = (x, y, id) => {
const div = document.createElement("div");
document.body.appendChild(div);
div.id = "s" + id;
div.style.position = "absolute";
div.style.width = "90px";
div.style.height = "90px";
div.style.top = 55 + (1 + y) * 100 + "px";
div.style.left = (1 + x) * 100 + "px";
div.style.cursor = "pointer";
div.onclick = (e) => update_board(id);
};
const update_board = (id) => {
if (turn == 9 || win_line(board).length == 3) {
board = [0, 0, 0, 0, 0, 0, 0, 0, 0];
turn = 0;
} else if (board[id] == 0) {
board[id] = (turn % 2) + 1;
turn++;
}
update_draw();
};
const update_draw = () => {
const line = win_line(board);
for (let id = 0; id < 9; id++) {
const div = document.getElementById("s" + id);
div.style.background = COLORS[board[id]];
div.style.outline = "none";
if (board[id] != 0) {
div.style.cursor = "default";
} else {
div.style.cursor = "pointer";
}
}
for (const id of line) {
div = document.getElementById("s" + id);
div.style.outline = "10px solid gold";
}
};
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]
];
const win_line = (B) => {
for (const [a, b, c] of LINES) {
if (B[a] != 0 && B[a] == B[b] && B[a] == B[c]) {
return [a, b, c];
}
}
return [];
};
for (let id = 0; id < 9; id++) {
make_div(id % 3, Math.floor(id / 3), id);
}
update_draw();
const create_reset_button = () => {
const button = document.createElement("button");
button.innerHTML = "Reset";
button.style.position = "absolute";
button.style.top = "73px";
button.style.left = "50px";
button.style.padding = "8px 10px";
button.style.fontSize = "16px";
button.style.cursor = "pointer";
button.onclick = () => {
board = [0, 0, 0, 0, 0, 0, 0, 0, 0];
turn = 0;
update_draw();
};
document.body.appendChild(button);
};
create_reset_button();