-
Notifications
You must be signed in to change notification settings - Fork 0
/
tic-tac-toe.js
233 lines (192 loc) · 7.98 KB
/
tic-tac-toe.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
document.addEventListener('DOMContentLoaded', () => {
const PLAYER_X_CLASS = 'x';
const PLAYER_O_CLASS = 'circle';
const WINNING_COMBINATIONS = [
[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 cellElements = document.querySelectorAll('[data-cell]');
const boardElement = document.getElementById('board');
const winningMessageElement = document.getElementById('winningMessage');
const restartButton = document.getElementById('restartButton');
const winningMessageTextElement = document.getElementById('winningMessageText');
const boardOverlay = document.getElementById('overlay');
const scribbleSound = document.getElementById('scribbleAudio');
let isPlayerTurn = true;
startGame();
restartButton.addEventListener('click', startGame);
function startGame() {
isPlayerTurn = true;
cellElements.forEach(cell => {
cell.classList.remove(PLAYER_X_CLASS);
cell.classList.remove(PLAYER_O_CLASS);
cell.removeEventListener('click', handleCellClick);
cell.addEventListener('click', handleCellClick, { once: true });
});
winningMessageElement.classList.remove('show');
setBoardHoverClass();
}
function computerPlay() {
isPlayerTurn = false;
boardOverlay.style.display = 'block';
const emptyCells = [...cellElements].filter(cell => !cell.classList.contains(PLAYER_X_CLASS) && !cell.classList.contains(PLAYER_O_CLASS));
if (Math.random() <= 0.5) {
// * 50% chance of making a random move
const randomIndex = Math.floor(Math.random() * emptyCells.length);
const selectedCell = emptyCells[randomIndex];
setTimeout(() => {
placeMark(selectedCell, PLAYER_O_CLASS);
endTurn();
boardOverlay.style.display = 'none';
}, Math.random() * 500 + 600);
} else {
// * 50% chance of making a strategic move
const strategicMove = getStrategicMove(emptyCells);
if (strategicMove !== null) {
setTimeout(() => {
placeMark(strategicMove, PLAYER_O_CLASS);
endTurn();
boardOverlay.style.display = 'none';
}, Math.random() * 500 + 600);
} else {
// If no strategic move available, make a random move
const randomIndex = Math.floor(Math.random() * emptyCells.length);
const selectedCell = emptyCells[randomIndex];
setTimeout(() => {
placeMark(selectedCell, PLAYER_O_CLASS);
endTurn();
boardOverlay.style.display = 'none';
}, Math.random() * 500 + 600);
}
}
}
function getStrategicMove(emptyCells) {
for (const cell of emptyCells) {
cell.classList.add(PLAYER_O_CLASS);
// * Check if AI can win in the next move
if (checkWin(PLAYER_O_CLASS)) {
cell.classList.remove(PLAYER_O_CLASS);
return cell;
}
cell.classList.remove(PLAYER_O_CLASS);
}
for (const cell of emptyCells) {
cell.classList.add(PLAYER_X_CLASS);
// * Check if player can win in the next move and block it
if (checkWin(PLAYER_X_CLASS)) {
cell.classList.remove(PLAYER_X_CLASS);
return cell;
}
cell.classList.remove(PLAYER_X_CLASS);
}
// * If no winning or blocking moves, prioritize center, corners, then edges
const centerCell = cellElements[4];
if (emptyCells.includes(centerCell)) {
return centerCell;
}
const corners = [cellElements[0], cellElements[2], cellElements[6], cellElements[8]];
const emptyCorners = corners.filter(corner => emptyCells.includes(corner));
if (emptyCorners.length > 0) {
return emptyCorners[Math.floor(Math.random() * emptyCorners.length)];
}
const edges = [cellElements[1], cellElements[3], cellElements[5], cellElements[7]];
const emptyEdges = edges.filter(edge => emptyCells.includes(edge));
if (emptyEdges.length > 0) {
return emptyEdges[Math.floor(Math.random() * emptyEdges.length)];
}
return null; // ! No strategic moves available
}
function endTurn() {
if (checkWin(PLAYER_O_CLASS)) {
endGame(false);
} else if (isDraw()) {
endGame(true);
} else {
isPlayerTurn = true;
setBoardHoverClass();
if (!isPlayerTurn) {
setTimeout(computerPlay, 300);
}
}
}
function handleCellClick(e) {
const cell = e.target;
if (!isPlayerTurn || cell.classList.contains(PLAYER_X_CLASS) || cell.classList.contains(PLAYER_O_CLASS)) {
return;
}
if (isPlayerTurn && !cell.classList.contains(PLAYER_X_CLASS) && !cell.classList.contains(PLAYER_O_CLASS)) {
const currentClass = PLAYER_X_CLASS;
placeMark(cell, currentClass);
if (checkWin(currentClass)) {
endGame(false);
} else if (isDraw()) {
endGame(true);
} else {
isPlayerTurn = false;
setBoardHoverClass();
setTimeout(computerPlay, 300);
}
}
}
function endGame(draw) {
if (draw) {
winningMessageTextElement.innerText = "It's a draw!";
boardOverlay.style.display = 'none';
} else {
if (isPlayerTurn) {
winningMessageTextElement.innerText = 'You win!';
boardOverlay.style.display = 'none';
var duration = 3 * 1000;
var animationEnd = Date.now() + duration;
var defaults = { startVelocity: 30, spread: 360, ticks: 60, zIndex: 9999 };
function randomInRange(min, max) {
return Math.random() * (max - min) + min;
}
var interval = setInterval(function() {
var timeLeft = animationEnd - Date.now();
if (timeLeft <= 0) {
return clearInterval(interval);
}
var particleCount = 50 * (timeLeft / duration);
// since particles fall down, start a bit higher than random
confetti({ ...defaults, particleCount, origin: { x: randomInRange(0.1, 0.3), y: Math.random() - 0.2 } });
confetti({ ...defaults, particleCount, origin: { x: randomInRange(0.7, 0.9), y: Math.random() - 0.2 } });
}, 250);
} else {
winningMessageTextElement.innerText = 'The computer wins!';
boardOverlay.style.display = 'none';
}
}
winningMessageElement.classList.add('show');
setBoardHoverClass();
}
function isDraw() {
return [...cellElements].every(cell => {
return cell.classList.contains(PLAYER_X_CLASS) || cell.classList.contains(PLAYER_O_CLASS);
});
}
function placeMark(cell, currentClass) {
// play the scribble sound
scribbleSound.currentTime = 0;
scribbleSound.play();
cell.classList.add(currentClass);
}
function setBoardHoverClass() {
boardElement.classList.remove(PLAYER_X_CLASS);
boardElement.classList.remove(PLAYER_O_CLASS);
boardElement.classList.add(PLAYER_X_CLASS);
}
function checkWin(currentClass) {
return WINNING_COMBINATIONS.some(combination => {
return combination.every(index => {
return cellElements[index].classList.contains(currentClass);
});
});
}
});