-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
353 lines (294 loc) · 10.9 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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
// when program is starting, this autoplays the bgm unless autoplay is blocked by the browser,
// then bgm starts playing when the user has clicked something
document.addEventListener('DOMContentLoaded', (event) => {
const bgm = document.getElementById('casual-bgm');
bgm.volume = 0.7;
bgm.play().catch(error => {
console.log('Auto-play was prevented. Click the screen to start the audio.');
});
document.addEventListener('click', () => {
bgm.play();
}, { once: true });
});
// create 2d array of tiles in a 10 x 10 grid
let board = [];
let timer;
let gameover;
const size = 10
const numBombs = 12;
const directions = [
[-1,-1], [-1,0], [-1,1],
[0,-1], [0,1],
[1,-1], [1,0], [1,1]
];
// keeps track of number of revealed tiles - if >= (size * size) - numBombs, game ends
let revealedTiles = 0;
function initializeBoard() {
switchAudio('casual-bgm', 'game-bgm');
gameover = false;
resetTimer();
// hide game over texts
document.getElementById("win-lose-text").classList.add('hidden');
document.getElementById("win-lose-image").classList.add('hidden');
document.getElementById("play-again-btn").classList.add('hidden');
// clear board
board = Array(size).fill().map(() => Array(size).fill(0));
revealedTiles = 0;
let placedBombs = 0;
// randomly populate grid with 10 bombs
while (placedBombs < numBombs) {
let row = Math.floor(Math.random() * size); // randomly generates row number from 0 to 9
let col = Math.floor(Math.random() * size); // randomly generates col number from 0 to 9
if (board[row][col] === 0) {
board[row][col] = -1; // this tile is now a bomb (-1)
placedBombs += 1;
}
}
// fill in non-bomb tiles with the number of bombs in their proximity
for (let row = 0; row < size; row++) {
for (let col = 0; col < size; col++) {
if (board[row][col] != -1) { // tile is not a bomb
let nearbyBombs = 0;
// check each direction in tile's proximity for bombs
for (let [dx,dy] of directions) {
let newRow = row+dx;
let newCol = col+dy;
if (newRow >= 0 && newRow < size && newCol >= 0 && newCol < size) {
// array indexes are valid
if (board[newRow][newCol] === -1) {
nearbyBombs++;
}
}
}
// update 2d array tile with number of bombs
board[row][col] = nearbyBombs;
}
}
}
displayBoard();
}
function displayBoard() {
const gridContainer = document.getElementById("board");
gridContainer.innerHTML = ''; // clear the board before populating it
for (let row = 0; row < size; row++) {
for (let col = 0; col < size; col++) {
// create grid item
const tile = document.createElement("div");
tile.className = "grid-item";
tile.dataset.row = row;
tile.dataset.col = col;
tile.dataset.value = board[row][col];
// assign light or dark green color for checkered board pattern
if ((row%2 === 0 && col%2 === 0) || (row%2 === 1 && col%2 === 1)) {
tile.classList.add("grid-item-light");
} else {
tile.classList.add("grid-item-dark");
}
// when left/regular-clicked, reveals bomb or number of nearby bombs
// when right-clicked, marks tile with flag
tile.addEventListener("click", () => {
revealTiles(tile);
});
tile.addEventListener("contextmenu", (event) => {
event.preventDefault();
flagTile(tile);
});
// add grid item to grid container
gridContainer.appendChild(tile);
}
}
startTimer();
}
function startTimer() {
timer = setInterval(() => {
seconds++;
document.getElementById('timer').innerText = `Time: ${seconds}`;
}, 1000);
}
function stopTimer() {
clearInterval(timer);
}
function resetTimer() {
clearInterval(timer);
seconds = 0;
document.getElementById('timer').innerText = `Time: ${seconds}`;
}
function flagTile(tile) {
// check that tile is not revealed
if (!tile.classList.contains('revealed')) {
if (tile.innerHTML != '🚩') {
// adds flag
tile.innerHTML = '🚩';
} else {
// removes flag
tile.innerHTML = '';
}
}
}
// recursive function
function revealTiles(tile) {
if (gameover === true) {
return;
}
const row = Number(tile.dataset.row);
const col = Number(tile.dataset.col);
const value = Number(tile.dataset.value);
if (tile.classList.contains('revealed')) {
return;
}
tile.classList.add('revealed');
revealedTiles++;
if (value === -1) { // is a bomb
gameover = true;
tile.innerHTML = '💣';
tile.style.backgroundColor = 'red';
// makes the cursor default when hovering over tiles
const allTiles = document.querySelectorAll('.grid-item');
allTiles.forEach(tile => {
tile.classList.add('revealed');
});
// create explosion image
const explosion = document.createElement('img');
explosion.src = 'art/explosion.png';
explosion.classList.add('explosion');
// position the explosion over the tile
explosion.style.left = `${tile.offsetLeft}px`;
explosion.style.top = `${tile.offsetTop + 20}px`;
// add explosion image to the game screen
const gameScreen = document.getElementById('game-screen');
gameScreen.appendChild(explosion);
// pause game bgm and play bomb sound
switchAudio('game-bgm', 'bomb-sound');
// remove the explosion image after 1 second
setTimeout(() => {
gameScreen.removeChild(explosion);
gameOver('lose');
}, 1000);
} else {
if (value > 0) { // has nearby bombs
tile.innerHTML = value;
tile.style.color = getTextColor(value);
} else { // empty tile (recursively reveals nearby tiles!)
for (let [dx,dy] of directions) {
let newRow = row + dx;
let newCol = col + dy;
if (newRow >= 0 && newRow < size && newCol >= 0 && newCol < size) {
const adjTile = document.querySelector(`.grid-item[data-row='${newRow}'][data-col='${newCol}']`);
if (adjTile) {
revealTiles(adjTile);
}
}
}
}
if (revealedTiles === (size * size) - numBombs) {
gameOver('win');
}
}
// assign light or dark brown color for checkered board pattern
if (tile.dataset.value != -1) { // bomb tiles are red
if (tile.classList.contains('grid-item-light')) {
tile.style.backgroundColor = 'rgb(255, 242, 171)'; // light
} else {
tile.style.backgroundColor = 'rgb(247, 207, 121)'; // dark
}
}
}
function getTextColor(num) {
switch(num) {
case 1:
return 'darkblue';
case 2:
return 'darkgreen';
case 3:
return 'darkred';
case 4:
return 'darkorchid';
case 5:
return 'darkorange';
case 6:
return 'darkcyan';
case 7:
return 'darkpink';
case 8:
return 'darkolivegreen';
case 9:
return 'darkslategrey';
}
}
function gameOver(winOrLose) {
document.getElementById('casual-bgm').play();
stopTimer();
const winLose = document.getElementById("win-lose-text");
const winLoseImage = document.getElementById("win-lose-image");
winLose.classList.remove('hidden');
winLoseImage.classList.remove('hidden');
const allTiles = document.querySelectorAll('.grid-item');
if (winOrLose === 'win') {
winLose.textContent = 'You Win!';
winLoseImage.src = 'art/you-win.png';
} else {
winLose.textContent = 'You Lose :(';
winLoseImage.src = 'art/you-lose.png';
// reveals all bomb tiles
allTiles.forEach(tile => {
if (tile.dataset.value === '-1') {
tile.innerHTML = '💣';
tile.style.backgroundColor = 'red';
}
});
}
document.getElementById('play-again-btn').classList.remove('hidden');
}
// BUTTONS
document.getElementById('play-again-btn').addEventListener('click', function() {
initializeBoard();
});
function switchScreens(fromScreen, toScreen) {
document.getElementById(fromScreen).classList.add('hidden');
document.getElementById(toScreen).classList.remove('hidden');
}
function switchAudio(fromAudio, toAudio) {
// pause and reset fromAudio
const fromAudioElement = document.getElementById(fromAudio);
fromAudioElement.pause();
fromAudioElement.currentTime = 0;
// stagger pause and play times so that audio reliably plays
// (avoids one audio task being prioritized over another)
setTimeout(() => {
const toAudioElement = document.getElementById(toAudio);
toAudioElement.play().then(() => {
if (callback) {
callback();
}
}).catch(error => {
console.error(`Failed to play ${toAudio}:`, error);
});
}, 100);
}
document.getElementById('start-game-btn').addEventListener('click', function() {
document.getElementById('title-bomb').classList.add('hidden');
document.getElementById('title-explosion').classList.remove('hidden');
switchAudio('casual-bgm', 'bomb-sound');
setTimeout(function() {
switchScreens('start-screen', 'game-screen');
initializeBoard();
}, 2000); // Wait for 2 seconds
});
document.getElementById('home-to-rules-btn').addEventListener('click', function() {
switchScreens('start-screen', 'rules-screen');
});
document.getElementById('rules-to-home-btn').addEventListener('click', function() {
switchScreens('rules-screen', 'start-screen');
});
document.getElementById('home-to-credits-btn').addEventListener('click', function() {
switchScreens('start-screen', 'credits-screen');
});
document.getElementById('credits-to-home-btn').addEventListener('click', function() {
switchScreens('credits-screen', 'start-screen');
});
document.getElementById('game-to-home-btn').addEventListener('click', function() {
document.getElementById('title-explosion').classList.add('hidden');
document.getElementById('title-bomb').classList.remove('hidden');
switchAudio('game-bgm', 'casual-bgm');
switchScreens('game-screen', 'start-screen');
});