-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
66 lines (57 loc) · 1.59 KB
/
index.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
import {
TILE_STATUSES,
getGameBoard,
markTile,
markedTiles,
minedTiles,
revealTile,
tilesWithMineMarked,
visibleTiles,
} from './minesweeper.js';
const NO_OF_TILES = 10,
NO_OF_MINES = 10;
const boardElement = document.querySelector('.board');
const subtitleElement = document.querySelector('.subtitle');
boardElement.style.setProperty('--size', NO_OF_TILES);
subtitleElement.textContent = `Mines left: ${NO_OF_MINES}`;
const board = getGameBoard(NO_OF_TILES, NO_OF_MINES);
board.forEach((tile) => {
tile.element.addEventListener('click', () => {
revealTile(board, tile);
checkWinGame();
});
tile.element.addEventListener('contextmenu', (e) => {
e.preventDefault();
markTile(tile);
listMinesLeft();
checkWinGame();
});
boardElement.appendChild(tile.element);
});
function listMinesLeft() {
subtitleElement.textContent = `Mines left: ${NO_OF_MINES - markedTiles}`;
}
function checkWinGame() {
const win =
tilesWithMineMarked === NO_OF_MINES ||
visibleTiles + markedTiles === NO_OF_TILES * NO_OF_TILES;
const lose = minedTiles > 0;
if (win || lose) {
boardElement.addEventListener('click', stopProp, { capture: true });
boardElement.addEventListener('contextmenu', stopProp, { capture: true });
}
if (win) {
subtitleElement.textContent = 'You win';
return;
}
if (lose) {
subtitleElement.textContent = 'You lose';
board.forEach((tile) => {
if (tile.status === TILE_STATUSES.MARKED) markTile(tile);
if (tile.mine) revealTile(board, tile);
});
}
}
function stopProp(e) {
e.stopImmediatePropagation();
}