-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
64 lines (59 loc) · 1.38 KB
/
Copy pathapp.js
File metadata and controls
64 lines (59 loc) · 1.38 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
const cells = document.querySelectorAll('.cell');
let winPositions = [[1,5,9],[3,5,7],[4,5,6],[2,5,8],[1,2,3],[7,8,9],[1,4,7],[3,6,9]];
let moves = [];
let won = false;
let player = "x";
cells.forEach(cell => {
cell.addEventListener('click', ()=> {
const cellNumber = Number(cell.dataset.indexNumber);
if(cell.classList.contains('x')) {
return;
} else if(cell.classList.contains('o')) {
return;
}
if(moves[player] == undefined) {
moves.x = []; moves.o = [];
}
moves[player].push(cellNumber);
winCheck();
if(player == "x") {
cell.classList.add(player);
player = "o";
} else if(player == "o"){
cell.classList.add(player);
player = "x";
}
if((won == false) && (moves["x"].length+moves["o"].length == 9)) {
alert("draw");
resetBoard();
}
else if(won == true) {
resetBoard();
won = false;
}
});
})
function winCheck() {
for(const winRow of winPositions) {
let streak = 0;
for(const winField of winRow) {
for(const move of moves[player]) {
if(winField == move) {
streak++;
if(streak == 3) {
alert(player+" won");
won = true;
return;
}
}
}
}
}
}
function resetBoard() {
cells.forEach(cell => {
cell.className = "cell";
player = "x";
moves = [];
});
}