-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
96 lines (85 loc) · 2.08 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
85
86
87
88
89
90
91
92
93
94
95
96
const cells = document.querySelectorAll(".row>div");
const winningCombos = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (let i = 0; i < cells.length; i++) {
cells[i].addEventListener("click", cellClicked);
}
let currentPlayer = "X"
let gameOver = false;
let moveCount = 0;
function cellClicked(event) {
if (gameOver) {
resetGame();
return;
}
if (event.target.textContent !== "") {
return;
};
//draws current player
event.target.textContent = currentPlayer;
moveCount++
//console.log(moveCount)
checkWinner();
togglePlayer();
}
function togglePlayer() {
if (currentPlayer === "X") {
currentPlayer = "O"
} else {
currentPlayer = "X"
}
}
//much simpler
function checkWinner() {
if (checkCombo(0, 1, 2)) {
console.log("WINNER!!!")
gameOver = true;
} else if (checkCombo(3, 4, 5)) {
console.log("WINNER!!!")
gameOver = true;
} else if (checkCombo(6, 7, 8)) {
console.log("WINNER!!!")
gameOver = true;
} else if (checkCombo(0, 3, 6)) {
console.log("WINNER!!!")
gameOver = true;
} else if (checkCombo(1, 4, 7)) {
console.log("WINNER!!!")
gameOver = true;
} else if (checkCombo(2, 5, 8)) {
console.log("WINNER!!!")
gameOver = true;
} else if (checkCombo(0, 4, 8)) {
console.log("WINNER!!!")
gameOver = true;
} else if (checkCombo(2, 4, 6)) {
console.log("WINNER!!!")
gameOver = true;
} else if (moveCount === 9) {
console.log("Draw!")
gameOver = true
}
}
function resetGame() {
for (let i = 0; i < cells.length; i++) {
cells[i].textContent = "";
}
currentPlayer = "X";
gameOver = false;
moveCount = 0;
}
function checkCombo(a, b, c) {
if (cells[a].textContent === currentPlayer && cells[b].textContent === currentPlayer && cells[c].textContent === currentPlayer) {
return true
} else {
return false
}
}