-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
218 lines (187 loc) · 6.63 KB
/
script.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
const X_CLASS = 'x';
const O_CLASS = 'o';
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 board = document.getElementById('board');
const statusText = document.getElementById('status');
const resetButton = document.getElementById('reset');
const aiToggleButton = document.getElementById('ai-toggle-button');
const hamburger = document.getElementById('hamburger');
const preferencesMenu = document.getElementById('preferences-menu');
const themeToggle = document.getElementById('theme-toggle');
const aiDifficulty = document.getElementById('ai-difficulty');
const popup = document.getElementById('popup');
const popupMessage = document.getElementById('popup-message');
const popupClose = document.getElementById('popup-close');
let isGameActive = true;
let currentPlayer = X_CLASS;
let isAIEnabled = false;
let isAIMakingMove = false;
let aiMode = 'easy'; // Default AI difficulty
// Load preferences from localStorage
const savedTheme = localStorage.getItem('theme');
const savedAIMode = localStorage.getItem('aiMode');
if (savedTheme) {
document.body.classList.toggle('light-mode', savedTheme === 'light');
themeToggle.checked = savedTheme === 'light';
}
if (savedAIMode) {
aiMode = savedAIMode;
aiDifficulty.value = savedAIMode;
}
startGame();
resetButton.addEventListener('click', startGame);
aiToggleButton.addEventListener('click', toggleAI);
hamburger.addEventListener('click', () => {
hamburger.classList.toggle('active');
preferencesMenu.classList.toggle('active');
});
themeToggle.addEventListener('change', () => {
document.body.classList.toggle('light-mode');
localStorage.setItem('theme', document.body.classList.contains('light-mode') ? 'light' : 'dark');
});
aiDifficulty.addEventListener('change', () => {
aiMode = aiDifficulty.value;
localStorage.setItem('aiMode', aiMode);
});
popupClose.addEventListener('click', () => {
popup.classList.remove('active');
});
function startGame() {
isGameActive = true;
isAIMakingMove = false;
currentPlayer = X_CLASS;
cellElements.forEach(cell => {
cell.innerHTML = '';
cell.classList.remove(X_CLASS, O_CLASS, 'winning-cell');
cell.removeEventListener('click', handleClick);
cell.addEventListener('click', handleClick, { once: true });
});
statusText.textContent = `Player ${currentPlayer.toUpperCase()}'s turn`;
popup.classList.remove('active');
}
function toggleAI() {
isAIEnabled = !isAIEnabled;
aiToggleButton.textContent = isAIEnabled ? "Stop AI" : "Play with AI";
startGame();
}
function handleClick(e) {
const cell = e.target;
if (!isGameActive || cell.children.length > 0 || isAIMakingMove) return;
placeMark(cell, currentPlayer);
if (checkWin(currentPlayer)) {
endGame(true);
} else if (isDraw()) {
endGame(false);
} else {
swapTurns();
statusText.textContent = `Player ${currentPlayer.toUpperCase()}'s turn`;
if (isAIEnabled && currentPlayer === O_CLASS) {
isAIMakingMove = true;
setTimeout(makeAIMove, 500); // AI moves after a short delay
}
}
}
function placeMark(cell, currentPlayer) {
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
const use = document.createElementNS("http://www.w3.org/2000/svg", "use");
if (currentPlayer === X_CLASS) {
use.setAttribute("href", "#x-icon");
svg.classList.add("x-icon");
} else {
use.setAttribute("href", "#o-icon");
svg.classList.add("o-icon");
}
svg.appendChild(use);
cell.appendChild(svg);
cell.classList.add(currentPlayer);
}
function swapTurns() {
currentPlayer = currentPlayer === X_CLASS ? O_CLASS : X_CLASS;
}
function checkWin(currentPlayer) {
return WINNING_COMBINATIONS.some(combination => {
return combination.every(index => {
return cellElements[index].classList.contains(currentPlayer);
});
});
}
function endGame(isWin) {
isGameActive = false;
if (isWin) {
popupMessage.textContent = `Player ${currentPlayer.toUpperCase()} Wins!`;
highlightWinningCombination();
} else {
popupMessage.textContent = "Game Draw!";
}
popup.classList.add('active');
}
function highlightWinningCombination() {
WINNING_COMBINATIONS.forEach(combination => {
if (combination.every(index =>
cellElements[index].classList.contains(currentPlayer))) {
combination.forEach(index => {
cellElements[index].classList.add('winning-cell');
});
}
});
}
function isDraw() {
return [...cellElements].every(cell => cell.children.length > 0);
}
function makeAIMove() {
const availableCells = [...cellElements].filter(cell => cell.children.length === 0);
if (availableCells.length > 0) {
let randomCell = getAIMove(availableCells, aiMode);
placeMark(randomCell, O_CLASS);
if (checkWin(O_CLASS)) {
endGame(true);
} else if (isDraw()) {
endGame(false);
} else {
swapTurns();
statusText.textContent = `Player ${currentPlayer.toUpperCase()}'s turn`;
}
}
isAIMakingMove = false;
}
function getAIMove(availableCells, aiMode) {
const shouldMakeSmartMove = Math.random() < (aiMode === 'easy' ? 0.3 : aiMode === 'medium' ? 0.7 : 1);
if (shouldMakeSmartMove) {
// Try to win if possible
for (let cell of availableCells) {
cell.classList.add(O_CLASS);
if (checkWin(O_CLASS)) {
cell.classList.remove(O_CLASS);
return cell;
}
cell.classList.remove(O_CLASS);
}
// Block player from winning
for (let cell of availableCells) {
cell.classList.add(X_CLASS);
if (checkWin(X_CLASS)) {
cell.classList.remove(X_CLASS);
return cell;
}
cell.classList.remove(X_CLASS);
}
}
if (aiMode === 'hard') {
const centerCell = cellElements[4];
if (availableCells.includes(centerCell)) {
return centerCell;
}
const corners = [0, 2, 6, 8];
const availableCorners = corners.filter(index => availableCells.includes(cellElements[index]));
if (availableCorners.length > 0) {
return cellElements[availableCorners[Math.floor(Math.random() * availableCorners.length)]];
}
}
// Otherwise, random move
return availableCells[Math.floor(Math.random() * availableCells.length)];
}