-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
108 lines (100 loc) · 2.62 KB
/
main.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
let gameWidth;
let gameHeight;
let mines;
let minefield;
let numLoops = 0;
startGame = () => {
numLoops = 0;
gameHeight = Number(document.getElementById("height").value);
gameWidth = Number(document.getElementById("width").value);
mines = Number(document.getElementById("mines").value);
createMinefieldObject();
renderGame();
console.log(numLoops);
};
const createMinefieldObject = () => {
minefield = [];
let minesToPlace = mines;
let squares = gameWidth * gameHeight;
for (let i = 0; i < gameHeight; i++) {
numLoops++;
let minefieldRow = new Array(gameWidth).fill("");
minefield.push(minefieldRow);
}
minefield.forEach((row, yIndex) => {
row.forEach((square, xIndex) => {
numLoops++;
let likelihoodOfPlacingMine = minesToPlace / squares;
if (likelihoodOfPlacingMine >= Math.random()) {
minefield[yIndex][xIndex] = "X";
minefield = addHintsToMinefieldObject(minefield, {
x: xIndex,
y: yIndex
});
minesToPlace--;
}
squares--;
});
});
};
const addHintsToMinefieldObject = (minefieldObject, coordinates) => {
for (let y = coordinates.y - 1; y <= coordinates.y + 1; y++) {
for (let x = coordinates.x - 1; x <= coordinates.x + 1; x++) {
numLoops++;
if (
x >= 0 &&
y >= 0 &&
x < gameWidth &&
y < gameHeight &&
minefieldObject[y][x] !== "X"
) {
minefieldObject[y][x] = +minefieldObject[y][x] + 1;
}
}
}
return minefieldObject;
};
const renderGame = () => {
let gameArea = document.getElementById("game-area");
let gameHtml = "";
let gameAreaStyle = "";
minefield.forEach((row, yIndex) => {
let gameLine = "";
row.forEach((square, xIndex) => {
gameHtml += generateSquareHTML(square, xIndex, yIndex);
gameLine += `y${yIndex}x${xIndex} `;
});
gameAreaStyle += `"${gameLine.trim()}" `;
});
gameArea.innerHTML = gameHtml;
gameArea.style = `grid-template-areas: ${gameAreaStyle}`;
};
const generateSquareHTML = (text, x, y) => {
let colorStyle = "";
switch (text) {
case 1:
colorStyle = "color:blue";
break;
case 2:
colorStyle = "color:green";
break;
case 3:
colorStyle = "color:red";
break;
case 4:
colorStyle = "color:purple";
break;
case 5:
colorStyle = "color:maroon";
break;
case 6:
colorStyle = "color:turquoise";
break;
case 8:
colorStyle = "color:gray";
break;
default:
break;
}
return `<div class=\"mine-section\" id="y${y}x${x}" style="grid-area:y${y}x${x};${colorStyle}">${text}</div>`;
};