Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.js
More file actions
Latest commit
100 lines (88 loc) · 3.3 KB
/
Copy pathgame.js
File metadata and controls
100 lines (88 loc) · 3.3 KB
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
exportclassGame{
#rows
#columns
#numOfMines
#gridMeta
#isGameWon
#isGameOver
constructor(height,width,numOfMines,gridId){
this.#rows =height;
this.#columns =width;
this.#numOfMines =numOfMines;
this.#gridMeta =[];
this.buildBoard(gridId);
this.#isGameWon =false;
this.#isGameOver =false;
}
buildBoard(gridId){
consttable=document.querySelector(gridId);
constcellsToBeMined=[];
for(letrowIndex=0;rowIndex<this.#rows;rowIndex++){
constrow=document.createElement('tr');
table.appendChild(row);
this.#gridMeta.push([])
for(letcolIndex=0;colIndex<this.#columns;colIndex++){
constcell=document.createElement('td');
cell.innerText="⬛";
cell.dataset.number=0;
cell.dataset.bomb=false;
cell.dataset.revealed=false;
cell.addEventListener('contextmenu',event=>event.preventDefault(),false);
cell.addEventListener('mousedown',event=>{
if(event.button===0){
this.reveal(cell);
}elseif(event.button===2){
this.flag(cell);
}
});
cellsToBeMined.push({ rowIndex, colIndex, cell });
this.#gridMeta[rowIndex].push(cell);
row.appendChild(cell);
}
}
cellsToBeMined
.sort(()=>0.5-Math.random())
.slice(0,this.#numOfMines)
.forEach(cellData=>{
cellData.cell.dataset.bomb=true;
this.safeIncrement(cellData.rowIndex+1,cellData.colIndex);
this.safeIncrement(cellData.rowIndex+1,cellData.colIndex+1);
this.safeIncrement(cellData.rowIndex+1,cellData.colIndex-1);
this.safeIncrement(cellData.rowIndex-1,cellData.colIndex);
this.safeIncrement(cellData.rowIndex-1,cellData.colIndex+1);
this.safeIncrement(cellData.rowIndex-1,cellData.colIndex-1);
this.safeIncrement(cellData.rowIndex,cellData.colIndex+1);
this.safeIncrement(cellData.rowIndex,cellData.colIndex-1);
});
//this.revealAll();
}
safeIncrement(row,col){
if(row>=this.#rows ||col>=this.#columns ||row<0||col<0){
return;
}
this.#gridMeta[row][col].dataset.number++;
}
revealAll(){
this.#gridMeta.forEach(row=>
row.forEach(cell=>
this.reveal(cell)))
}
reveal(cell){
constnums=["🟦","1️⃣","2️⃣","3️⃣","4️⃣","5️⃣","6️⃣","7️⃣","8️⃣"];
if(cell.dataset.bomb==="true"&&this.#isGameWon){
cell.innerText="💣";
}elseif(cell.dataset.bomb==="true"){
cell.innerText="💥";
this.#isGameOver =true;
}else{
cell.innerText=nums[cell.dataset.number];
}
cell.dataset.revealed="true";
}
flag(cell){
if(cell.dataset.revealed==="true"){
return;
}
cell.innerText="🚩";
}
}