-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmine_clearance.js
More file actions
80 lines (66 loc) 路 1.72 KB
/
Copy pathmine_clearance.js
File metadata and controls
80 lines (66 loc) 路 1.72 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
// tags: #math #game
/**
* generating a mine clearance board
* @param {number} m - row
* @param {number} k - mines
*/
class MC {
#board;
constructor(m, n, k) {
this.m = m;
this.n = n;
this.k = k;
this.generate();
}
generate() {
this.#board = [...Array(this.m)].map(() => Array(this.n).fill("."));
this.#setMine();
this.#setNumber();
}
#setMine() {
const { m, n } = this;
let { k } = this;
for (let row = 0; row < m; row++) {
for (let col = 0; col < n; col++) {
if (k / (m * n - (row * n + col)) >= Math.random()) {
this.#board[row][col] = "X";
k--;
}
}
}
}
#setNumber() {
const { m, n } = this;
for (let row = 0; row < m; row++) {
for (let col = 0; col < n; col++) {
if (this.#board[row][col] !== "X") {
this.#board[row][col] = this.#mineCount(row, col);
}
}
}
}
#mineCount(row, col) {
let count = 0;
if (row - 1 >= 0) {
col - 1 >= 0 && this.#isMine(row - 1, col - 1) && count++;
this.#isMine(row - 1, col) && count++;
col + 1 < this.n && this.#isMine(row - 1, col + 1) && count++;
}
col - 1 >= 0 && this.#isMine(row, col - 1) && count++;
col + 1 < this.n && this.#isMine(row, col + 1) && count++;
if (row + 1 < this.m) {
col - 1 >= 0 && this.#isMine(row + 1, col - 1) && count++;
this.#isMine(row + 1, col) && count++;
col + 1 < this.n && this.#isMine(row + 1, col + 1) && count++;
}
return count;
}
#isMine(row, col) {
return this.#board[row][col] === "X";
}
getBoard() {
return this.#board.map((row) => row.join(" ")).join("\n");
}
}
const mc = new MC(10, 10, 10);
console.log(mc.getBoard());