-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
828 lines (583 loc) · 22.8 KB
/
game.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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
//initialise variables
var gameBoard = [];
//init revealed array
var revealed = [];
//size of board in concentric hexs
var size = 9;
//Hexagon cell sizes
var hexW = 25;
//Given hex width calculate other parameters of hexagon
//Hex edge length
var hexE = hexW / Math.sqrt(3);
//Hex height
var hexH = hexE * 2;
//Border margin between cells
var hexMargin = 5;
//size of longest row
var sizeHex = size * 2 - 1
//calculates total number of valid cells
var cellTotal = 1;
for (i = 1; i < size; i++) {
cellTotal += i * 6
}
//percentage of available cells mines
var minePercent = 20;
//Array to contain positions of mines
var minePos = [];
//calc number of mines
var numOfMines = Math.floor(cellTotal * (minePercent / 100));
//determines if odd or even rows are offset
var margin = (size + 1) % 2; // 1 if 1st row needs offset
//Var to track if first reveal
var firstCell = true;
//Variable to track if game is in progress or not
var acceptAnswer = false;
//variable to track if player won game at game end event
var wonGame = false;
//track if CTRL key is down
var ctrDown = false;
//to deal with rapid triggering of keypress event
var lastCtrDown = false;
//to track which cell mouse is over
var hover = [];
//track which is highlighted
var highlighted= [];
//Generate board based on size
generateGameBoard = (sizeHex) => {
for (i = 0; i < sizeHex; i++) {
//initialise rows
gameBoard.push([]);
//determine how many valid cells are in each row
cellsInRow = (sizeHex) - (Math.abs(size - 1 - i));
//pushes number of valid cells to row
for (j = 0; j < cellsInRow; j++) {
gameBoard[i].push(0);
}
//pushes null for non valid cells to row.
//Alternates add to start or add to end depending on margin and row num
for (j = 0; j < sizeHex - cellsInRow; j++) {
if ((margin + i + j) % 2) {
gameBoard[i].push(null);
} else {
gameBoard[i].unshift(null);
}
}
}
//generate revealed mat to track which cells have been revealed
revealed = [];
for (i = 0; i < gameBoard.length; i++) {
revealed.push([]);
for (j = 0; j < gameBoard.length; j++) {
revealed[i].push(gameBoard[i][j]);
}
}
}
//Fill board with mines
generateGameMines = (firsti, firstj) => {
//init positions array
minePos = [];
//determines reletive index number of above/below row before
var offsetMin = (firsti + margin + 1) % 2;
//determines relative index number of above/below cell after
var offsetPlus = (firsti + margin) % 2;
//list of available cells to randomly pick where mines are
var availableCells = []
//itirates through gameboard and adds valid cells to available cells array
for (i = 0; i < gameBoard.length; i++) {
for (j = 0; j < gameBoard.length; j++) {
//doesn't add first click or surrounding cells to available cells array to make initial gameplay easier
if(gameBoard[i][j] != null &&
!(i == firsti && j == firstj) &&
!(i == firsti && j == firstj+1) &&
!(i == firsti && j == firstj-1) &&
!(i == firsti-1 && j == firstj - offsetMin) &&
!(i == firsti-1 && j == firstj + offsetPlus) &&
!(i == firsti+1 && j == firstj-offsetMin) &&
!(i == firsti+1 && j == firstj+offsetPlus)){
//init valid co-ordinate
var validij = [];
//if a valid co-ord then push to i j array
validij.push(i);
validij.push(j);
//push array to available cells array
availableCells.push(validij);
}
}
}
//Choosing random cell index and adding to list of where mines are
for (i = 0; i < numOfMines; i++) {
//Generate rand based on what's left in available cells
var rand = Math.floor(Math.random() * availableCells.length);
//Addes to array
minePos.push(availableCells[rand]);
//Delete picked cell from available cells
availableCells.splice(rand, 1);
}
//Calls fill gameboard fn
fillGameMines();
}
//Update board with mines
fillGameMines = () => {
//for each i,j pair in miePos array change gameboard co-ord to a mine (x)
minePos.forEach(mineCoord => {
gameBoard[mineCoord[0]][mineCoord[1]] = "x";
});
//when all added calculate surrounding mines for each alid cell
calculateSurroundCells();
}
//calculate number of surrounging mines for each cell
calculateSurroundCells = () => {
//itirate through gameboard array
for (i = 0; i < gameBoard.length; i++) {
for (j = 0; j < gameBoard.length; j++) {
var surround = getSurround(i, j);
//if a valid cell and not a mine start calculation
if (gameBoard[i][j] != null && gameBoard[i][j] != "x") {
//start count at 0
var count = 0;
surround.forEach( countMines = (cell) => {
if(gameBoard[cell[0]][cell[1]] == "x"){count++}
});
//Set cell to surrounding mine #
gameBoard[i][j] = count;
}
}
}
printBoardConsole();
}
//logs gameboard to console in readable form
printBoardConsole = () => {
//init output string
var boardString = "";
for (i = 0; i < gameBoard.length; i++) {
//adds indent if printing an offset row
boardString += ((margin + i) % 2) == 1 ? " " : "";
//prints row. If null prints .
for (j = 0; j < gameBoard.length; j++) {
boardString += gameBoard[i][j] == null ? ". " : gameBoard[i][j] + " ";
}
//go to next line
boardString += '\n'
}
//display output
console.log(boardString);
}
//fn to create page elements
printBoardToPage = () => {
//itirate through gameboard
for (i = 0; i < gameBoard.length; i++) {
for (j = 0; j < gameBoard.length; j++) {
//if it's a cell, create element on page
if (gameBoard[i][j] != null) {
// Creates a cell at the correct position. Rows are 3/4 the height of a hex down + the vertical distance to create the correct margin between two angled lines
//Horizontal position is index * hex width + the extra on the start if it's an offset row.
createCellHex((.75 * hexH + (hexMargin / Math.cos(((2 * Math.PI / 360) * 30)))) * i, j * (hexW + hexMargin) + ((i + margin) % 2) * ((hexW + hexMargin) / 2), i, j);
}
}
}
}
//Creates hexagons given x pos, y pos and cell index
createCellHex = (x, y, indexi, indexj) => {
//initialise div
var newHex = document.createElement('div');
//Assign class name
newHex.classList.add("hexagon");
//init top and bottom triangles
var hexTop = document.createElement('div');
var hexBottom = document.createElement('div');
//classes to make divs look like triangles
hexTop.classList.add("hexTop");
hexBottom.classList.add("hexBottom");
//Set position
newHex.style.cssText = `top:${x}px;left:${y}px`;
//Set index
newHex.setAttribute("data-indexi", indexi);
newHex.setAttribute("data-indexj", indexj);
//Add click event
newHex.addEventListener("click", e => {
//if clicked pass the i and j co-ord to reveal handling fn
var i = Number(e.currentTarget.dataset["indexi"]);
var j = Number(e.currentTarget.dataset["indexj"]);
//calls reveal fn for cell
revealCell(i, j);
if(revealed[i][j] == 1 && acceptAnswer && gameBoard[i][j] > 0 && ctrDown){
revealAllSurround(i, j);
}
});
newHex.addEventListener("mouseenter", e => {
//get i and j of mouse over
var i = e.target.dataset.indexi;
var j = e.target.dataset.indexj;
hover[0] = i;
hover[1] = j;
highlightRevealSurround();
});
newHex.addEventListener("mouseleave", e => {
//get i and j of mouse over
var i = e.target.dataset.indexi;
var j = e.target.dataset.indexj;
//set hover to nothing on mouse leave
hover = [];
highlightRevealSurround();
});
//Adding right-click event
newHex.addEventListener("contextmenu", e => {
//Calls toggle flag fn for cell
toggleFlag(e.currentTarget.dataset.indexi, e.currentTarget.dataset.indexj);
//Prevents the option menu coming up on right-click
e.preventDefault();
}, false);
//adds top and bottom triangles as children
newHex.appendChild(hexTop);
newHex.appendChild(hexBottom);
//Attach to document
document.getElementById("gamecontainer").appendChild(newHex);
}
//Reveal cell method
revealCell = (i, j) => {
//if it's the first cell clicked then fill the board with mines except cell clicked and surrounding
if(firstCell == true){
generateGameMines(i, j);
firstCell = false;
}
//if cell hasn't been revealed before and accepting answers
if (revealed[i][j] == 0 && acceptAnswer) {
//Sets revealed to 1 so fn can't run again
revealed[i][j] = 1;
//finds cell element on page
cell = findCell(i, j);
//Sets colour to change elements to. lightblue if number or red if mine
var cellColor = gameBoard[i][j] >= 0 ? "#4d8eff" : "#ff5252";
//adds number to cell or a dot if it's a mine, nothing if it has no surrounding mines
cell.innerHTML += gameBoard[i][j] > 0 ? gameBoard[i][j] : gameBoard[i][j] == "x" ? "●" : "";
//if clicked on a mine cell
if (gameBoard[i][j] == "x") {
//Trigger endgame events
endGame();
}
//Change the three elements of the hexagon to the colour
cell.style.backgroundColor = cellColor
cell.querySelector('.hexTop').style.borderBottomColor = cellColor;
cell.querySelector('.hexBottom').style.borderTopColor = cellColor;
}
//if it's a cell with no surrounging mines reveal self and all surrounging cells
if (gameBoard[i][j] == 0 && acceptAnswer) {
//init surroung array
var surround;
//gets surrounding points from fn
surround = getSurround(i,j);
//for each pair of surround coords do stuff
surround.forEach(cell => {
//if it hasn't been revealed
if(revealed[cell[0]][cell[1]] != 1){
// if it's a flag toogle flag to remove
if (revealed[cell[0]][cell[1]] == 2) { toggleFlag(cell[0], cell[1]) }
//call reveal cell on specific cell
revealCell(cell[0], cell[1]);
}
});
}
//calls check complere fn. if true i.e. player has won then do stuff
if(checkComplete()){
wonGame = true;
//end game
endGame();
};
}
//check if all cells that don't contain mines have been revealed i.e. game over and player has won
checkComplete = () => {
//itirate through game board
for(i = 0; i < gameBoard.length; i++){
for(j = 0; j < gameBoard.length; j++){
//if it's a valid cell that's not a mine and hasn't been revealed
if(gameBoard[i][j] != null && gameBoard[i][j] != "x" && revealed[i][j] != 1){
//still cells left to reveal so return false
return false;
}
}
}
//if iterated through all cells and all valids and non mines have been revealed then game is complete i.e. return true
return true;
}
//fn to add/remove flags
toggleFlag = (i, j) => {
//if game is in progress then do stuff
if(acceptAnswer){
//if the cell hasn't been revealed and there's no flag present
if (revealed[i][j] == 0 && revealed[i][j] != 2) {
//Need to update to use find cell fn
//iterate throguh page elements to find corresponding element
document.querySelectorAll(".hexagon").forEach(cell => {
//when found
if (cell.dataset.indexi == i && cell.dataset.indexj == j) {
//create div
var flagDiv = document.createElement('div');
//Add class that makes it look like a flag
flagDiv.classList.add('flag');
//append as child to page element
cell.appendChild(flagDiv);
//Change reveald to 2
revealed[i][j] = 2;
}
});
//If cell already has a flag on it
} else if (revealed[i][j] == 2) {
//find corresponding page element
document.querySelectorAll(".hexagon").forEach(cell => {
//when found correct one
if (cell.dataset.indexi == i && cell.dataset.indexj == j) {
//finds flag div in cell and removes it
cell.removeChild(cell.querySelector('.flag'));
//change revealed indicator back to 0
revealed[i][j] = 0;
}
})
}
}
}
//fn to reveal all surroung
revealAllSurround = (i, j) => {
//gets surrounding cell of cell clicked
var surround = getSurround(i, j);
//Initialises flag count to 0
var flagCount = 0
//For each surrounding cell coord
surround.forEach(coord => {
//restructure
var coodi = coord[0];
var coodj = coord[1];
//if there's a flag in a surround cell increase flag count
if(revealed[coodi][coodj] == 2){flagCount++};
});
//if all mines are accounted for i.e. flag count = num of surrounging mines
if(flagCount == gameBoard[i][j]){
//Reveal each surrounding cell
surround.forEach(coord => {
coordi = coord[0];
coordj = coord[1];
//calls reveal cell method
revealCell(coordi, coordj);
})
}
}
//fn to highlight surround cells when ctrl held down
highlightRevealSurround = () => {
//if there are already cells highlighted
if (highlighted.length){
//restructure
i = highlighted[0];
j = highlighted[1];
//Gets surrounding cells to revert back to normal colour
var surroundRevert = getSurround(i, j);
//iterate through surround cells
surroundRevert.forEach(coordRevert => {
//restructure
var surroundReverti = coordRevert[0];
var surroundRevertj = coordRevert[1];
//if cell isn't revealed, changes colour back to regular blue
if(revealed[surroundReverti][surroundRevertj] == 0){
//finds cell in page
var revertCell = findCell(surroundReverti, surroundRevertj);
//colour to change cell to
var normalColour = "#0A5CE8"
//change cell elements to normal colour
revertCell.style.backgroundColor = normalColour;
revertCell.querySelector('.hexTop').style.borderBottomColor = normalColour;
revertCell.querySelector('.hexBottom').style.borderTopColor = normalColour;
}
});
//Empties highlighted tracker
highlighted = [];
//Else if there are no cells highlighted
} else {
//if ctrl held down, game in progress and there is a cell being hovered over
if(acceptAnswer && ctrDown && hover.length){
//restructure hovered cell coords
var i = hover[0];
var j = hover[1];
//if cell is revealed and it's not a number (not an empty cell)
if(revealed[i][j] == 1 && gameBoard[i][j] > 0) {
//gets surrounging cells for cell hovered
var surround = getSurround(i, j);
//for each surrounging cell
surround.forEach(coord => {
//restructure to get cell coords
var surroundi = coord[0];
var surroundj = coord[1];
//if the surround cell isn't revealed
if (revealed[surroundi][surroundj] == 0) {
//find cell in the page
var cell = findCell(surroundi, surroundj);
//colour to change to highlight colour
var highlightColour = "#70a4ff"
//highlight cells and elements
cell.style.backgroundColor = highlightColour;
cell.querySelector('.hexTop').style.borderBottomColor = highlightColour;
cell.querySelector('.hexBottom').style.borderTopColor = highlightColour;
}
});
//Add cell to highlighted tracker var
highlighted[0] = i;
highlighted[1] = j;
}
}
}
}
//fn to reveal remaining unfound mines in random order. Also puts X on wrong flags
revealMines = () => {
//init arays to contain coords
var minesUnfound = [];
var wrongFlags = [];
//interate through game board
for(i = 0; i < gameBoard.length; i++){
for(j = 0; j < gameBoard.length; j++){
//if cell is a mine and not revealed
if(gameBoard[i][j] == "x" && revealed[i][j] == 0){
//push coords to unfound mines array
minesUnfound.push([i, j]);
//if cell has a flag but is NOT a mine
} else if(revealed[i][j] == 2 && gameBoard[i][j] != "x"){
//push coors to wrong flags array
wrongFlags.push([i, j]);
}
}
}
//fn that will reveal a random mine
delayRevealMines = () => {
//if length is not 0, i.e. there are still mines to reveal
if (minesUnfound.length) {
//generate random number for mine to display
var rand = Math.floor(Math.random() * minesUnfound.length);
//finds cell on page given i and j
var cell = findCell(minesUnfound[rand][0], minesUnfound[rand][1]);
//adds dot to cell
cell.innerHTML += "●";
//removes coord from remaining unrevealed cells
minesUnfound.splice(rand, 1);
//calls fn again with 150ms delay
setTimeout(delayRevealMines, 150);
//if all mines are revealed skip to crossing flags
} else {
delayRevealFlags();
}
}
//Flag reveal Fn
delayRevealFlags = () => {
//if there are flags to reveal
if (wrongFlags.length) {
//generate rand number for flag to reveal
var rand = Math.floor(Math.random() * wrongFlags.length);
//finds cell in page
var cell = findCell(wrongFlags[rand][0], wrongFlags[rand][1]);
//creates X element
var newX = document.createElement('div');
//adds styling
newX.classList.add('flagcross');
//Adds to page
cell.appendChild(newX);
//removes self from coords array
wrongFlags.splice(rand, 1);
//call fn again recursively
setTimeout(delayRevealFlags, 150);
}
//if you completed the game, alert
if(wonGame){alert("You Won!")}
}
//call cascade to reveal mines then reveal flags
delayRevealMines();
}
//fn to get surrounding cells given i j value
getSurround = (i, j) => {
//Just to ensure i and j values are numbers
i = Number(i);
j = Number(j);
var output = [];
//determines reletive index number of above/below row before
var offsetMin = (i + margin + 1) % 2;
//determines relative index number of above/below cell after
var offsetPlus = (i + margin) % 2;
if (gameBoard[i][j] != null) {
//if not at edge
if (j - 1 >= 0) {
if (gameBoard[i][j - 1] != null) { output.push([i, j - 1]) }
}
if (j + 1 <= gameBoard.length - 1) {
if (gameBoard[i][j + 1] != null) { output.push([i, j + 1]); }
}
if (i - 1 >= 0) {
if (j - offsetMin >= 0) {
if (gameBoard[i - 1][j - offsetMin] != null) { output.push([i - 1, j - offsetMin]); }
}
if (j + offsetPlus <= gameBoard.length - 1) {
if (gameBoard[i - 1][j + offsetPlus] != null) { output.push([i - 1, j + offsetPlus]); }
}
}
if (i + 1 <= gameBoard.length - 1) {
if (j - offsetMin >= 0) {
if (gameBoard[i + 1][j - offsetMin] != null) { output.push([i + 1, j - offsetMin]); }
}
if (j + offsetPlus <= gameBoard.length - 1) {
if (gameBoard[i + 1][j + offsetPlus] != null) { output.push([i + 1, j + offsetPlus]); }
}
}
}
return output;
}
//fn to find cell elements on page given i j
findCell = (i, j) => {
//init return var
var cellToReturn;
//finds all hexes on page
document.querySelectorAll(".hexagon").forEach(cell => {
//if cell is the one being looked for
if(cell.dataset.indexi == i && cell.dataset.indexj == j){
//get ready to return
cellToReturn = cell;
}
});
//return cell
return cellToReturn;
}
//fns to call on game start
startGame = () => {
//calc board w and h
var boardWidth = sizeHex * (hexW + hexMargin) - hexMargin;
var boardHeight = sizeHex * (hexH * 0.75 + (hexMargin / Math.cos(((2 * Math.PI / 360) * 30))));
//Set height and width of container to correct values
document.querySelector('#gamecontainer').style.cssText = `height: ${boardHeight}px; width: ${boardWidth}px;`
//generates gameboard given size input
generateGameBoard(sizeHex);
//creates page elements
printBoardToPage();
//After things are generated start accepting answers
acceptAnswer = true;
//attach keydown listner to page
document.addEventListener("keydown", e => {
if (e.key == "Control") {
//change tracker to true on keydown
ctrDown = true;
if(lastCtrDown != ctrDown){
highlightRevealSurround();
}
lastCtrDown = true;
}
})
//attach keyup listner to page
document.addEventListener("keyup", e => {
if (e.key == "Control") {
//change tracker to false on keyup
ctrDown = false;
lastCtrDown = false;
highlightRevealSurround();
}
})
}
//Endgame events
endGame = () => {
//Stop accepting answers
acceptAnswer = false;
//Reveal mines
revealMines();
}
//Calls start game on page load
startGame();