-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.js
99 lines (81 loc) · 2.14 KB
/
game.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
let turn = "x";
let winConditions = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[1, 4, 7],
[2, 5, 8],
[3, 6, 9],
[1, 5, 9],
[3, 5, 7]
];
let squares = document.querySelectorAll(".square");
let selecteds = {
1: { isSelected: false, by: "none" },
2: { isSelected: false, by: "none" },
3: { isSelected: false, by: "none" },
4: { isSelected: false, by: "none" },
5: { isSelected: false, by: "none" },
6: { isSelected: false, by: "none" },
7: { isSelected: false, by: "none" },
8: { isSelected: false, by: "none" },
9: { isSelected: false, by: "none" }
};
const nextTurn = () => {
if(turn === "x") {
turn = "o";
} else {
turn = "x";
}
}
const checkSequences = (s) => {
if (selecteds[s[0]].by === selecteds[s[1]].by && selecteds[s[0]].by === selecteds[s[2]].by
&& selecteds[s[0]].by !== "none") {
return true;
}
return false;
}
const checkDraw = () => {
for(let i = 1; i <= squares.length; i++ ){
if(!selecteds[i].isSelected){
return false;
}
}
for(let item of winConditions) {
if (checkSequences(item)) {
return false;
}
}
return true
}
const isGameOver = () => {
for (let item of winConditions) {
if (checkSequences(item) || checkDraw()) {
return true;
}
}
return false;
}
const handlePlays = (square) => {
if(selecteds[parseInt(square.id)].isSelected === false) {
selecteds[parseInt(square.id)].isSelected = true;
selecteds[parseInt(square.id)].by = turn;
if (!isGameOver()) {
nextTurn();
}
}
}
const handleReset = () => {
turn = "x";
selecteds = {
1: { isSelected: false, by: "none" },
2: { isSelected: false, by: "none" },
3: { isSelected: false, by: "none" },
4: { isSelected: false, by: "none" },
5: { isSelected: false, by: "none" },
6: { isSelected: false, by: "none" },
7: { isSelected: false, by: "none" },
8: { isSelected: false, by: "none" },
9: { isSelected: false, by: "none" }
};
}