Minesweeper

HTML for this example

Select the code and use your copy shortcut. Changes in this preview are temporary.

<!doctype html><html lang="en-US"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Minesweeper</title><style>*{box-sizing:border-box}html{color-scheme:light}body{margin:0;background:var(--bg,#eef1f4);color:var(--ink,#233449);font:16px/1.5 system-ui,-apple-system,Segoe UI,sans-serif}main{max-width:1040px;margin:auto;padding:26px 28px 44px}header{margin-bottom:20px}h1{font-size:clamp(26px,4vw,36px);letter-spacing:-.035em;line-height:1.15;margin:5px 0 10px}h2{font-size:21px;line-height:1.3;margin:0 0 15px}h3{font-size:17px;margin:0 0 9px}p{margin:8px 0 16px}.kicker{font-size:12px;text-transform:uppercase;letter-spacing:.12em;font-weight:750;color:var(--accent,#315b87)}.muted,small{color:#556473}.panel{margin:20px 0;padding:24px;border:1px solid var(--line,#ccd5df);border-radius:10px;background:#fff}.hero{padding:24px;background:var(--hero,#183b5c);color:#fff;border-radius:12px;margin:18px 0}.hero .kicker,.hero small{color:#d9e5ef}.big{font-size:clamp(32px,5vw,52px);line-height:1.15;font-weight:750;letter-spacing:-.035em;overflow-wrap:anywhere;margin:10px 0 15px}.row{display:flex;flex-wrap:wrap;gap:15px;align-items:end}.row>label{flex:1;min-width:140px}.grid{display:grid;grid-template-columns:1fr 1fr;gap:20px}.thirds{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:15px}label{display:block;font-size:14px;font-weight:650}input,select,textarea{font:inherit;font-size:16px;color:inherit;display:block;width:100%;margin-top:6px;padding:11px 12px;border:1px solid #a9b4c1;border-radius:6px;background:white;min-width:0}input[type=checkbox]{display:inline;width:auto;margin:0 8px 0 0;accent-color:var(--accent,#315b87)}textarea{min-height:100px;resize:vertical}button{font:inherit;font-weight:650;min-height:44px;border:1px solid var(--accent,#315b87);border-radius:6px;background:var(--accent,#315b87);color:white;padding:10px 16px;cursor:pointer}button.secondary{background:white;color:var(--accent,#315b87)}button:disabled{opacity:.5;cursor:default}button[aria-pressed=true]{box-shadow:0 0 0 3px #eab655}button:hover:not(:disabled){filter:brightness(.94)}:focus-visible{outline:3px solid #e5a72f;outline-offset:3px}.actions{display:flex;flex-wrap:wrap;gap:10px;margin:18px 0 0}[hidden]{display:none!important}.error{color:#a3232a;font-weight:650}.error:not(:empty){padding:12px;background:#fff0ed;border-left:4px solid #ab3439;margin:14px 0}.note{padding:14px;background:#edf2f6;border-radius:6px;margin:14px 0}.mono,pre{font-family:ui-monospace,Consolas,monospace;font-variant-numeric:tabular-nums}pre{white-space:pre-wrap;overflow-wrap:anywhere;font-size:14px;line-height:1.7;margin:0}.mono{overflow-wrap:anywhere}table{width:100%;border-collapse:collapse;table-layout:fixed;font-size:14px}th,td{text-align:left;vertical-align:top;overflow-wrap:anywhere;padding:11px 8px;border-bottom:1px solid #d4dce4}th{font-size:12px;text-transform:uppercase;letter-spacing:.035em;color:#536372}th:first-child,td:first-child{padding-left:0}.tag{display:inline-block;padding:4px 8px;border:1px solid currentColor;border-radius:4px;font-size:12px;font-weight:750}.rule{border-top:1px solid #cbd4dd;padding-top:18px}.line{height:30px;border-bottom:1px solid #aab5bf}.stat{font-size:34px;line-height:1.15;font-weight:750}.stat small{font:14px system-ui;display:block;margin-top:8px}details{margin:20px 0;border-top:1px solid #cbd4dd;padding:18px 0}summary{font-weight:700;cursor:pointer}details p{margin-top:15px}a{color:var(--accent,#315b87)}footer{font-size:13px;color:#556473;margin-top:25px}fieldset{min-width:0;border:1px solid #c8d2db;border-radius:7px;padding:18px;margin:15px 0}legend{font-weight:750;padding:0 6px}@media(max-width:720px){main{padding:20px}.panel,.hero{padding:20px}.thirds{gap:10px}}@media(max-width:540px){main{padding:16px}.grid,.thirds{grid-template-columns:1fr}.panel,.hero{padding:18px}.row{gap:12px}.row>label{min-width:100px}h1{font-size:27px}th,td{padding:10px 5px;font-size:13px}.big{font-size:37px}}.game{max-width:680px;margin:0 auto 20px;border-top:5px solid #496759}.game-head{display:flex;justify-content:space-between;gap:20px}.counter{text-align:right;min-width:120px}.counter strong{font-size:30px;display:block}.counter small{display:block}.board{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:6px;max-width:350px;margin:20px auto}.cell{aspect-ratio:1;min-height:44px;padding:0;font-size:23px;background:#567365;border-color:#365544;border-bottom:4px solid #334d40}.cell.opened{background:#e5ede7;color:#253d2d;border:1px solid #b5c5b8}.cell:disabled{opacity:1}.game .actions{margin:10px 0}@media(max-width:540px){.game-head{display:block}.counter{text-align:left;margin:14px 0}.counter strong,.counter small{display:inline-block;margin-right:8px}.board{gap:5px}}</style></head><body style="--bg:#edf2ed;--accent:#426651;--ink:#253d30"><main><header><div class="kicker">5 × 5 · 3 mines</div><h1>Minesweeper</h1><p class="muted">Reveal every safe cell; flags are hypotheses, and each cell counts once.</p></header><section class="game panel"><div class="game-head"><div><span id="gameType" class="tag"></span><h2 id="gameStatus" style="margin-top:10px"></h2></div><div class="counter"><strong id="safeCount"></strong><small>safe cells revealed</small></div></div><div class="actions"><button type="button" id="reveal" aria-pressed="true">Reveal</button><button type="button" id="flag" class="secondary" aria-pressed="false">Flag</button><button type="button" id="reset" class="secondary">Reset game</button></div><p id="gameMessage" aria-live="polite"></p><div id="board" class="board" role="group" aria-label="Five-by-five Minesweeper board"></div><p id="modeText" class="muted"></p></section><section class="panel"><label for="gameMode">Board mode<select id="gameMode"><option value="fixture">Developer fixture · fixed mines</option><option value="play">Play · first legal reveal is safe</option></select></label><p id="modeExplanation"></p><button type="button" id="example" class="secondary">Open fixture r1c1 example</button></section><details id="key"><summary>Developer fixture key · separate from play</summary><p>Mines: r1c5, r3c3, r5c1. Fixture first clicks can lose. The key is inspectable client-side, not protected information.</p><pre>0 0 0 1 M
0 1 1 2 1
0 1 M 1 0
1 2 1 1 0
M 1 0 0 0</pre></details><details><summary>State rules and source</summary><p>Each numbered cell reveals itself. A zero expands through unflagged safe zero neighbors and their numbered boundary. Removing a wrong safe-cell flag lets you reveal that cell later. Reset is synchronous: no animation timers or delayed reveals survive it.</p><p>In play mode, flags do not generate mines. The first legal reveal excludes that cell when placing three distinct mines; it need not have a zero clue, and later guesses may still be needed. A win requires all 22 safe cells; loss freezes play.</p><p><a href="https://www.cis.upenn.edu/~cis110/18fa/hw/hw09/writeup.pdf">UPenn: general Minesweeper adjacency and completion rules</a></p></details><footer>Local example · No information is sent or saved.</footer></main><script>const $=id=>document.getElementById(id);const esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));function gcd(a,b){return b?gcd(b,a%b):a}function rat(n,d=1n){const g=gcd(n,d);return {n:n/g,d:d/g}}function mul(a,b){return rat(a.n*b.n,a.d*b.d)}function div(a,b){return rat(a.n*b.d,a.d*b.n)}function rounded(r,p=6){const scale=10n**BigInt(p),q=(r.n*scale*2n+r.d)/(2n*r.d),s=q.toString().padStart(p+1,'0');return p?s.slice(0,-p)+'.'+s.slice(-p):s}function show(r,unit=''){if(r.n>0n&&r.n*1000000n<r.d)return '<0.000001 '+unit;return '≈ '+rounded(r,6).replace(/([.][0-9]*?)0+$/,'$1').replace(/[.]$/,'')+' '+unit}function decimal(s,name,max=1000000,places=6){if(!new RegExp('^[0-9]+(?:[.][0-9]{1,'+places+'})?$').test(s)||s.length>35)throw Error(name+': enter a nonnegative dot-decimal number, up to '+places+' decimal places.');let [a,b='']=s.split('.');const r=rat(BigInt(a+b),10n**BigInt(b.length));if(r.n>BigInt(max)*r.d)throw Error(name+': maximum is '+max+'.');return r}function whole(s,name,max){if(!/^[0-9]+$/.test(s)||s.length>15||Number(s)>max)throw Error(name+': enter an integer from 0 to '+max+'.');return Number(s)}function onForm(fn,clear){$('form').addEventListener('submit',e=>{e.preventDefault();fn()});$('form').addEventListener('input',clear);$('form').addEventListener('change',clear)}

