-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
50 lines (47 loc) · 1.42 KB
/
script.js
File metadata and controls
50 lines (47 loc) · 1.42 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
const cellStatus = {
HIDDEN : "hidden",
MINE : "mine",
SAFE : "safe",
}
export function createBoard(boardSize, mineCount){
const board = [];
const minePositions = getMinePositions(boardSize, mineCount);
for(let x = 0; x < boardSize; x++){
const row = [];
for(let y = 0; y < boardSize; y++){
const element = document.createElement("div");
element.dataset.status = cellStatus.HIDDEN;
const cell = {
element,
x,
y,
mine: minePositions.some(positionMatch.bind(null, {x, y})),
get status(){
return this.element.dataset.status;
},
set status(value){
this.element.dataset.status = value;
},
}
row.push(cell);
}
board.push(row);
}
return board;
}
function getMinePositions(boardSize, mineCount){
const positions = [];
while(positions.length < mineCount){
const position = {
x: Math.floor(Math.random() * boardSize),
y: Math.floor(Math.random() * boardSize),
}
if(!positions.some(positionMatch.bind(null, position))){
positions.push(position);
}
}
return positions;
}
function positionMatch(a, b){
return a.x === b.x && a.y === b.y;
}