forked from tony-luisi/minesweeper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminesweeper.js
348 lines (302 loc) · 10.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
// ***********************************************************
// minesweeper.js
// Author: Anthony McGrath
// Copyright: 07/07/2020
// ***********************************************************
document.addEventListener('DOMContentLoaded', startGame)
//*************************************************************
// Global Variables
//*************************************************************
var board = {
cells: [] // cells[]
}; // board{}
var gameLevel = 4; // Default Difficulty level. Can be between 2-6
var double = false; // Switch for handling dual click
var activeCell; // Placeholder for storing current active cell on dual click
// End Globals
//*************************************************************
// Game board generation
//*************************************************************
function startGame () {
// Perform game initialisation
mineCount = generateBoard(gameLevel); // Generate game board return # mines
showMineCount(mineCount); // Update flag count
board.cells.forEach(cell => { // Populate cell mine count
cell.surroundingMines = countSurroundingMines(cell);
}); // ForEach
// Don't remove this function call: it makes the game work!
lib.initBoard()
// Add global Event Listeners
document.addEventListener('keydown', validateKeyPress);
document.getElementById('reset').addEventListener('click', resetGame);
document.getElementById('easier').addEventListener('click', changeDifficulty);
document.getElementById('harder').addEventListener('click', changeDifficulty);
document.getElementById('showInstructions').addEventListener('click', toggleInstructions);
document.getElementById('hideInstructions').addEventListener('click', toggleInstructions);
// Add game play listeners
addGameListeners();
} // startGame()
// Function to reset game
function resetGame(){
board.cells = [];
document.getElementsByClassName('board')[0].innerHTML = " ";
startGame();
} // resetGame()
function countSurroundingMines(cell) {
// Count surrounding mines
// Update cell object
let surrounding = lib.getSurroundingCells(cell.row, cell.col);
let count=0;
surrounding.forEach(mine => {
if (mine.isMine) count++;
}); // foreach
return count;
} // countSurroundingMines(cell)
function getBoardChildren(){
return document.getElementsByClassName('board')[0];
} // getBoardChildren()
function addGameListeners(){
let gameBoard = getBoardChildren();
for (let i = 0; i < gameBoard.children.length; i++){
gameBoard.children[i].addEventListener('mousedown', checkClick);
gameBoard.children[i].addEventListener('mouseup', checkClick);
} // for
} // addGameListeners()
function removeGameListeners(){
let gameBoard = getBoardChildren();
for (let i = 0; i < gameBoard.children.length; i++){
gameBoard.children[i].removeEventListener('mousedown', checkClick);
gameBoard.children[i].removeEventListener('mouseup', checkClick);
} // for
} // removeGameListeners
function generateBoard(level){
for (let i = 1; i <= level; i++){
for (let j = 1; j <= level; j++){
board.cells.push({
"row": i,
"col": j,
"isMine": false,
"hidden": true,
"isMarked": false
});
} // for column
} // for row
return addMines(level);
} // generateBoard(level)
function addMines(level){
let maxMines = 0;
let mineLocations = [];
let col = 0;
let row = 0;
let needle = "";
let cellInx = 0;
// Determine maximum number of mines that should be present
switch(level){
case 2:
maxMines = 1;
break;
case 3:
maxMines = 3;
break;
case 4:
maxMines = 5;
break;
case 5:
maxMines = 9;
break;
case 6:
maxMines = 12;
break;
} // Switch(level)
// Allocate Mines to board
for(let i = 0; i < maxMines; i++){
col = Math.ceil(Math.random() * level);
row = Math.ceil(Math.random() * level);
needle = col + ":" + row;
if (mineLocations.indexOf(needle) > -1) {
i--; // Pretend loop never happened if mine exists already
} else {
cellInx = getThisCellIndex(col, row);
board.cells[cellInx].isMine = true;
mineLocations.push(needle);
} // if
} // for
return maxMines;
} // addMines(level)
function getThisCellIndex(col, row){
return row * gameLevel + col - gameLevel -1;
} // getThisCellIndex(col, row)
function showMineCount(mineCount){
if (mineCount < 0){
document.getElementById("notes").innerHTML = '<p class="warn"><img src="images/redflag.png" alt="marks" class="hint"> = ' + mineCount + '</p>';
} else {
document.getElementById("notes").innerHTML = '<p class="hint"><img src="images/flag.png" alt="marks" class="hint"> = ' + mineCount + '</p>';
} // if-else
} // showMineCount(mineCount)
//*************************************************************
// Key Presses / Associated Functions
//*************************************************************
function validateKeyPress(evt){
// Process Key Presses
if (evt.key == "F2") resetGame();
if (evt.key == "i") toggleInstructions();
if (evt.key == "-" || evt.key == "_" || evt.key == "+" || evt.key == "=") changeDifficulty(evt);
}
function changeDifficulty(evt){
if (evt.target.id == "easier" || evt.key == "-" || evt.key == "_"){
// Reduce Game Level
if (gameLevel > 2) {
gameLevel--;
} else {
alert("It can't go any easier, there's only 1 bomb!");
} // if-else
} else if (evt.target.id == "harder" || evt.key == "+" || evt.key == "=") {
// Increase Game Level
if (gameLevel < 6) {
gameLevel++;
} else {
alert("You're too good for me!");
} // if-else
} // if-elseif
resetGame();
} // changeDifficulty(evt)
//*************************************************************
// Mouse Clicks / Associated Functions
//*************************************************************
function checkClick(evt){
// Handle dual click
if (evt.buttons == 3 && evt.type == 'mousedown' && double == false) {
// Both mouse buttons down, indicate surrounding cells
double = true;
hint(evt);
} else if (evt.type == 'mouseup' && double == true) {
// Both mouse buttons up, process reveal
double = false;
showUnmarked(evt);
checkForWin(evt);
} // if-elseif
}
function showUnmarked(evt){
let count = 0;
let cell = activeCell;
let surrounding = lib.getSurroundingCells(cell.row, cell.col);
surrounding.forEach(cellCount =>{
if(cellCount.isMarked) count++;
toggleIndication(cellCount, evt);
});
if (count == cell.surroundingMines){
surrounding.forEach(surrCell => {
if (surrCell.isMarked == false){
showThisCell(surrCell, evt);
}
});
}
}
function hint(evt){
// Store event cell to handle pending mouseup event later on
activeCell = getCell(evt);
// indicate surrounding hidden cells on dual click with class
let cell = activeCell;
let surrounding = lib.getSurroundingCells(cell.row, cell.col);
surrounding.forEach(surrCell => {
if (surrCell.isMarked == false){
toggleIndication(surrCell, evt);
} // if
}) // forEach(surrCell)
} // hint(evt)
function toggleIndication(cell, evt) {
// Add / Remove class indicated on specified cell
if (cell.isMarked == false && cell.hidden == true){
let cellClass = "msRow-" + cell.row + " msCol-" + cell.col;
let currCell = document.getElementsByClassName(cellClass)[0];
if (evt.type == 'mousedown'){
currCell.classList.add('indicated')
} else if (evt.type == 'mouseup'){
currCell.classList.remove('indicated')
} // if-elseif
} // if
} // toggleIndication(cell, evt)
// function to play sounds
function playAudio(id){
document.getElementById(id).play();
} // playAudio(id)
//*************************************************************
// Cell Functions
//*************************************************************
function getCell(evt){
// Return the clicked cell's object
let row = parseInt(evt.target.classList[0].substr(6));
let col = parseInt(evt.target.classList[1].substr(6));
let idx = getThisCellIndex(col, row);
return board.cells[idx];
} // getCell(evt)
function showThisCell (cell, evt) {
// Update Cell Properties
cell.hidden = false;
cell.isMarked = false;
// Find DOM object based on row / col class
let cellClass = "msRow-" + cell.row + " msCol-" + cell.col;
let currCell = document.getElementsByClassName(cellClass)[0];
// Update DOM Object class
currCell.classList.remove('hidden');
currCell.classList.remove('marked');
// handle if cell is a mine / select audio cue
if (cell.isMine == true) {
playAudio('bomb');
displayMessage('BOOM!');
revealMines(evt);
removeGameListeners();
return;
} else {
playAudio('click');
} // if-else
// Update cell contents
setInnerHTML(cell)
if (cell.surroundingMines === 0) {
showSurrounding(evt.target)
} // if
} // showThisCell(cell, evt)
function checkForWin () {
// Check current board state
// evaluate win condition not met
// Win conditions:
// - All non mine cells revealed
// - Mines do not need to be marked
let loseCondition = false;
board.cells.forEach(cell => {
if (loseCondition == true) return;
// If Any non Mine Cell is not hidden Pass
if (cell.isMine == false && cell.hidden == true) {
loseCondition = true;
};
}) // forEach
if (loseCondition == true) return;
// No lose condition found, game won.
board.cells.forEach(cell => {
if (cell.isMine == true){
markOnWin(cell);
}
})
lib.displayMessage('You win!');
playAudio('win');
} // checkForWin()
function markOnWin(cell){
// Mark all mines on win!
let mineClass = "msRow-" + cell.row + " msCol-" + cell.col;
let mine = document.getElementsByClassName(mineClass);
mine[0].classList.add('mine');
mine[0].classList.add('win');
mine[0].classList.remove("hidden");
mine[0].classList.remove("marked");
} // checkForWin()
//*************************************************************
// Help Functions
//*************************************************************
function toggleInstructions(){
console.log(instructions.style.display);
if (instructions.style.display === "none"){
instructions.style.display = "block";
} else {
instructions.style.display = "none";
}
} // toggleInstructions()