function neighbors(i){const r=Math.floor(i/5),c=i%5,out=[];for(let dr=-1;dr<=1;dr++)for(let dc=-1;dc<=1;dc++){const rr=r+dr,cc=c+dc;if((dr||dc)&&rr>=0&&rr<5&&cc>=0&&cc<5)out.push(rr*5+cc)}return out}function place(g,mines){mines.forEach(i=>g.cells[i].mine=true);g.cells.forEach((c,i)=>c.clue=neighbors(i).filter(j=>g.cells[j].mine).length);g.generated=true}function newGame(type,rng=Math.random){const g={type,rng,cells:Array.from({length:25},()=>({mine:false,clue:0,revealed:false,flagged:false})),generated:false,status:'active',mode:'reveal',message:'Choose Reveal or Flag, then activate a cell.'};if(type==='fixture')place(g,[4,12,20]);return g}function progress(g){return g.cells.filter(c=>c.revealed&&!c.mine).length}function act(g,i){if(g.status!=='active')return;if(!Number.isInteger(i)||i<0||i>=25)return;const c=g.cells[i];if(c.revealed){g.message='This cell is already revealed.';return}if(g.mode==='flag'){c.flagged=!c.flagged;g.message=c.flagged?'Flag placed — this is a hypothesis.':'Flag removed.';return}if(c.flagged){g.message='Remove this flag before revealing the cell.';return}if(!g.generated){const pool=Array.from({length:25},(_,j)=>j).filter(j=>j!==i);for(let k=pool.length-1;k>0;k--){const j=Math.floor(g.rng()*(k+1));[pool[k],pool[j]]=[pool[j],pool[k]]}place(g,pool.slice(0,3))}if(c.mine){c.revealed=true;g.status='lost';g.message='Mine revealed. Game over; reset to start again.';return}const queue=[i],seen=new Set();while(queue.length){const j=queue.shift();if(seen.has(j))continue;seen.add(j);const cell=g.cells[j];if(cell.mine||cell.flagged||cell.revealed)continue;cell.revealed=true;if(cell.clue===0)queue.push(...neighbors(j))}g.status=progress(g)===22?'won':'active';g.message=g.status==='won'?'All 22 safe cells are revealed. You win.':'Safe reveal complete. Flags do not count as revealed cells.'}
let game=newGame('fixture');function render(){ $('gameType').textContent=game.type==='fixture'?'Developer fixture':'First-reveal-safe play';$('gameStatus').textContent=game.status==='won'?'Board cleared':game.status==='lost'?'Mine found':'Board in progress';$('safeCount').textContent=progress(game)+' / 22';$('gameMessage').textContent=game.message;$('modeText').textContent='Current action: '+(game.mode==='reveal'?'Reveal':'Flag')+' · '+game.cells.filter(c=>c.flagged).length+' flags';$('modeExplanation').textContent=game.type==='fixture'?'Fixed key. The starting example opens r1c1; Reset restores a covered fixture.':'Mines are deferred until the first legal Reveal action. Flagging does not choose a layout.';$('reveal').setAttribute('aria-pressed',String(game.mode==='reveal'));$('flag').setAttribute('aria-pressed',String(game.mode==='flag'));$('board').innerHTML='';game.cells.forEach((c,i)=>{const b=document.createElement('button');b.type='button';b.className='cell '+(c.revealed?'opened':'covered');b.id='cell-'+i;const mineShown=game.status==='lost'&&c.mine;b.textContent=mineShown?'M':c.flagged?'F':c.revealed?(c.clue?String(c.clue):'·'):'?';b.setAttribute('aria-label','Row '+(Math.floor(i/5)+1)+', column '+(i%5+1)+': '+(mineShown?'mine, shown after loss':c.flagged?'flagged':c.revealed?'revealed, '+c.clue+' adjacent mines':'covered'));b.disabled=game.status!=='active';b.onclick=()=>{act(game,i);render();$('cell-'+i).focus()};$('board').appendChild(b)})}function reset(){game=newGame($('gameMode').value);render()}$('gameMode').onchange=reset;$('reset').onclick=reset;['reveal','flag'].forEach(mode=>$(mode).onclick=()=>{if(game.status==='active'){game.mode=mode;render()}});$('example').onclick=()=>{$('gameMode').value='fixture';game=newGame('fixture');act(game,0);game.message='Worked reveal: r1c1 opened its zero region and numbered boundary.';render()};act(game,0);render();</script></body></html>