flag & reveal bombs with m2 & m3

This commit is contained in:
Theis Pieter Hollebeek 2024-08-17 14:14:46 +02:00
parent 1225f8da24
commit 70fa950721

View File

@ -1,4 +1,4 @@
var board = [];
const board = [];
const canvas = document.getElementById("minesweeper");
@ -49,6 +49,13 @@ function draw() {
context.fillRect(x * CELL_SIZE + CELL_SIZE - STROKE_SIZE, y * CELL_SIZE + STROKE_SIZE, STROKE_SIZE, CELL_SIZE - STROKE_SIZE);
context.fillRect(x * CELL_SIZE + STROKE_SIZE, y * CELL_SIZE + CELL_SIZE - STROKE_SIZE, CELL_SIZE - STROKE_SIZE, STROKE_SIZE);
if (cell.isFlagged) {
context.fillStyle = "red";
context.beginPath();
context.arc(x * CELL_SIZE + CELL_SIZE / 2, y * CELL_SIZE + CELL_SIZE / 2, CELL_SIZE / 3, 0, 2 * Math.PI);
context.fill();
}
if (cell.isRevealed) {
if (cell.isMine) {
context.fillStyle = "black";
@ -144,6 +151,9 @@ function getCellNumber(x, y) {
}
function revealCell(x, y) {
if (board[x][y].isFlagged) {
return;
}
board[x][y].isRevealed = true;
if (getCellNumber(x, y) === 0) {
@ -156,10 +166,60 @@ function revealCell(x, y) {
}
}
function cellMarkedAsMine(cell) {
return cell.isFlagged || (cell.isRevealed && cell.isMine);
}
function revealSafeCell(x, y) {
if (!board[x][y].isRevealed || board[x][y].isMine) {
return;
}
const targetValue = getCellNumber(x, y);
const neighbours = getCellsAround(x, y);
const revealedBombs = neighbours
.map(([x, y]) => board[x][y])
.map(cellMarkedAsMine)
.reduce((acc, isMine) => acc + (isMine ? 1 : 0), 0);
if (revealedBombs === targetValue) {
neighbours.forEach(([x, y]) => revealCell(x, y))
}
}
function flagCell(x, y) {
if (board[x][y].isRevealed) {
return;
}
board[x][y].isFlagged = !board[x][y].isFlagged;
}
window.addEventListener("contextmenu", event => {
event.preventDefault();
})
const MouseButton = Object.freeze({
Left: 0,
Middle: 1,
Right: 2,
})
window.addEventListener("mousedown", event => {
const { x, y } = screenCoordsToBoardCoords(event.pageX + scrollX * 2, event.pageY + scrollY * 2);
revealCell(x, y);
switch (event.button) {
case MouseButton.Left:
revealCell(x, y);
break;
case MouseButton.Middle:
event.preventDefault();
revealSafeCell(x, y);
break;
case MouseButton.Right:
event.preventDefault();
flagCell(x, y);
break;
default:
return true;
}
draw();
});