-
Notifications
You must be signed in to change notification settings - Fork 0
/
minesweeper.js
614 lines (555 loc) · 16.2 KB
/
minesweeper.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
"use strict";
!(function (global) {
// CONSTANTS
const MINE = -1;
const EXPLODED = "💥";
const UNEXPLODED = "💣";
const FLAG = "🚩";
const INFINITY = "♾️";
const SQUARE_CLASSES = {
"-1": "mine",
"0": "empty",
"1": "one",
"2": "two",
"3": "three",
"4": "four",
"5": "five",
"6": "six",
"7": "seven",
"8": "eight"
};
const GAME_TYPES = {
BEGINNER: {
numRows: 8,
numColumns: 8,
numMines: 10
},
INTERMEDIATE: {
numRows: 16,
numColumns: 16,
numMines: 40
},
ADVANCED: {
numRows: 18,
numColumns: 32,
numMines: 99
}
};
const GAME_OVER_CLASSES = {
WIN: "winner",
LOSE: "loser"
};
// classes
class Timer {
constructor() {
this.timeElapsed = 0;
this.interval = null;
this.root = null;
this.tick = this.tick.bind(this);
}
init() {
// exit if we already have a reference to the root div
if (this.root) return;
this.root = document.getElementById("timer");
}
start() {
this.interval = setInterval(this.tick, 1000);
}
tick() {
this.timeElapsed++;
this.render();
}
stop() {
clearInterval(this.interval);
}
reset() {
this.stop();
this.timeElapsed = 0;
this.render();
}
static toTimeString(elapsed) {
const seconds = elapsed % 60;
const minutes = (elapsed - seconds) / 60;
const hours = (elapsed - seconds - minutes * 60) / 3600;
return `${hours ? `${hours}:` : ""}${`0${minutes}`.slice(
-2
)}:${`0${seconds}`.slice(-2)}`;
}
render() {
this.root.textContent = Timer.toTimeString(this.timeElapsed);
}
}
class StoredTimes {
constructor(gameType) {
this.gameType = gameType;
this.root = null;
this.bestTime = "♾️";
}
init() {
this.getBestTimeFromStorage();
if (this.root) return;
this.root = document.getElementById(
`best-time-${this.gameType.toLowerCase()}`
);
}
reset() {
this.getBestTimeFromStorage();
this.render();
}
getBestTimeFromStorage() {
let bestTime = Infinity;
const storedTimes = localStorage.getItem("bestTimes");
if (storedTimes) {
const parsed = JSON.parse(storedTimes);
bestTime = parsed[this.gameType] || Infinity;
}
this.bestTime =
bestTime < Infinity ? Timer.toTimeString(bestTime) : INFINITY;
}
setAndStoreBestTime(timeElapsed) {
const storedTimes = localStorage.getItem("bestTimes");
if (storedTimes) {
const parsed = JSON.parse(storedTimes);
if (!parsed[this.gameType]) {
parsed[this.gameType] = timeElapsed;
} else {
parsed[this.gameType] =
timeElapsed < parsed[this.gameType]
? timeElapsed
: parsed[this.gameType];
}
localStorage.setItem("bestTimes", JSON.stringify(parsed));
this.bestTime =
parsed[this.gameType] < Infinity
? Timer.toTimeString(parsed[this.gameType])
: INFINITY;
} else {
const bestTimes = {};
Object.keys(GAME_TYPES).forEach((type) => {
bestTimes[type] = type === this.gameType ? timeElapsed : Infinity;
});
localStorage.setItem("bestTimes", JSON.stringify(bestTimes));
this.bestTime =
bestTimes[this.gameType] < Infinity
? Timer.toTimeString(bestTimes[this.gameType])
: INFINITY;
}
this.render();
}
render() {
this.root.textContent = this.bestTime;
this.root.style.display = "block";
}
}
class Game {
constructor(gameType) {
this.root = null;
this.gameType = gameType;
// pass reference to this object down, so that game controls can respond to events down the chain
// an alternate approach would be to use the postMessage API or create custom Events
this.grid = new Grid({ ...GAME_TYPES[gameType], parent: this });
this.timer = new Timer();
this.storedTimes = new StoredTimes(gameType);
this.clicked = false;
this.gameover = false;
}
init() {
this.storedTimes.init();
this.grid.init();
this.timer.init();
// exit if we already have a reference to the root div
if (this.root) return;
this.root = document.getElementById("minesweeper");
this.root.addEventListener("click", (e) => {
e.preventDefault();
if (this.clicked || this.gameover) {
return;
}
this.timer.start();
this.clicked = true;
console.log("PLAYING!!!!");
});
}
start() {
this.init();
this.render();
}
end(className) {
this.gameover = true;
this.root.classList.add("game-over", className);
this.timer.stop();
console.log(`Time Elapsed: ${this.timer.timeElapsed} seconds.`);
if (className === GAME_OVER_CLASSES.WIN) {
this.storedTimes.setAndStoreBestTime(this.timer.timeElapsed);
}
}
reset(gameType) {
this.gameType = gameType;
this.grid.numRows = GAME_TYPES[gameType].numRows;
this.grid.numColumns = GAME_TYPES[gameType].numColumns;
this.grid.numMines = GAME_TYPES[gameType].numMines;
this.grid.flags.maxFlags = GAME_TYPES[gameType].numMines;
this.root.innerHTML = "";
this.root.classList.remove(
"game-over",
GAME_OVER_CLASSES.WIN,
GAME_OVER_CLASSES.LOSE
);
this.storedTimes.gameType = gameType;
this.gameover = false;
this.clicked = false;
this.grid.reset();
this.storedTimes.reset();
this.timer.reset();
this.render();
}
render() {
this.storedTimes.render();
const grid = this.grid.render();
grid.forEach((row) => this.root.appendChild(row));
}
}
class Flags {
constructor(maxFlags) {
this.flagsUsed = 0;
this.maxFlags = maxFlags;
this.root = null;
}
init() {
if (this.root) return;
this.root = document.getElementById("flags");
}
increment() {
this.flagsUsed++;
this.render();
}
decrement() {
this.flagsUsed--;
this.render();
}
reset() {
this.flagsUsed = 0;
}
render() {
this.root.textContent = `${this.maxFlags - this.flagsUsed} ${FLAG}`;
}
}
class Grid {
constructor({ numRows = 8, numColumns = 8, numMines = 10, parent }) {
this.grid = [];
this.numRows = numRows;
this.numColumns = numColumns;
this.numMines = numMines;
this.flags = new Flags(numMines);
// store reference to parent to call methods related to state
this.parent = parent;
}
init() {
this.flags.init();
this.generateGrid();
this.fillGridWithMines();
}
generateGrid() {
for (let rowCoord = 0; rowCoord < this.numRows; rowCoord++) {
const row = [];
for (let colCoord = 0; colCoord < this.numColumns; colCoord++) {
const square = new Square({ parent: this, rowCoord, colCoord });
row.push(square);
}
this.grid.push(row);
}
}
fillGridWithMines() {
let mines = 0;
while (mines < this.numMines) {
const [rowCoord, colCoord] = this.generateCoordinates();
if (this.grid[rowCoord][colCoord].value !== MINE) {
this.grid[rowCoord][colCoord].value = MINE;
mines++;
// Check for Edge Cases
if (rowCoord - 1 >= 0) {
// Row Above
this.grid[rowCoord - 1][colCoord].incrementValue();
}
if (colCoord - 1 >= 0) {
// Column to the Left
this.grid[rowCoord][colCoord - 1].incrementValue();
}
if (rowCoord + 1 !== this.numRows && colCoord - 1 >= 0) {
// Bottom Left Diagonal
this.grid[rowCoord + 1][colCoord - 1].incrementValue();
}
if (rowCoord - 1 >= 0 && colCoord - 1 >= 0) {
// Top Left Diagonal
this.grid[rowCoord - 1][colCoord - 1].incrementValue();
}
if (rowCoord + 1 !== this.numRows) {
// Row Below
this.grid[rowCoord + 1][colCoord].incrementValue();
}
if (colCoord + 1 !== this.numColumns) {
// Column to the Right
this.grid[rowCoord][colCoord + 1].incrementValue();
}
if (
rowCoord + 1 !== this.numRows &&
colCoord + 1 !== this.numColumns
) {
// Bottom Right Diagonal
this.grid[rowCoord + 1][colCoord + 1].incrementValue();
}
if (rowCoord - 1 >= 0 && colCoord + 1 !== this.numColumns) {
// Top Right Diagonal
this.grid[rowCoord - 1][colCoord + 1].incrementValue();
}
}
}
}
generateCoordinates() {
const rowCoord = Math.floor(Math.random() * this.numRows);
const colCoord = Math.floor(Math.random() * this.numColumns);
return [rowCoord, colCoord];
}
checkForWin() {
let win = true;
for (let row = 0; row < this.numRows; row++) {
for (let col = 0; col < this.numColumns; col++) {
if (
!this.grid[row][col].revealed &&
this.grid[row][col].value !== MINE
) {
win = false;
break;
}
}
}
return win;
}
revealAllAndUnMountEvents() {
this.grid.forEach((row) =>
row.forEach((square) => {
square.revealSquare();
square.removeClickHandler();
})
);
}
end(className) {
this.revealAllAndUnMountEvents();
this.parent.end(className);
}
reset() {
this.grid = [];
this.flags.reset();
this.init();
}
render() {
this.flags.render();
const rows = this.grid.map((row) => {
const rowEl = document.createElement("div");
rowEl.classList.add("row");
row.forEach((square) => {
rowEl.appendChild(square.render());
});
return rowEl;
});
return rows;
}
}
class Square {
constructor({ parent, rowCoord, colCoord }) {
this.revealed = false;
this.flagged = false;
this.value = 0;
this.rowCoord = rowCoord;
this.colCoord = colCoord;
this.root = null;
// store reference to parent to call methods related to state on parent and parent's parent
this.parent = parent;
}
setValue(value) {
this.value = value;
}
incrementValue() {
this.value = this.value === MINE ? this.value : this.value + 1;
}
handleClick(e) {
e.preventDefault();
if (
e.button === 2 ||
e.which === 3 ||
e.ctrlKey ||
this.root.textContent === FLAG
) {
this.toggleFlag();
return;
}
this.handleReveal();
}
handleRightClick(e) {
e.preventDefault();
this.toggleFlag();
}
handleReveal() {
if (this.revealed) {
return;
}
// check value
// respond to value
switch (this.value) {
case -1:
console.log("BOOM!!!!");
// BOOM
// Trigger UI
this.parent.end(GAME_OVER_CLASSES.LOSE);
this.root.classList.add("boom");
this.root.textContent = EXPLODED;
return;
case 0:
// trigger UI Update
this.revealSquare();
if (this.parent.checkForWin()) {
console.log("WINNER!!!!");
this.parent.end(GAME_OVER_CLASSES.WIN);
} else {
// reveal neighbors
this.revealNeighbors();
}
break;
default:
// trigger UI Update
this.revealSquare();
// check for Game Over
if (this.parent.checkForWin()) {
console.log("WINNER!!!!");
this.parent.end(GAME_OVER_CLASSES.WIN);
}
break;
}
}
checkForWin() {}
toggleFlag() {
// only toggle flag if there are flags remaining
if (
((this.parent.flags.flagsUsed < this.parent.flags.maxFlags &&
!this.flagged) ||
this.flagged) &&
!this.revealed
) {
this.flagged = !this.flagged;
this.root.textContent = this.flagged ? FLAG : "";
this.root.classList.toggle("flagged");
if (this.flagged) {
this.parent.flags.increment();
} else {
this.parent.flags.decrement();
}
}
}
removeClickHandler() {
this.root.removeEventListener("click", this.handleClick.bind(this));
this.root.removeEventListener(
"contextmenu",
this.handleRightClick.bind(this)
);
}
revealSquare() {
this.revealed = true;
const content = this.value === 0 ? "" : this.value;
this.root.textContent = this.value === MINE ? UNEXPLODED : content;
this.root.classList.remove("covered");
this.root.classList.remove("flagged");
this.root.classList.add(SQUARE_CLASSES[this.value.toString()]);
}
revealNeighbors() {
const { numColumns, numRows, grid } = this.parent;
if (this.rowCoord - 1 >= 0) {
// Row Above
grid[this.rowCoord - 1][this.colCoord].handleReveal();
}
if (this.colCoord - 1 >= 0) {
// Column to the Left
grid[this.rowCoord][this.colCoord - 1].handleReveal();
}
if (this.rowCoord + 1 !== numRows && this.colCoord - 1 >= 0) {
// Bottom Left Diagonal
grid[this.rowCoord + 1][this.colCoord - 1].handleReveal();
}
if (this.rowCoord - 1 >= 0 && this.colCoord - 1 >= 0) {
// Top Left Diagonal
grid[this.rowCoord - 1][this.colCoord - 1].handleReveal();
}
if (this.rowCoord + 1 !== numRows) {
// Row Below
grid[this.rowCoord + 1][this.colCoord].handleReveal();
}
if (this.colCoord + 1 !== numColumns) {
// Column to the Right
grid[this.rowCoord][this.colCoord + 1].handleReveal();
}
if (this.rowCoord + 1 !== numRows && this.colCoord + 1 !== numColumns) {
// Bottom Right Diagonal
grid[this.rowCoord + 1][this.colCoord + 1].handleReveal();
}
if (this.rowCoord - 1 >= 0 && this.colCoord + 1 !== numColumns) {
// Top Right Diagonal
grid[this.rowCoord - 1][this.colCoord + 1].handleReveal();
}
}
/**
* Renders UI for each Square, adds Click event listeners, and returns reference to Element
* @returns HTMLElement - Square
*/
render() {
const square = document.createElement("div");
square.classList.add("square", "covered");
square.textContent = "";
square.addEventListener("click", this.handleClick.bind(this));
square.addEventListener("contextmenu", this.handleRightClick.bind(this));
this.root = square;
return square;
}
}
// append Game to Global Object
if (typeof global.__MINESWEEPER !== Game) {
global.__MINESWEEPER = new Game("BEGINNER");
}
// check document.readyState to support asynchronous loading of this script
switch (document.readyState) {
case "loading":
document.addEventListener("DOMContentLoaded", initGame);
break;
default:
initGame();
break;
}
/**
* Will call start to Minesweeper Game
* Expects the following HTML structure
*
* <div class="controls">
* <button class="control-btn" id="beginner">Beginner</button>
* <button class="control-btn" id="intermediate">Intermediate</button>
* <button class="control-btn" id="advanced">Advanced</button>
* <div id="timer">00:00</div>
* <div id="flags">0 🚩</div>
* </div>
* <div class="game-container">
* <div id="minesweeper"></div>
* </div>
*/
function initGame() {
global.__MINESWEEPER.start();
const controlButtons = document.querySelectorAll(".control-btn");
controlButtons.forEach((button) =>
button.addEventListener("click", (e) => {
e.preventDefault();
const id = e.currentTarget.id.toUpperCase();
if (Object.keys(GAME_TYPES).includes(id)) {
global.__MINESWEEPER.reset(id);
} else {
global.__MINESWEEPER.reset("BEGINNER");
}
})
);
}
})(globalThis || window);