-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminesweeper.js
147 lines (118 loc) · 2.59 KB
/
minesweeper.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
var ROWS = 10;
var COLS = 10;
var MINES = 10;
var board = [];
var boardStatus = [];
var BLOCK_MINE = -1;
var BLOCK_CLOSED = 0;
var BLOCK_OPENED = 1;
var BLOCK_FLAGGED = 2;
var playing = true;
// https://www.youtube.com/watch?v=LRnnNInjmN0
// 32:19
function init() {
for (var x = 0; x < ROWS; x++) {
board[x] = [];
for (var y = 0; y < COLS; y++) {
board[x][y] = 0;
}
}
boardStatus = JSON.parse(JSON.stringify(board));
board = placeMines(board, MINES);
for (var x = 0; x < ROWS; x++) {
for (var y = 0; y < COLS; y++) {
if (board[x][y] !== BLOCK_MINE) {
board[x][y] = countAdjacentMines(x, y);
}
}
}
}
function countAdjacentMines(x, y) {
var mineCount = 0;
for (var i = x - 1; i <= x + 1; i++) {
for (var j = y - 1; j <= y + 1; j++) {
if (inBounds(i, j)) {
if (board[i][j] == BLOCK_MINE) {
mineCount++;
}
}
}
}
return mineCount;
}
function inBounds(x, y) {
return (x >= 0 && y >= 0 && x < ROWS && y < COLS);
}
function placeMines(board, numMines) {
var mine = 0;
while (mine < numMines) {
var x = Math.floor(Math.random() * ROWS);
var y = Math.floor(Math.random() * COLS);
if (board[x][y] !== BLOCK_MINE) {
board[x][y] = BLOCK_MINE;
mine++;
}
}
return board;
}
function flagBlock(x, y) {
if (!playing || boardStatus[x][y] == BLOCK_OPENED) {
return;
}
if (boardStatus[x][y] !== BLOCK_FLAGGED) {
boardStatus[x][y] = BLOCK_FLAGGED;
}
else {
boardStatus[x][y] = BLOCK_CLOSED
}
}
function openBlock(x, y) {
if (!playing || boardStatus[x][y] === BLOCK_FLAGGED) {
return;
}
if (board[x][y] == BLOCK_MINE) {
alert('Game over!');
playing = false;
revealBoard();
}
boardStatus[x][y] = BLOCK_OPENED;
if (board[x][y] == 0) {
// Flood fill.
for (var dx = -1; dx <= 1; dx++) {
for (var dy = -1; dy <= 1; dy++) {
var xx = x + dx;
var yy = y + dy;
if (inBounds(xx, yy)) {
if (boardStatus[xx][yy] != BLOCK_OPENED) {
openBlock(xx, yy);
}
}
}
}
}
if (checkVictory()) {
alert('You win!');
playing = false;
revealBoard();
}
}
function checkVictory() {
for (var x = 0; x < COLS; x++) {
for (var y = 0; y < ROWS; y++) {
if (board[x][y] !== BLOCK_MINE && boardStatus[x][y] !== BLOCK_OPENED) {
return false;
}
}
}
if (playing) {
return true;
}
}
function revealBoard() {
for (var x = 0; x < COLS; x++) {
for (var y = 0; y < ROWS; y++) {
boardStatus[x][y] = BLOCK_OPENED;
}
}
}
init();