File size: 7,490 Bytes
ef987bb | 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 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Minesweeper</title>
<style>
body{font-family:sans-serif;background:#bdbdbd;color:#222;text-align:center}
#board{display:inline-grid;background:#7b7b7b;padding:6px;border-radius:4px;
grid-gap:2px;margin:16px auto}
.cell{box-sizing:border-box;width:34px;height:34px;line-height:30px;font-size:18px;font-weight:bold;
background:#c0c0c0;border:2px outset #e0e0e0;cursor:pointer;user-select:none}
.cell.revealed{background:#d8d8d8;border:1px solid #9a9a9a}
.cell.mine{background:#ff7676}
.cell.flagged{color:#c00}
.a1{color:#0000ff}.a2{color:#008000}.a3{color:#ff0000}.a4{color:#000080}
.a5{color:#800000}.a6{color:#008080}.a7{color:#000}.a8{color:#808080}
#hud{font-size:20px;margin:8px}
button{font-size:16px;padding:6px 12px;margin:4px}
</style>
</head>
<body>
<h1>Minesweeper</h1>
<div id="hud">Status: <span data-testid="status">playing</span></div>
<div>
<label for="grid-size">Board Size</label>
<select id="grid-size" data-testid="grid-size" aria-label="board size">
<option value="5x5">5 × 5</option>
<option value="8x8">8 × 8</option>
<option value="12x12">12 × 12</option>
</select>
<button data-testid="new-game">New Game</button>
<p>Left-click to reveal · Right-click to flag</p>
</div>
<div id="board" data-testid="board"></div>
<script>
(function(){
const DEFAULT_SIZE = 5;
let previousLayout = null;
function randomMines(rows, cols) {
const count = Math.max(1, Math.min(rows * cols - 1, Math.round(rows * cols * 0.16)));
const randomIndex = limit => {
if (window.crypto && window.crypto.getRandomValues) {
const value = new Uint32Array(1);
const threshold = Math.floor(4294967296 / limit) * limit;
do { window.crypto.getRandomValues(value); } while (value[0] >= threshold);
return value[0] % limit;
}
return Math.floor(Math.random() * limit);
};
let chosen, fingerprint;
do {
const positions = Array.from({length: rows * cols}, (_, i) => i);
for (let i = positions.length - 1; i > 0; i--) {
const j = randomIndex(i + 1);
[positions[i], positions[j]] = [positions[j], positions[i]];
}
chosen = positions.slice(0, count).sort((a,b) => a-b);
fingerprint = `${rows}x${cols}:${chosen.join(',')}`;
} while (fingerprint === previousLayout);
previousLayout = `${rows}x${cols}:${chosen.join(',')}`;
return chosen.map(i => [Math.floor(i / cols), i % cols]);
}
const G = {
rows: 0, cols: 0, status: 'playing', cells: [],
init(cfg){
cfg = cfg || {};
const selected = document.querySelector('[data-testid="grid-size"]').value.split('x').map(Number);
const rows = cfg.rows != null ? cfg.rows : selected[0] || DEFAULT_SIZE;
const cols = cfg.cols != null ? cfg.cols : selected[1] || DEFAULT_SIZE;
if (!Number.isInteger(rows) || !Number.isInteger(cols) || rows < 1 || cols < 1 || rows * cols < 2) {
throw new Error('board needs at least two cells');
}
const mines = cfg.mines != null ? cfg.mines : randomMines(rows, cols);
this.rows = rows;
this.cols = cols;
this.status = 'playing';
this.cells = [];
const mineSet = new Set(mines.map(m => m[0] + ',' + m[1]));
for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++){
this.cells.push({ revealed:false, flagged:false, mine: mineSet.has(r+','+c), adj:0 });
}
// compute adjacency
for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++){
let n = 0;
for (let dr = -1; dr <= 1; dr++) for (let dc = -1; dc <= 1; dc++){
if (dr === 0 && dc === 0) continue;
const rr = r + dr, cc = c + dc;
if (rr < 0 || rr >= rows || cc < 0 || cc >= cols) continue;
if (this.cells[rr * cols + cc].mine) n++;
}
this.cells[r * cols + c].adj = n;
}
render();
return this.getState();
},
getState(){
return {
rows: this.rows,
cols: this.cols,
status: this.status,
cells: this.cells.map(x => ({ revealed:x.revealed, flagged:x.flagged, mine:x.mine, adj:x.adj }))
};
},
idx(r,c){ return r * this.cols + c; },
reveal(r,c){
if (this.status !== 'playing') return this.getState();
const cell = this.cells[this.idx(r,c)];
if (!cell || cell.revealed || cell.flagged) return this.getState();
if (cell.mine){
cell.revealed = true;
this.status = 'lost';
for (const x of this.cells) if (x.mine) x.revealed = true;
render();
return this.getState();
}
this._flood(r,c);
this._checkWin();
render();
return this.getState();
},
toggleFlag(r,c){
if (this.status !== 'playing') return this.getState();
const cell = this.cells[this.idx(r,c)];
if (!cell || cell.revealed) return this.getState();
cell.flagged = !cell.flagged;
render();
return this.getState();
},
// ---- internals ----
_flood(sr,sc){
const stack = [[sr,sc]];
while (stack.length){
const [r,c] = stack.pop();
if (r < 0 || r >= this.rows || c < 0 || c >= this.cols) continue;
const cell = this.cells[this.idx(r,c)];
if (cell.revealed || cell.mine) continue;
if (cell.flagged) continue;
cell.revealed = true;
// only keep expanding through zero-adj cells; numbered cells form the border
if (cell.adj === 0){
for (let dr = -1; dr <= 1; dr++) for (let dc = -1; dc <= 1; dc++){
if (dr === 0 && dc === 0) continue;
stack.push([r + dr, c + dc]);
}
}
}
},
_checkWin(){
let allRevealed = true;
for (const x of this.cells){
if (!x.mine && !x.revealed){ allRevealed = false; break; }
}
if (allRevealed) this.status = 'won';
}
};
function render(){
const board = document.getElementById('board');
if (!board) return;
board.style.gridTemplateColumns = 'repeat(' + G.cols + ',34px)';
board.innerHTML = '';
for (let r = 0; r < G.rows; r++) for (let c = 0; c < G.cols; c++){
const cell = G.cells[r * G.cols + c];
const d = document.createElement('div');
let cls = 'cell';
let text = '';
if (cell.revealed){
cls += ' revealed';
if (cell.mine){ cls += ' mine'; text = '💣'; }
else if (cell.adj > 0){ cls += ' a' + cell.adj; text = cell.adj; }
} else if (cell.flagged){
cls += ' flagged'; text = '🚩';
}
d.className = cls;
d.textContent = text;
d.dataset.r = r;
d.dataset.c = c;
board.appendChild(d);
}
const st = document.querySelector('[data-testid="status"]');
if (st) st.textContent = G.status;
}
document.addEventListener('click', e => {
const t = e.target;
if (t && t.matches('[data-testid="new-game"]')){ G.init({}); return; }
if (t && t.classList && t.classList.contains('cell') && t.dataset.r != null){
G.reveal(+t.dataset.r, +t.dataset.c);
}
});
document.addEventListener('contextmenu', e => {
const t = e.target;
if (t && t.classList && t.classList.contains('cell') && t.dataset.r != null){
e.preventDefault();
G.toggleFlag(+t.dataset.r, +t.dataset.c);
}
});
window.__game = G;
G.init({});
})();
</script>
</body>
</html>
|