15 Puzzle Game JavaScript Source Code: Make Every Swap Legal
HTML for this example
Select the code and use your copy shortcut. Changes in this preview are temporary.
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>15 Puzzle Game JavaScript Source Code: Make Every Swap Legal</title><style>*{box-sizing:border-box}body{margin:0;color:var(--ink,#233342);background:var(--bg,#eef2f3);font:17px/1.6 system-ui,sans-serif}main{max-width:980px;margin:auto;padding:clamp(16px,4vw,38px)}h1{font:700 clamp(30px,5vw,49px)/1.12 Georgia,serif;margin:10px 0 20px;max-width:800px}h2{font-size:24px;line-height:1.3;margin:0 0 15px}h3{font-size:19px;margin:12px 0}p{margin:0 0 16px}.eyebrow{font-weight:750;letter-spacing:.08em;text-transform:uppercase;font-size:16px}header{padding:10px 0 25px;border-bottom:3px solid var(--accent,#24586d);margin-bottom:24px}.lede{font-size:20px;max-width:760px}.panel{background:var(--paper,#fff);padding:clamp(18px,3vw,28px);border:1px solid var(--line,#c6d1d8);border-radius:12px;margin:20px 0}.grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:20px}.grid>*{min-width:0}.row{display:flex;gap:12px;flex-wrap:wrap;align-items:center;margin:16px 0}.stack>*{margin:12px 0}button{font:700 17px/1.4 system-ui,sans-serif;cursor:pointer;color:white;background:var(--accent,#24586d);border:2px solid var(--accent,#24586d);border-radius:7px;padding:11px 17px;max-width:100%;overflow-wrap:anywhere}button.secondary{background:transparent;color:var(--ink,#233342)}button[aria-pressed=true]{box-shadow:inset 0 0 0 3px #fff;outline:2px solid var(--ink,#233342)}button:disabled{opacity:.55;cursor:default}input,textarea,select{font:17px/1.5 system-ui,sans-serif;color:inherit;background:white;border:1px solid #778591;padding:10px 12px;border-radius:6px;max-width:100%;width:100%;min-width:0}input[type=checkbox]{width:22px;height:22px}textarea{min-height:110px;resize:vertical}label{display:block;font-weight:700;margin:12px 0 7px}button:focus-visible,input:focus-visible,textarea:focus-visible,summary:focus-visible,[tabindex]:focus-visible{outline:3px solid #aa3d70;outline-offset:4px}.result{padding:18px;border-left:5px solid var(--accent,#24586d);background:var(--soft,#e5eff2);white-space:pre-wrap;overflow-wrap:anywhere;margin:20px 0}.result:empty{display:none}.hint{font-size:16px;color:var(--muted,#435968)}table{border-collapse:collapse;width:100%;table-layout:fixed;margin:16px 0}th,td{text-align:left;vertical-align:top;overflow-wrap:anywhere;padding:12px 8px;border-bottom:1px solid var(--line,#c6d1d8)}caption{text-align:left;font-weight:750;margin:8px 0}details{padding:18px;border:1px dashed #7b8b96;margin:20px 0}summary{cursor:pointer;font-weight:750}pre{font:16px/1.6 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;background:#162735;color:#f5f8fa;padding:18px;border-radius:8px}canvas,svg{display:block;max-width:100%;height:auto}footer{margin:28px 0;font-size:16px}.badge{font-weight:750;color:var(--accent,#24586d)}.metric{font:700 38px/1.3 Georgia,serif}.board{display:grid;gap:5px;max-width:440px;margin:20px auto}.board button{padding:7px;min-height:45px}.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)}@media(max-width:560px){.grid{grid-template-columns:1fr}main{padding:16px}th,td{padding:10px 5px}.row button{flex-grow:1}.metric{font-size:32px}}
:root{--bg:#e9ebf2;--paper:#fff;--accent:#56557d;--soft:#e5e3f4;--ink:#34334e}.puzzle{grid-template-columns:repeat(4,minmax(0,1fr));grid-template-rows:repeat(4,65px);max-width:360px}.puzzle button{font:700 26px Georgia,serif;background:#f2dfb0;color:#3b3040;border-color:#a28f68}.blank{border:2px dashed #8b86a1;display:flex;align-items:center;justify-content:center;font-size:16px}</style></head><body><main><header><p class="eyebrow">Sliding-number lab · One board model</p><h1>15 Puzzle Game JavaScript Source Code: Make Every Swap Legal</h1><p class="lede">Move the blank with adjacent tiles. New puzzles come from reversible legal walks.</p><p class="hint">Original fictional sample. Changes last only while this page remains open.</p></header><section class="panel"><h2>Order 1 through 15, then Blank</h2><p>Direction controls move the blank. Focus the board for arrow keys.</p><div id="board" class="board puzzle" tabindex="0" role="group" aria-label="Sliding puzzle"><button id="tile1" type="button">1</button><button id="tile2" type="button">2</button><button id="tile3" type="button">3</button><button id="tile4" type="button">4</button><button id="tile5" type="button">5</button><button id="tile6" type="button">6</button><button id="tile7" type="button">7</button><button id="tile8" type="button">8</button><button id="tile9" type="button">9</button><button id="tile10" type="button">10</button><button id="tile11" type="button">11</button><button id="tile12" type="button">12</button><button id="tile13" type="button">13</button><button id="tile14" type="button">14</button><button id="tile15" type="button">15</button><span id="blank" class="blank">Blank</span></div><div class="row"><button id="up" type="button">Blank up</button><button id="down" type="button">Blank down</button><button id="left" type="button">Blank left</button><button id="right" type="button">Blank right</button></div><p id="status" class="result" role="status"></p><p id="message" role="status"></p><div class="row"><button id="new" type="button">New Puzzle</button><button id="verify" type="button">Verify construction</button><button id="reset" type="button" class="secondary">Reset baseline</button></div><p id="construction" class="result" role="status"></p></section><footer>Solve the one-move board, then verify a new puzzle’s reversible construction.</footer></main><script>
(()=>{'use strict';const $=id=>document.getElementById(id);
const goal=Array.from({length:16},(_,i)=>(i+1)%16),initial=[...goal.slice(0,12),13,14,0,15];let board=initial.slice(),moves=0,won=false,build=[],baseline=board.slice();function neighbors(i){const r=Math.floor(i/4),c=i%4;return [[r-1,c],[r+1,c],[r,c-1],[r,c+1]].filter(([r,c])=>r>=0&&r<4&&c>=0&&c<4).map(([r,c])=>r*4+c);}function isGoal(a){return a.every((x,i)=>x===goal[i]);}function render(){board.forEach((value,i)=>{const e=value?$('tile'+value):$('blank');e.style.gridRow=String(Math.floor(i/4)+1);e.style.gridColumn=String(i%4+1);e.setAttribute('aria-label',value?'Tile '+value+', row '+Math.floor(i/4)+', column '+i%4:'Blank, row '+Math.floor(i/4)+', column '+i%4);});const z=board.indexOf(0);$('status').textContent=(won?'Won':'Playing')+' · Player moves: '+moves+' · Blank ('+Math.floor(z/4)+','+z%4+').';}function swapTile(value){if(won)return;const z=board.indexOf(0),i=board.indexOf(value);if(!value||!neighbors(z).includes(i)){$('message').textContent='Rejected: tile must be a cardinal neighbor of the blank.';return;}[board[z],board[i]]=[board[i],board[z]];moves++;won=isGoal(board);$('message').textContent=won?'Ordered goal reached. Reset or New Puzzle to continue.':'Legal swap.';render();$('tile'+value).focus();}for(let i=1;i<=15;i++)$('tile'+i).addEventListener('click',()=>swapTile(i));const dirs={up:-4,down:4,left:-1,right:1};function move(k){const z=board.indexOf(0),i=z+dirs[k];if(!neighbors(z).includes(i)){$('message').textContent='Rejected boundary; no row wrapping.';return;}swapTile(board[i]);}for(const k of Object.keys(dirs))$(k).addEventListener('click',()=>move(k));$('board').addEventListener('keydown',event=>{if(!['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(event.key))return;event.preventDefault();if(event.repeat)return;move(event.key.replace('Arrow','').toLowerCase());});$('new').addEventListener('click',()=>{let accepted=false;for(let attempt=0;attempt<5;attempt++){board=goal.slice();build=[];for(let j=0;j<100;j++){const z=board.indexOf(0),n=neighbors(z),i=n[Math.floor(Math.random()*n.length)];[board[z],board[i]]=[board[i],board[z]];build.push([z,i]);}if(!isGoal(board)){accepted=true;break;}}if(!accepted){board=goal.slice();build=[[15,14],[14,10]];for(const[a,b]of build)[board[a],board[b]]=[board[b],board[a]];}baseline=board.slice();moves=0;won=false;$('construction').textContent='New reachable board from '+build.length+' construction swaps. Player moves: 0.';$('message').textContent='New puzzle ready.';render();});$('verify').addEventListener('click',()=>{if(!build.length){$('construction').textContent='Baseline is one swap from goal: tile 15 enters the blank.';return;}const copy=baseline.slice();for(let i=build.length-1;i>=0;i--){const[a,b]=build[i];[copy[a],copy[b]]=[copy[b],copy[a]];}$('construction').textContent=isGoal(copy)?'Reverse replay reaches the exact goal. '+build.length+' construction swaps; player moves unchanged.':'Construction verification failed.';});$('reset').addEventListener('click',()=>{board=initial.slice();baseline=board.slice();build=[];moves=0;won=false;$('message').textContent='Original one-move baseline restored.';$('construction').textContent='';render();});render();
})();
</script></body></html>