-
Notifications
You must be signed in to change notification settings - Fork 0
/
minesweeper.js
125 lines (108 loc) · 3.01 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
import { times, range } from "lodash/fp"
import { off } from "process"
export const TILES_STATUS = {
HIDDEN: "hidden",
MINE: "mine",
NUMBER: "number",
MARKED: "marked"
}
export function createBoard(boardSize, minePositions) {
return times(x => {
return times(y => {
return {
x,
y,
mine: minePositions.some(positionMatch.bind(null, { x, y })),
status: TILES_STATUS.HIDDEN
}
}, boardSize)
}, boardSize)
}
export function markedTilesCount(board) {
return board.reduce((count, row) => {
return (
count + row.filter(tile => tile.status === TILES_STATUS.MARKED).length
)
}, 0)
}
export function markTile(board, { x, y }) {
const tile = board[x][y]
if (
tile.status !== TILES_STATUS.HIDDEN &&
tile.status !== TILES_STATUS.MARKED
) {
return board
}
if (tile.status === TILES_STATUS.MARKED) {
return replaceTile(
board,
{ x, y },
{ ...tile, status: TILES_STATUS.HIDDEN }
)
} else {
return replaceTile(
board,
{ x, y },
{ ...tile, status: TILES_STATUS.MARKED }
)
}
}
function replaceTile(board, position, newTile) {
return board.map((row, x) => {
return row.map((tile, y) => {
if (positionMatch(position, { x, y })) {
return newTile
}
return tile
})
})
}
export function revealTile(board, { x, y }) {
const tile = board[x][y]
if (tile.status !== TILES_STATUS.HIDDEN) {
return board
}
if (tile.mine) {
return replaceTile(board, { x, y }, { ...tile, status: TILES_STATUS.MINE})
}
tile.status = TILES_STATUS.NUMBER
const adjacentTiles = nearbyTiles(board, tile)
const mines = adjacentTiles.filter(t => t.mine)
const newBoard = replaceTile(
board,
{ x, y},
{...tile, status: TILES_STATUS.NUMBER, adjacentMinesCount: mines.length }
)
if (mines.length === 0) {
return adjacentTiles.reduce((b, t) => {
return revealTile(b, t)
}, newBoard)
}
return newBoard
}
export function checkWin(board) {
return board.every(row => {
return row.every(tile => {
return tile.status === TILES_STATUS.NUMBER ||
(tile.mine && (tile.status === TILES_STATUS.HIDDEN || tile.status === TILES_STATUS.MARKED))
})
})
}
export function checkLoose(board){
return board.some(row => {
return row.some(tile => {
return tile.status === TILES_STATUS.MINE
})
})
}
export function positionMatch(a, b) {
return a.x === b.x && a.y === b.y
}
function nearbyTiles(board, { x, y }) {
const offsets = range(-1, 2)
return offsets.flatMap(xOffset => {
return offsets.map(yOffset => {
return board[x + xOffset]?.[y + yOffset]
})
}).filter(tile => tile != null)
}