UXInteract / task_048 /solution /code /index.html
DojiSum's picture
Publish the current 141-task UXInteract release
ef987bb verified
Raw History Blame Contribute Delete
7.49 kB
<!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>