FILE: build/feedback.js // Adapted from Assios/chessguessr useChessguessr.ts, GPL-3.0 const chessCols = "abcdefgh"; const kingMove = "OK"; function formatGuess(currentGuess, game) { const solutionArray = [...game.solution]; const discardYellowArray = [...game.solution]; const formattedGuess = [...currentGuess].map((move) => { return { move, color: "grey", pieceColor: "regular" }; }); formattedGuess.forEach((move, i) => { if (solutionArray[i] === move.move) { formattedGuess[i].color = "green"; solutionArray[i] = null; discardYellowArray[i] = null; } }); formattedGuess.forEach((move, i) => { if (discardYellowArray.includes(move.move) && move.color !== "green") { formattedGuess[i].color = "yellow"; discardYellowArray[discardYellowArray.indexOf(move.move)] = null; } if (move.color !== "green" && solutionArray[i] !== null && (solutionArray[i][0] === move.move[0] || chessCols.includes(solutionArray[i][0]) && chessCols.includes(move.move[0]) || kingMove.includes(solutionArray[i][0]) && kingMove.includes(move.move[0]))) { formattedGuess[i].pieceColor = "blue"; } }); return formattedGuess; } ; export { formatGuess }; FILE: build/main.js /* Five Ply: static adaptation of Chessguessr by Assios. GPL-3.0. */ import {Chess} from 'chess.js';import {formatGuess} from './feedback.js'; const $=id=>document.getElementById(id);let puzzles=[],index=0,game,chess,state,selected=null,flipped=false,review=null,lastMove=null; const glyph={k:'♚',q:'♛',r:'♜',b:'♝',n:'♞',p:'♟'},names={k:'king',q:'queen',r:'rook',b:'bishop',n:'knight',p:'pawn'}; let book={version:1,index:0,puzzles:{}};try{const saved=JSON.parse(localStorage.getItem('five-ply-v1'));if(saved?.version===1&&saved.puzzles)book=saved}catch{} function save(){book.index=index;try{localStorage.setItem('five-ply-v1',JSON.stringify(book))}catch{}} function fresh(){return{guesses:[],current:[],status:'playing',assisted:false,hints:0}} function load(n){index=(n+puzzles.length)%puzzles.length;game=puzzles[index];state=book.puzzles[game.id]||fresh();book.puzzles[game.id]=state;chess=new Chess(game.fen);for(const m of state.current){if(!chess.move(m)){state.current=[];chess=new Chess(game.fen);break}}selected=null;lastMove=null;review=null;flipped=false;$('puzzle').value=index;save();render();if(state.status!=='playing')setReview(0)} function announce(text){$('message').textContent=text} function played(m){if(state.status!=='playing'||state.current.length===5||review)return;const move=chess.move(m);if(!move){announce('That move is not legal. Select a highlighted destination.');return}state.current.push(move.san);lastMove=[move.from,move.to];selected=null;save();render();announce(state.current.length===5?'Five moves ready. Submit your line to get the clues.':`${move.san} recorded. ${chess.turn()==='w'?'White':'Black'} plays next.`)} function attempt(from,to){const moves=chess.moves({verbose:true}).filter(m=>m.from===from&&m.to===to);if(!moves.length){selected=null;renderBoard();return}if(moves.some(m=>m.promotion)){$('promotion-options').replaceChildren();for(const p of ['q','r','b','n']){const b=document.createElement('button');b.textContent=glyph[p];b.setAttribute('aria-label','Promote to '+names[p]);b.addEventListener('click',()=>{$('promotion').close();played({from,to,promotion:p})});$('promotion-options').append(b)}$('promotion').showModal()}else played({from,to})} function clickSquare(sq){if(state.status!=='playing'||state.current.length===5||review)return;const piece=chess.get(sq);if(selected===sq){selected=null;renderBoard();return}if(selected){const from=selected;if(chess.moves({square:from,verbose:true}).some(m=>m.to===sq)){attempt(from,sq);return}}selected=piece?.color===chess.turn()?sq:null;renderBoard();if(selected)announce(`${names[piece.type]} on ${sq}. Choose a highlighted square.`)} function renderBoard(){const shown=review?.chess||chess;const orient=(game.fen.split(' ')[1]==='b')!==flipped;const files=orient?'hgfedcba':'abcdefgh',ranks=orient?'12345678':'87654321';const dests=selected?chess.moves({square:selected,verbose:true}).map(m=>m.to):[];const focus=document.activeElement?.dataset?.square;const frag=document.createDocumentFragment();for(const r of ranks)for(const f of files){const sq=f+r,piece=shown.get(sq),b=document.createElement('button');b.className='square'+(((f.charCodeAt(0)-97+Number(r))%2===1)?' dark':'')+(selected===sq?' selected':'')+(dests.includes(sq)?' dest':'')+(piece?' occupied':'')+(lastMove?.includes(sq)?' last':'');b.dataset.square=sq;b.setAttribute('aria-label',`${sq}${piece?' '+(piece.color==='w'?'White':'Black')+' '+names[piece.type]:' empty'}${dests.includes(sq)?' legal destination':''}`);b.addEventListener('click',()=>clickSquare(sq));b.addEventListener('keydown',e=>{const keys={ArrowRight:1,ArrowLeft:-1,ArrowDown:8,ArrowUp:-8};if(e.key in keys){e.preventDefault();const all=[...$('board').children],i=all.indexOf(b);all[(i+keys[e.key]+64)%64].focus()}});if(piece){const span=document.createElement('span');span.className='piece'+(piece.color==='w'?' whitepiece':'');span.textContent=glyph[piece.type];b.append(span)}const c=document.createElement('span');c.className='coord';c.textContent=sq;b.append(c);frag.append(b)}$('board').replaceChildren(frag);if(focus)$('board').querySelector(`[data-square="${focus}"]`)?.focus();$('turn').textContent=(shown.turn()==='w'?'White':'Black')+' to move';$('position-label').textContent=review?review.label:`${state.current.length}/5 moves in your line`;} function tile(move,feedback,active=false){const t=document.createElement('span');t.className='tile '+(feedback?.color||'')+(feedback?.pieceColor==='blue'?' pieceblue':'')+(active?' active':'');t.textContent=move||'·';if(feedback){const label=feedback.color==='green'?'exact':feedback.color==='yellow'?'elsewhere':feedback.pieceColor==='blue'?'piece type':'miss';t.title=label+(feedback.pieceColor==='blue'&&feedback.color==='yellow'?' + correct piece type':'');if(feedback.pieceColor==='blue'&&feedback.color==='grey')t.classList.add('blue');const small=document.createElement('small');small.textContent=label;t.append(small)}return t} function render(){renderBoard();$('players').textContent=`${game.white} · ${game.black}`;$('puzzle-meta').textContent=`Archive #${game.id} · ${game.date}${state.assisted?' · Assisted':''}`;$('record').textContent=Object.values(book.puzzles).filter(s=>s.status==='solved').length+' solved';$('rows').replaceChildren();for(let i=0;i<5;i++){const row=document.createElement(isetReview(0,guess,`Attempt ${i+1}`));for(let j=0;j<5;j++){const fb=guess?formatGuess(guess,game)[j]:null;row.append(tile(guess?.[j]||(i===state.guesses.length?state.current[j]:null),fb,i===state.guesses.length&&state.status==='playing'))}$('rows').append(row)}const ended=state.status!=='playing';$('review').hidden=!ended&&!review;$('submit').disabled=ended||state.current.length!==5||!!review;$('undo').disabled=ended||!state.current.length||!!review;$('resetline').disabled=ended||!state.current.length||!!review;$('hint').disabled=ended||!!review;$('reveal').disabled=ended;$('playmove').disabled=ended||state.current.length===5||!!review;$('moves').disabled=$('playmove').disabled;$('moves').replaceChildren();for(const m of chess.moves()){const o=document.createElement('option');o.value=m;o.textContent=m;$('moves').append(o)}if(ended){$('solution').textContent=game.solution.join(' → ');$('nextcase').hidden=false;announce(state.status==='solved'?`Mystery solved in ${state.guesses.length}/5 attempts${state.assisted?' · assisted':''}. Explore the recorded line below.`:state.status==='revealed'?'Solution revealed. Review the five moves, then try another mystery.':'Five attempts complete. Review the recorded line and try another mystery.')}else if(review)announce('Reviewing a submitted line. Return to your line to keep guessing.');else announce(`Attempt ${state.guesses.length+1}/5 · ${state.current.length}/5 moves recorded.`);} function submit(){if(state.status!=='playing'||state.current.length!==5||review)return;state.guesses.push([...state.current]);state.status=state.current.every((m,i)=>m===game.solution[i])?'solved':state.guesses.length===5?'failed':'playing';state.current=[];chess=new Chess(game.fen);lastMove=null;selected=null;save();render();if(state.status!=='playing')setReview(0)} function setReview(step,moves=game.solution,label='Recorded line'){const c=new Chess(game.fen);for(const m of moves.slice(0,step))c.move(m);review={chess:c,step,moves,label:`${label} · ${step}/5`,name:label};selected=null;lastMove=null;$('review').hidden=false;$('solution').textContent=moves.join(' → ');$('review-label').textContent=review.label;$('reviewprev').disabled=step===0;$('reviewnext').disabled=step===5;$('nextcase').hidden=state.status==='playing';if(state.status==='playing'){$('review-label').textContent+=' · Click Clear review to return';$('reviewprev').textContent=step===0?'Clear review':'← Back'}else $('reviewprev').textContent='← Back';// At step zero allow leaving an in-progress replay. if(state.status==='playing')$('reviewprev').disabled=false;renderBoard();$('submit').disabled=true;$('undo').disabled=true;$('resetline').disabled=true;$('hint').disabled=true;$('playmove').disabled=true;$('moves').disabled=true;} $('submit').addEventListener('click',submit);$('playmove').addEventListener('click',()=>played($('moves').value));$('undo').addEventListener('click',()=>{if(!state.current.length||review)return;chess.undo();state.current.pop();lastMove=null;selected=null;save();render()});$('resetline').addEventListener('click',()=>{state.current=[];chess=new Chess(game.fen);selected=null;lastMove=null;save();render()});$('flip').addEventListener('click',()=>{flipped=!flipped;renderBoard()});$('puzzle').addEventListener('change',()=>load(Number($('puzzle').value)));$('prev').addEventListener('click',()=>load(index-1));$('next').addEventListener('click',()=>load(index+1));$('nextcase').addEventListener('click',()=>load(index+1));$('daily').addEventListener('click',()=>{const date=new Date().toISOString().slice(0,10);const n=puzzles.findIndex(p=>p.date===date);load(n>=0?n:Math.floor(Date.now()/86400000)%puzzles.length)}); $('hint').addEventListener('click',()=>{let n=0;while(n$('confirm').showModal());$('cancelreveal').addEventListener('click',()=>$('confirm').close());$('confirmreveal').addEventListener('click',()=>{$('confirm').close();state.status='revealed';state.current=[];chess=new Chess(game.fen);save();render();setReview(0)}); $('reviewnext').addEventListener('click',()=>{if(review)setReview(Math.min(5,review.step+1),review.moves,review.name)});$('reviewprev').addEventListener('click',()=>{if(review?.step===0&&state.status==='playing'){review=null;render();return}if(review)setReview(Math.max(0,review.step-1),review.moves,review.name)}); $('help').addEventListener('click',()=>$('rules').showModal());for(const id of ['closehelp','start'])$(id).addEventListener('click',()=>{$('rules').close();try{localStorage.setItem('five-ply-rules','seen')}catch{}}); document.addEventListener('keydown',e=>{if(e.target.closest('dialog')||e.target.matches('input,select,button,a'))return;if(e.key==='Enter'){e.preventDefault();submit()}if(e.key==='Backspace'){e.preventDefault();$('undo').click()}}); fetch('puzzles.json').then(r=>{if(!r.ok)throw Error('Unable to load puzzles');return r.json()}).then(data=>{puzzles=data;for(let i=0;i=0&&book.indexannounce('Could not load the puzzle archive. Please reload.')); FILE: build/package-lock.json { "name": "build", "lockfileVersion": 3, "requires": true, "packages": { "": { "dependencies": { "chess.js": "0.12.1", "esbuild": "0.25.12" } }, "node_modules/@esbuild/aix-ppc64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz", "integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==", "cpu": [ "ppc64" ], "license": "MIT", "optional": true, "os": [ "aix" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/android-arm": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz", "integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==", "cpu": [ "arm" ], "license": "MIT", "optional": true, "os": [ "android" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/android-arm64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz", "integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==", "cpu": [ "arm64" ], "license": "MIT", "optional": true, "os": [ "android" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/android-x64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz", "integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==", "cpu": [ "x64" ], "license": "MIT", "optional": true, "os": [ "android" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/darwin-arm64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz", "integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==", "cpu": [ "arm64" ], "license": "MIT", "optional": true, "os": [ "darwin" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/darwin-x64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz", "integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==", "cpu": [ "x64" ], "license": "MIT", "optional": true, "os": [ "darwin" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/freebsd-arm64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz", "integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==", "cpu": [ "arm64" ], "license": "MIT", "optional": true, "os": [ "freebsd" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/freebsd-x64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz", "integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==", "cpu": [ "x64" ], "license": "MIT", "optional": true, "os": [ "freebsd" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-arm": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz", "integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==", "cpu": [ "arm" ], "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-arm64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz", "integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==", "cpu": [ "arm64" ], "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-ia32": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz", "integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==", "cpu": [ "ia32" ], "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-loong64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz", "integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==", "cpu": [ "loong64" ], "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-mips64el": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz", "integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==", "cpu": [ "mips64el" ], "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-ppc64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz", "integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==", "cpu": [ "ppc64" ], "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-riscv64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz", "integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==", "cpu": [ "riscv64" ], "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-s390x": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz", "integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==", "cpu": [ "s390x" ], "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/linux-x64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz", "integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==", "cpu": [ "x64" ], "license": "MIT", "optional": true, "os": [ "linux" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/netbsd-arm64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz", "integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==", "cpu": [ "arm64" ], "license": "MIT", "optional": true, "os": [ "netbsd" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/netbsd-x64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz", "integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==", "cpu": [ "x64" ], "license": "MIT", "optional": true, "os": [ "netbsd" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/openbsd-arm64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz", "integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==", "cpu": [ "arm64" ], "license": "MIT", "optional": true, "os": [ "openbsd" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/openbsd-x64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz", "integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==", "cpu": [ "x64" ], "license": "MIT", "optional": true, "os": [ "openbsd" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/openharmony-arm64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz", "integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==", "cpu": [ "arm64" ], "license": "MIT", "optional": true, "os": [ "openharmony" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/sunos-x64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz", "integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==", "cpu": [ "x64" ], "license": "MIT", "optional": true, "os": [ "sunos" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/win32-arm64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz", "integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==", "cpu": [ "arm64" ], "license": "MIT", "optional": true, "os": [ "win32" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/win32-ia32": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz", "integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==", "cpu": [ "ia32" ], "license": "MIT", "optional": true, "os": [ "win32" ], "engines": { "node": ">=18" } }, "node_modules/@esbuild/win32-x64": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz", "integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==", "cpu": [ "x64" ], "license": "MIT", "optional": true, "os": [ "win32" ], "engines": { "node": ">=18" } }, "node_modules/chess.js": { "version": "0.12.1", "resolved": "https://registry.npmjs.org/chess.js/-/chess.js-0.12.1.tgz", "integrity": "sha512-95PsuUCtoxPyQNB+29k54OWGeEEpuWXu+d+oWL/fcko5T5NhDuGxaYmoXcZ6KUnFKyUYxdLjwqRqCWZonRuoJQ==", "license": "BSD-2-Clause" }, "node_modules/esbuild": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", "integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==", "hasInstallScript": true, "license": "MIT", "bin": { "esbuild": "bin/esbuild" }, "engines": { "node": ">=18" }, "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.12", "@esbuild/android-arm": "0.25.12", "@esbuild/android-arm64": "0.25.12", "@esbuild/android-x64": "0.25.12", "@esbuild/darwin-arm64": "0.25.12", "@esbuild/darwin-x64": "0.25.12", "@esbuild/freebsd-arm64": "0.25.12", "@esbuild/freebsd-x64": "0.25.12", "@esbuild/linux-arm": "0.25.12", "@esbuild/linux-arm64": "0.25.12", "@esbuild/linux-ia32": "0.25.12", "@esbuild/linux-loong64": "0.25.12", "@esbuild/linux-mips64el": "0.25.12", "@esbuild/linux-ppc64": "0.25.12", "@esbuild/linux-riscv64": "0.25.12", "@esbuild/linux-s390x": "0.25.12", "@esbuild/linux-x64": "0.25.12", "@esbuild/netbsd-arm64": "0.25.12", "@esbuild/netbsd-x64": "0.25.12", "@esbuild/openbsd-arm64": "0.25.12", "@esbuild/openbsd-x64": "0.25.12", "@esbuild/openharmony-arm64": "0.25.12", "@esbuild/sunos-x64": "0.25.12", "@esbuild/win32-arm64": "0.25.12", "@esbuild/win32-ia32": "0.25.12", "@esbuild/win32-x64": "0.25.12" } } } } FILE: build/package.json {"type": "module", "dependencies": {"chess.js": "0.12.1", "esbuild": "0.25.12"}} FILE: index.html Five Ply · Chessguessr
♞FIVE PLYTHE CHESSGUESSR NOTEBOOK

A SMALL MYSTERY ON SIXTY-FOUR SQUARES

Read the position.
Find the next five moves.

Two players left a trail. Reconstruct five half-moves from their real game, using a little chess and a little deduction.

YOUR NOTEBOOK0 solvedSaved on this device

White to move

Starting position♔ White · ♚ Black
Click a piece, then a highlighted square. Or select a legal move above.

FIVE MOVES · FIVE ATTEMPTS

Your line of inquiry

You play both sides. A move is one player’s turn.

ExactElsewherePiece typeMiss

Build a legal five-move line, then submit it.

Find what actually happened, not necessarily the engine’s best move. Reveals are marked as assisted.

WELCOME TO THE NOTEBOOK

Five half-moves. Five guesses.

Reconstruct the next five individual moves from a real game. You move both White and Black, alternating turns. Click a piece and a legal destination, or use the legal-move menu.

  • Exact — this move is in the correct place.
  • Elsewhere — this exact move occurs elsewhere in the line.
  • Piece type — the right kind of piece moved on this turn. A blue underline can accompany an Elsewhere tile.
  • Miss — neither the move nor its piece type matches here.

After a miss, the board resets to the initial position. Click any submitted row to replay it. Undo and clear work before submitting. Reveal next move builds the correct prefix and marks the puzzle assisted.

Chess notation: K king, Q queen, R rook, B bishop, N knight; no letter means pawn. “x” is capture, “+” check, “#” mate, “O-O” castling. Promotion offers four piece choices.

Choose a promotion

Reveal this mystery?

This ends the current puzzle and shows the recorded continuation.

FILE: style.css :root{color-scheme:light;--ink:#163532;--muted:#62706a;--paper:#f7f4eb;--line:#dcded0;--green:#315f4e;--gold:#c69a51}*{box-sizing:border-box}body{margin:0;background:var(--paper);color:var(--ink);font:16px/1.5 system-ui,-apple-system,sans-serif}button,select{font:inherit}button,a,select{-webkit-tap-highlight-color:transparent}button,select{border:1px solid #c9cfc0;background:#fffdf7;color:var(--ink);border-radius:7px;padding:9px 13px}button{cursor:pointer;transition:background .15s}button:hover{background:#e9e9db}button:disabled{opacity:.4;cursor:default}button:focus-visible,a:focus-visible,select:focus-visible{outline:3px solid #dd9a36;outline-offset:3px}a{color:inherit;text-underline-offset:4px}header{display:flex;justify-content:space-between;align-items:center;padding:20px 5vw;border-bottom:1px solid var(--line);gap:20px}.brand{display:flex;gap:12px;align-items:center;text-decoration:none;font-weight:800;letter-spacing:.14em}.brand small{display:block;font-size:9px;letter-spacing:.13em;color:var(--muted)}.crest{font-size:40px;line-height:1}nav{display:flex;gap:22px;align-items:center;font-size:13px}nav button{border:0;background:none}main{max-width:1190px;margin:auto;padding:35px 30px}.intro{display:flex;justify-content:space-between;align-items:center;gap:30px;margin-bottom:28px}.eyebrow{font-size:10px;font-weight:800;letter-spacing:.18em;color:#7b6b49;margin:0 0 11px}h1{font:46px/1.1 Georgia,serif;letter-spacing:-.035em;margin:0 0 14px}h2{font:27px/1.15 Georgia,serif;margin:0 0 8px}.lede{color:var(--muted);max-width:600px;font-size:14px;margin:0}.scorecard{border:1px solid var(--line);border-radius:10px;min-width:190px;padding:24px;transform:rotate(2deg);background:#fffdf6}.scorecard span{font-size:9px;letter-spacing:.15em}.scorecard strong{display:block;font:27px Georgia,serif;margin:8px 0}.scorecard small{color:var(--muted);font-size:11px}.toolbar{display:flex;align-items:center;gap:8px;padding:12px 0 22px;border-top:1px solid var(--line);font-size:13px}.toolbar select{max-width:135px}.toolbar label{white-space:nowrap}.toolbar #puzzle-meta{margin-left:auto;color:var(--muted)}.game{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:38px}.boardtitle{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:15px}.boardtitle small{font-size:11px;color:var(--muted);display:block;margin-bottom:6px}.boardtitle h2{font-size:24px;margin:0}.boardtitle button{font-size:12px}.frame{background:#25453c;border-radius:8px;padding:11px;box-shadow:0 12px 25px #132b2220}#board{display:grid;grid-template-columns:repeat(8,1fr);aspect-ratio:1}.square{border:0;border-radius:0;padding:0;aspect-ratio:1;position:relative;display:flex;align-items:center;justify-content:center;font-size:clamp(28px,4vw,47px);line-height:1;font-family:Georgia,'Apple Symbols','Segoe UI Symbol',serif;background:#ebeedb;color:#142d28}.square.dark{background:#7e9d82}.square:hover{background:#e8cb8b}.square.selected{background:#eac36a;box-shadow:inset 0 0 0 3px #8c5c12}.square.dest:after{content:'';position:absolute;width:22%;height:22%;border-radius:50%;background:#173e3290;pointer-events:none}.square.dest.occupied:after{width:87%;height:87%;border:5px solid #dec178;background:transparent}.square.last{box-shadow:inset 0 0 0 3px #ac8a45}.square .piece{pointer-events:none}.square .whitepiece{color:#fffef1;text-shadow:1px 1px 0 #26392e,-1px -1px 0 #26392e,1px -1px 0 #26392e,-1px 1px 0 #26392e}.square .coord{position:absolute;font:8px system-ui;bottom:2px;right:3px;color:#19362c;opacity:.7}.boardfoot{display:flex;justify-content:space-between;margin:10px 0;font-size:11px;color:var(--muted)}.legal{display:flex;align-items:center;gap:7px;padding-top:13px;border-top:1px solid var(--line)}.legal label{font-size:11px;max-width:80px}.legal select{flex:1;min-width:0}.legal button{font-size:12px}.hintline{display:block;color:var(--muted);font-size:11px;margin-top:9px}.notebook{padding:23px;border:1px solid var(--line);border-radius:10px;background:#fffdf6;align-self:start;box-shadow:3px 4px 0 #e8e6d9}.notebook h2{font-size:29px}.sub{font-size:12px;color:var(--muted);margin:0 0 18px}.legend{display:flex;gap:6px;font-size:10px;margin-bottom:15px}.legend span{padding:4px 9px;border-radius:4px}.green{background:#326949;color:#fff}.yellow{background:#c9a34e;color:#252b21}.blue{background:#33687b;color:#fff}.grey{background:#dfe3db;color:#5f6964}#rows{display:grid;gap:7px}.guessrow{display:grid;grid-template-columns:repeat(5,1fr);gap:6px;border:0;background:none;padding:0;text-align:center;width:100%;border-radius:0}.guessrow:hover{background:none}.tile{border:1px solid #d6dccf;border-radius:6px;min-height:45px;display:flex;align-items:center;justify-content:center;position:relative;font-size:14px;font-weight:700}.tile.active{border:2px solid #b2914b;background:#f8f0db}.tile.pieceblue{border-bottom:5px solid #2985ac}.tile small{position:absolute;font-size:7px;bottom:1px;letter-spacing:.05em}#message{font-size:13px;min-height:42px;margin:18px 0 7px;font-weight:600}.actions{display:flex;gap:7px;flex-wrap:wrap}.actions button{font-size:12px;flex:1;white-space:nowrap}.primary{background:#1e4b3d;color:white;border-color:#1e4b3d}.primary:hover{background:#32664f}.support{display:flex;justify-content:space-between;margin-top:12px}.support button{font-size:11px;border:0;background:none;padding:5px 0;text-decoration:underline;text-underline-offset:3px}.fine{font-size:10px;color:var(--muted);margin:15px 0 0}#review{border-top:1px solid var(--line);margin-top:18px;padding-top:12px}#review h3{font:20px Georgia;margin:0}#solution{font-family:monospace;line-height:1.8}#review-label{font-size:12px}#nextcase{font-size:12px}footer{font-size:11px;color:var(--muted);border-top:1px solid var(--line);padding-top:20px;margin-top:35px}dialog{max-width:590px;width:calc(100% - 30px);border:1px solid #bdc7b3;border-radius:14px;background:var(--paper);color:var(--ink);padding:28px;box-shadow:0 30px 100px #0004}dialog::backdrop{background:#102c27b8;backdrop-filter:blur(4px)}dialog p,dialog li{font-size:13px}dialog li{margin:11px 0}dialog li b{display:inline-block;border-radius:3px;padding:1px 6px}.dialoghead{display:flex;justify-content:space-between;align-items:center;gap:10px}.dialoghead button{border:0;background:none;font-size:24px;padding:0 8px}#promotion-options{display:flex;gap:9px}#promotion-options button{font-size:32px}#rules ul{padding-left:18px}.source{max-width:850px}.source pre{white-space:pre-wrap;word-break:break-word;font-size:12px} @media(max-width:760px){header{padding:15px 18px}nav{gap:8px;font-size:10px}.brand{font-size:12px;gap:7px}.brand small{font-size:7px}.crest{font-size:30px}main{padding:25px 16px}.intro{gap:15px}h1{font-size:34px}.scorecard{display:none}.toolbar{flex-wrap:wrap;gap:6px}.toolbar #puzzle-meta{width:100%;margin:3px 0 0}.game{grid-template-columns:1fr;gap:25px}.square{font-size:clamp(25px,8vw,50px)}.boardpanel{max-width:510px;width:100%;margin:auto}.notebook{max-width:510px;width:100%;margin:auto;padding:18px}.legal label{max-width:none}.eyebrow{font-size:8px}.lede{font-size:12px}.toolbar button,.toolbar select{font-size:12px;padding:7px 9px}footer{line-height:1.8}.tile{min-height:44px}.actions button{padding:10px 8px}.notebook h2{font-size:27px}}@media(prefers-reduced-motion:reduce){*{transition:none!important;scroll-behavior:auto!important}} FILE: icon.svg ♞ FILE: metadata.json { "title": "Five Ply \u00b7 Chessguessr", "slug": "five-ply-chessguessr", "repository": "https://github.com/Assios/chessguessr", "source": "https://github.com/Assios/chessguessr/tree/0d09a53b118727eedc138062ef2e9980564edd05", "stars_observed": 105, "license": "GPL-3.0", "last_pushed": "2026-10-25T18:29:35Z", "tags": [ "github-source", "game" ], "adaptations": [ "Static vanilla UI in place of Remix/Firebase", "Original feedback function and 1594 puzzle records retained", "Local chess.js legal move engine", "Local progress, assisted hints, submitted-line and solution replay", "Original Unicode chess display; no external assets or authentication" ] } FILE: vendor/chess.js /* * Copyright (c) 2021, Jeff Hlywa (jhlywa@gmail.com) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * *----------------------------------------------------------------------------*/ var Chess = function (fen) { var BLACK = 'b' var WHITE = 'w' var EMPTY = -1 var PAWN = 'p' var KNIGHT = 'n' var BISHOP = 'b' var ROOK = 'r' var QUEEN = 'q' var KING = 'k' var SYMBOLS = 'pnbrqkPNBRQK' var DEFAULT_POSITION = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1' var TERMINATION_MARKERS = ['1-0', '0-1', '1/2-1/2', '*'] var PAWN_OFFSETS = { b: [16, 32, 17, 15], w: [-16, -32, -17, -15], } var PIECE_OFFSETS = { n: [-18, -33, -31, -14, 18, 33, 31, 14], b: [-17, -15, 17, 15], r: [-16, 1, 16, -1], q: [-17, -16, -15, 1, 17, 16, 15, -1], k: [-17, -16, -15, 1, 17, 16, 15, -1], } // prettier-ignore var ATTACKS = [ 20, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0,20, 0, 0,20, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0,20, 0, 0, 0, 0,20, 0, 0, 0, 0, 24, 0, 0, 0, 0,20, 0, 0, 0, 0, 0, 0,20, 0, 0, 0, 24, 0, 0, 0,20, 0, 0, 0, 0, 0, 0, 0, 0,20, 0, 0, 24, 0, 0,20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,20, 2, 24, 2,20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,53, 56, 53, 2, 0, 0, 0, 0, 0, 0, 24,24,24,24,24,24,56, 0, 56,24,24,24,24,24,24, 0, 0, 0, 0, 0, 0, 2,53, 56, 53, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,20, 2, 24, 2,20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,20, 0, 0, 24, 0, 0,20, 0, 0, 0, 0, 0, 0, 0, 0,20, 0, 0, 0, 24, 0, 0, 0,20, 0, 0, 0, 0, 0, 0,20, 0, 0, 0, 0, 24, 0, 0, 0, 0,20, 0, 0, 0, 0,20, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0,20, 0, 0, 20, 0, 0, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0,20 ]; // prettier-ignore var RAYS = [ 17, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 15, 0, 0, 17, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 15, 0, 0, 0, 0, 17, 0, 0, 0, 0, 16, 0, 0, 0, 0, 15, 0, 0, 0, 0, 0, 0, 17, 0, 0, 0, 16, 0, 0, 0, 15, 0, 0, 0, 0, 0, 0, 0, 0, 17, 0, 0, 16, 0, 0, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 0, 16, 0, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 16, 15, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, -1, -1, -1,-1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0,-15,-16,-17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-15, 0,-16, 0,-17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,-15, 0, 0,-16, 0, 0,-17, 0, 0, 0, 0, 0, 0, 0, 0,-15, 0, 0, 0,-16, 0, 0, 0,-17, 0, 0, 0, 0, 0, 0,-15, 0, 0, 0, 0,-16, 0, 0, 0, 0,-17, 0, 0, 0, 0,-15, 0, 0, 0, 0, 0,-16, 0, 0, 0, 0, 0,-17, 0, 0, -15, 0, 0, 0, 0, 0, 0,-16, 0, 0, 0, 0, 0, 0,-17 ]; var SHIFTS = { p: 0, n: 1, b: 2, r: 3, q: 4, k: 5 } var FLAGS = { NORMAL: 'n', CAPTURE: 'c', BIG_PAWN: 'b', EP_CAPTURE: 'e', PROMOTION: 'p', KSIDE_CASTLE: 'k', QSIDE_CASTLE: 'q', } var BITS = { NORMAL: 1, CAPTURE: 2, BIG_PAWN: 4, EP_CAPTURE: 8, PROMOTION: 16, KSIDE_CASTLE: 32, QSIDE_CASTLE: 64, } var RANK_1 = 7 var RANK_2 = 6 var RANK_3 = 5 var RANK_4 = 4 var RANK_5 = 3 var RANK_6 = 2 var RANK_7 = 1 var RANK_8 = 0 // prettier-ignore var SQUARES = { a8: 0, b8: 1, c8: 2, d8: 3, e8: 4, f8: 5, g8: 6, h8: 7, a7: 16, b7: 17, c7: 18, d7: 19, e7: 20, f7: 21, g7: 22, h7: 23, a6: 32, b6: 33, c6: 34, d6: 35, e6: 36, f6: 37, g6: 38, h6: 39, a5: 48, b5: 49, c5: 50, d5: 51, e5: 52, f5: 53, g5: 54, h5: 55, a4: 64, b4: 65, c4: 66, d4: 67, e4: 68, f4: 69, g4: 70, h4: 71, a3: 80, b3: 81, c3: 82, d3: 83, e3: 84, f3: 85, g3: 86, h3: 87, a2: 96, b2: 97, c2: 98, d2: 99, e2: 100, f2: 101, g2: 102, h2: 103, a1: 112, b1: 113, c1: 114, d1: 115, e1: 116, f1: 117, g1: 118, h1: 119 }; var ROOKS = { w: [ { square: SQUARES.a1, flag: BITS.QSIDE_CASTLE }, { square: SQUARES.h1, flag: BITS.KSIDE_CASTLE }, ], b: [ { square: SQUARES.a8, flag: BITS.QSIDE_CASTLE }, { square: SQUARES.h8, flag: BITS.KSIDE_CASTLE }, ], } var board = new Array(128) var kings = { w: EMPTY, b: EMPTY } var turn = WHITE var castling = { w: 0, b: 0 } var ep_square = EMPTY var half_moves = 0 var move_number = 1 var history = [] var header = {} var comments = {} /* if the user passes in a fen string, load it, else default to * starting position */ if (typeof fen === 'undefined') { load(DEFAULT_POSITION) } else { load(fen) } function clear(keep_headers) { if (typeof keep_headers === 'undefined') { keep_headers = false } board = new Array(128) kings = { w: EMPTY, b: EMPTY } turn = WHITE castling = { w: 0, b: 0 } ep_square = EMPTY half_moves = 0 move_number = 1 history = [] if (!keep_headers) header = {} comments = {} update_setup(generate_fen()) } function prune_comments() { var reversed_history = [] var current_comments = {} var copy_comment = function (fen) { if (fen in comments) { current_comments[fen] = comments[fen] } } while (history.length > 0) { reversed_history.push(undo_move()) } copy_comment(generate_fen()) while (reversed_history.length > 0) { make_move(reversed_history.pop()) copy_comment(generate_fen()) } comments = current_comments } function reset() { load(DEFAULT_POSITION) } function load(fen, keep_headers) { if (typeof keep_headers === 'undefined') { keep_headers = false } var tokens = fen.split(/\s+/) var position = tokens[0] var square = 0 if (!validate_fen(fen).valid) { return false } clear(keep_headers) for (var i = 0; i < position.length; i++) { var piece = position.charAt(i) if (piece === '/') { square += 8 } else if (is_digit(piece)) { square += parseInt(piece, 10) } else { var color = piece < 'a' ? WHITE : BLACK put({ type: piece.toLowerCase(), color: color }, algebraic(square)) square++ } } turn = tokens[1] if (tokens[2].indexOf('K') > -1) { castling.w |= BITS.KSIDE_CASTLE } if (tokens[2].indexOf('Q') > -1) { castling.w |= BITS.QSIDE_CASTLE } if (tokens[2].indexOf('k') > -1) { castling.b |= BITS.KSIDE_CASTLE } if (tokens[2].indexOf('q') > -1) { castling.b |= BITS.QSIDE_CASTLE } ep_square = tokens[3] === '-' ? EMPTY : SQUARES[tokens[3]] half_moves = parseInt(tokens[4], 10) move_number = parseInt(tokens[5], 10) update_setup(generate_fen()) return true } /* TODO: this function is pretty much crap - it validates structure but * completely ignores content (e.g. doesn't verify that each side has a king) * ... we should rewrite this, and ditch the silly error_number field while * we're at it */ function validate_fen(fen) { var errors = { 0: 'No errors.', 1: 'FEN string must contain six space-delimited fields.', 2: '6th field (move number) must be a positive integer.', 3: '5th field (half move counter) must be a non-negative integer.', 4: '4th field (en-passant square) is invalid.', 5: '3rd field (castling availability) is invalid.', 6: '2nd field (side to move) is invalid.', 7: "1st field (piece positions) does not contain 8 '/'-delimited rows.", 8: '1st field (piece positions) is invalid [consecutive numbers].', 9: '1st field (piece positions) is invalid [invalid piece].', 10: '1st field (piece positions) is invalid [row too large].', 11: 'Illegal en-passant square', } /* 1st criterion: 6 space-seperated fields? */ var tokens = fen.split(/\s+/) if (tokens.length !== 6) { return { valid: false, error_number: 1, error: errors[1] } } /* 2nd criterion: move number field is a integer value > 0? */ if (isNaN(tokens[5]) || parseInt(tokens[5], 10) <= 0) { return { valid: false, error_number: 2, error: errors[2] } } /* 3rd criterion: half move counter is an integer >= 0? */ if (isNaN(tokens[4]) || parseInt(tokens[4], 10) < 0) { return { valid: false, error_number: 3, error: errors[3] } } /* 4th criterion: 4th field is a valid e.p.-string? */ if (!/^(-|[abcdefgh][36])$/.test(tokens[3])) { return { valid: false, error_number: 4, error: errors[4] } } /* 5th criterion: 3th field is a valid castle-string? */ if (!/^(KQ?k?q?|Qk?q?|kq?|q|-)$/.test(tokens[2])) { return { valid: false, error_number: 5, error: errors[5] } } /* 6th criterion: 2nd field is "w" (white) or "b" (black)? */ if (!/^(w|b)$/.test(tokens[1])) { return { valid: false, error_number: 6, error: errors[6] } } /* 7th criterion: 1st field contains 8 rows? */ var rows = tokens[0].split('/') if (rows.length !== 8) { return { valid: false, error_number: 7, error: errors[7] } } /* 8th criterion: every row is valid? */ for (var i = 0; i < rows.length; i++) { /* check for right sum of fields AND not two numbers in succession */ var sum_fields = 0 var previous_was_number = false for (var k = 0; k < rows[i].length; k++) { if (!isNaN(rows[i][k])) { if (previous_was_number) { return { valid: false, error_number: 8, error: errors[8] } } sum_fields += parseInt(rows[i][k], 10) previous_was_number = true } else { if (!/^[prnbqkPRNBQK]$/.test(rows[i][k])) { return { valid: false, error_number: 9, error: errors[9] } } sum_fields += 1 previous_was_number = false } } if (sum_fields !== 8) { return { valid: false, error_number: 10, error: errors[10] } } } if ( (tokens[3][1] == '3' && tokens[1] == 'w') || (tokens[3][1] == '6' && tokens[1] == 'b') ) { return { valid: false, error_number: 11, error: errors[11] } } /* everything's okay! */ return { valid: true, error_number: 0, error: errors[0] } } function generate_fen() { var empty = 0 var fen = '' for (var i = SQUARES.a8; i <= SQUARES.h1; i++) { if (board[i] == null) { empty++ } else { if (empty > 0) { fen += empty empty = 0 } var color = board[i].color var piece = board[i].type fen += color === WHITE ? piece.toUpperCase() : piece.toLowerCase() } if ((i + 1) & 0x88) { if (empty > 0) { fen += empty } if (i !== SQUARES.h1) { fen += '/' } empty = 0 i += 8 } } var cflags = '' if (castling[WHITE] & BITS.KSIDE_CASTLE) { cflags += 'K' } if (castling[WHITE] & BITS.QSIDE_CASTLE) { cflags += 'Q' } if (castling[BLACK] & BITS.KSIDE_CASTLE) { cflags += 'k' } if (castling[BLACK] & BITS.QSIDE_CASTLE) { cflags += 'q' } /* do we have an empty castling flag? */ cflags = cflags || '-' var epflags = ep_square === EMPTY ? '-' : algebraic(ep_square) return [fen, turn, cflags, epflags, half_moves, move_number].join(' ') } function set_header(args) { for (var i = 0; i < args.length; i += 2) { if (typeof args[i] === 'string' && typeof args[i + 1] === 'string') { header[args[i]] = args[i + 1] } } return header } /* called when the initial board setup is changed with put() or remove(). * modifies the SetUp and FEN properties of the header object. if the FEN is * equal to the default position, the SetUp and FEN are deleted * the setup is only updated if history.length is zero, ie moves haven't been * made. */ function update_setup(fen) { if (history.length > 0) return if (fen !== DEFAULT_POSITION) { header['SetUp'] = '1' header['FEN'] = fen } else { delete header['SetUp'] delete header['FEN'] } } function get(square) { var piece = board[SQUARES[square]] return piece ? { type: piece.type, color: piece.color } : null } function put(piece, square) { /* check for valid piece object */ if (!('type' in piece && 'color' in piece)) { return false } /* check for piece */ if (SYMBOLS.indexOf(piece.type.toLowerCase()) === -1) { return false } /* check for valid square */ if (!(square in SQUARES)) { return false } var sq = SQUARES[square] /* don't let the user place more than one king */ if ( piece.type == KING && !(kings[piece.color] == EMPTY || kings[piece.color] == sq) ) { return false } board[sq] = { type: piece.type, color: piece.color } if (piece.type === KING) { kings[piece.color] = sq } update_setup(generate_fen()) return true } function remove(square) { var piece = get(square) board[SQUARES[square]] = null if (piece && piece.type === KING) { kings[piece.color] = EMPTY } update_setup(generate_fen()) return piece } function build_move(board, from, to, flags, promotion) { var move = { color: turn, from: from, to: to, flags: flags, piece: board[from].type, } if (promotion) { move.flags |= BITS.PROMOTION move.promotion = promotion } if (board[to]) { move.captured = board[to].type } else if (flags & BITS.EP_CAPTURE) { move.captured = PAWN } return move } function generate_moves(options) { function add_move(board, moves, from, to, flags) { /* if pawn promotion */ if ( board[from].type === PAWN && (rank(to) === RANK_8 || rank(to) === RANK_1) ) { var pieces = [QUEEN, ROOK, BISHOP, KNIGHT] for (var i = 0, len = pieces.length; i < len; i++) { moves.push(build_move(board, from, to, flags, pieces[i])) } } else { moves.push(build_move(board, from, to, flags)) } } var moves = [] var us = turn var them = swap_color(us) var second_rank = { b: RANK_7, w: RANK_2 } var first_sq = SQUARES.a8 var last_sq = SQUARES.h1 var single_square = false /* do we want legal moves? */ var legal = typeof options !== 'undefined' && 'legal' in options ? options.legal : true var piece_type = typeof options !== 'undefined' && 'piece' in options && typeof options.piece === 'string' ? options.piece.toLowerCase() : true /* are we generating moves for a single square? */ if (typeof options !== 'undefined' && 'square' in options) { if (options.square in SQUARES) { first_sq = last_sq = SQUARES[options.square] single_square = true } else { /* invalid square */ return [] } } for (var i = first_sq; i <= last_sq; i++) { /* did we run off the end of the board */ if (i & 0x88) { i += 7 continue } var piece = board[i] if (piece == null || piece.color !== us) { continue } if (piece.type === PAWN && (piece_type === true || piece_type === PAWN)) { /* single square, non-capturing */ var square = i + PAWN_OFFSETS[us][0] if (board[square] == null) { add_move(board, moves, i, square, BITS.NORMAL) /* double square */ var square = i + PAWN_OFFSETS[us][1] if (second_rank[us] === rank(i) && board[square] == null) { add_move(board, moves, i, square, BITS.BIG_PAWN) } } /* pawn captures */ for (j = 2; j < 4; j++) { var square = i + PAWN_OFFSETS[us][j] if (square & 0x88) continue if (board[square] != null && board[square].color === them) { add_move(board, moves, i, square, BITS.CAPTURE) } else if (square === ep_square) { add_move(board, moves, i, ep_square, BITS.EP_CAPTURE) } } } else if (piece_type === true || piece_type === piece.type) { for (var j = 0, len = PIECE_OFFSETS[piece.type].length; j < len; j++) { var offset = PIECE_OFFSETS[piece.type][j] var square = i while (true) { square += offset if (square & 0x88) break if (board[square] == null) { add_move(board, moves, i, square, BITS.NORMAL) } else { if (board[square].color === us) break add_move(board, moves, i, square, BITS.CAPTURE) break } /* break, if knight or king */ if (piece.type === 'n' || piece.type === 'k') break } } } } /* check for castling if: a) we're generating all moves, or b) we're doing * single square move generation on the king's square */ if (piece_type === true || piece_type === KING) { if (!single_square || last_sq === kings[us]) { /* king-side castling */ if (castling[us] & BITS.KSIDE_CASTLE) { var castling_from = kings[us] var castling_to = castling_from + 2 if ( board[castling_from + 1] == null && board[castling_to] == null && !attacked(them, kings[us]) && !attacked(them, castling_from + 1) && !attacked(them, castling_to) ) { add_move(board, moves, kings[us], castling_to, BITS.KSIDE_CASTLE) } } /* queen-side castling */ if (castling[us] & BITS.QSIDE_CASTLE) { var castling_from = kings[us] var castling_to = castling_from - 2 if ( board[castling_from - 1] == null && board[castling_from - 2] == null && board[castling_from - 3] == null && !attacked(them, kings[us]) && !attacked(them, castling_from - 1) && !attacked(them, castling_to) ) { add_move(board, moves, kings[us], castling_to, BITS.QSIDE_CASTLE) } } } } /* return all pseudo-legal moves (this includes moves that allow the king * to be captured) */ if (!legal) { return moves } /* filter out illegal moves */ var legal_moves = [] for (var i = 0, len = moves.length; i < len; i++) { make_move(moves[i]) if (!king_attacked(us)) { legal_moves.push(moves[i]) } undo_move() } return legal_moves } /* convert a move from 0x88 coordinates to Standard Algebraic Notation * (SAN) * * @param {boolean} sloppy Use the sloppy SAN generator to work around over * disambiguation bugs in Fritz and Chessbase. See below: * * r1bqkbnr/ppp2ppp/2n5/1B1pP3/4P3/8/PPPP2PP/RNBQK1NR b KQkq - 2 4 * 4. ... Nge7 is overly disambiguated because the knight on c6 is pinned * 4. ... Ne7 is technically the valid SAN */ function move_to_san(move, moves) { var output = '' if (move.flags & BITS.KSIDE_CASTLE) { output = 'O-O' } else if (move.flags & BITS.QSIDE_CASTLE) { output = 'O-O-O' } else { if (move.piece !== PAWN) { var disambiguator = get_disambiguator(move, moves) output += move.piece.toUpperCase() + disambiguator } if (move.flags & (BITS.CAPTURE | BITS.EP_CAPTURE)) { if (move.piece === PAWN) { output += algebraic(move.from)[0] } output += 'x' } output += algebraic(move.to) if (move.flags & BITS.PROMOTION) { output += '=' + move.promotion.toUpperCase() } } make_move(move) if (in_check()) { if (in_checkmate()) { output += '#' } else { output += '+' } } undo_move() return output } // parses all of the decorators out of a SAN string function stripped_san(move) { return move.replace(/=/, '').replace(/[+#]?[?!]*$/, '') } function attacked(color, square) { for (var i = SQUARES.a8; i <= SQUARES.h1; i++) { /* did we run off the end of the board */ if (i & 0x88) { i += 7 continue } /* if empty square or wrong color */ if (board[i] == null || board[i].color !== color) continue var piece = board[i] var difference = i - square var index = difference + 119 if (ATTACKS[index] & (1 << SHIFTS[piece.type])) { if (piece.type === PAWN) { if (difference > 0) { if (piece.color === WHITE) return true } else { if (piece.color === BLACK) return true } continue } /* if the piece is a knight or a king */ if (piece.type === 'n' || piece.type === 'k') return true var offset = RAYS[index] var j = i + offset var blocked = false while (j !== square) { if (board[j] != null) { blocked = true break } j += offset } if (!blocked) return true } } return false } function king_attacked(color) { return attacked(swap_color(color), kings[color]) } function in_check() { return king_attacked(turn) } function in_checkmate() { return in_check() && generate_moves().length === 0 } function in_stalemate() { return !in_check() && generate_moves().length === 0 } function insufficient_material() { var pieces = {} var bishops = [] var num_pieces = 0 var sq_color = 0 for (var i = SQUARES.a8; i <= SQUARES.h1; i++) { sq_color = (sq_color + 1) % 2 if (i & 0x88) { i += 7 continue } var piece = board[i] if (piece) { pieces[piece.type] = piece.type in pieces ? pieces[piece.type] + 1 : 1 if (piece.type === BISHOP) { bishops.push(sq_color) } num_pieces++ } } /* k vs. k */ if (num_pieces === 2) { return true } else if ( /* k vs. kn .... or .... k vs. kb */ num_pieces === 3 && (pieces[BISHOP] === 1 || pieces[KNIGHT] === 1) ) { return true } else if (num_pieces === pieces[BISHOP] + 2) { /* kb vs. kb where any number of bishops are all on the same color */ var sum = 0 var len = bishops.length for (var i = 0; i < len; i++) { sum += bishops[i] } if (sum === 0 || sum === len) { return true } } return false } function in_threefold_repetition() { /* TODO: while this function is fine for casual use, a better * implementation would use a Zobrist key (instead of FEN). the * Zobrist key would be maintained in the make_move/undo_move functions, * avoiding the costly that we do below. */ var moves = [] var positions = {} var repetition = false while (true) { var move = undo_move() if (!move) break moves.push(move) } while (true) { /* remove the last two fields in the FEN string, they're not needed * when checking for draw by rep */ var fen = generate_fen().split(' ').slice(0, 4).join(' ') /* has the position occurred three or move times */ positions[fen] = fen in positions ? positions[fen] + 1 : 1 if (positions[fen] >= 3) { repetition = true } if (!moves.length) { break } make_move(moves.pop()) } return repetition } function push(move) { history.push({ move: move, kings: { b: kings.b, w: kings.w }, turn: turn, castling: { b: castling.b, w: castling.w }, ep_square: ep_square, half_moves: half_moves, move_number: move_number, }) } function make_move(move) { var us = turn var them = swap_color(us) push(move) board[move.to] = board[move.from] board[move.from] = null /* if ep capture, remove the captured pawn */ if (move.flags & BITS.EP_CAPTURE) { if (turn === BLACK) { board[move.to - 16] = null } else { board[move.to + 16] = null } } /* if pawn promotion, replace with new piece */ if (move.flags & BITS.PROMOTION) { board[move.to] = { type: move.promotion, color: us } } /* if we moved the king */ if (board[move.to].type === KING) { kings[board[move.to].color] = move.to /* if we castled, move the rook next to the king */ if (move.flags & BITS.KSIDE_CASTLE) { var castling_to = move.to - 1 var castling_from = move.to + 1 board[castling_to] = board[castling_from] board[castling_from] = null } else if (move.flags & BITS.QSIDE_CASTLE) { var castling_to = move.to + 1 var castling_from = move.to - 2 board[castling_to] = board[castling_from] board[castling_from] = null } /* turn off castling */ castling[us] = '' } /* turn off castling if we move a rook */ if (castling[us]) { for (var i = 0, len = ROOKS[us].length; i < len; i++) { if ( move.from === ROOKS[us][i].square && castling[us] & ROOKS[us][i].flag ) { castling[us] ^= ROOKS[us][i].flag break } } } /* turn off castling if we capture a rook */ if (castling[them]) { for (var i = 0, len = ROOKS[them].length; i < len; i++) { if ( move.to === ROOKS[them][i].square && castling[them] & ROOKS[them][i].flag ) { castling[them] ^= ROOKS[them][i].flag break } } } /* if big pawn move, update the en passant square */ if (move.flags & BITS.BIG_PAWN) { if (turn === 'b') { ep_square = move.to - 16 } else { ep_square = move.to + 16 } } else { ep_square = EMPTY } /* reset the 50 move counter if a pawn is moved or a piece is captured */ if (move.piece === PAWN) { half_moves = 0 } else if (move.flags & (BITS.CAPTURE | BITS.EP_CAPTURE)) { half_moves = 0 } else { half_moves++ } if (turn === BLACK) { move_number++ } turn = swap_color(turn) } function undo_move() { var old = history.pop() if (old == null) { return null } var move = old.move kings = old.kings turn = old.turn castling = old.castling ep_square = old.ep_square half_moves = old.half_moves move_number = old.move_number var us = turn var them = swap_color(turn) board[move.from] = board[move.to] board[move.from].type = move.piece // to undo any promotions board[move.to] = null if (move.flags & BITS.CAPTURE) { board[move.to] = { type: move.captured, color: them } } else if (move.flags & BITS.EP_CAPTURE) { var index if (us === BLACK) { index = move.to - 16 } else { index = move.to + 16 } board[index] = { type: PAWN, color: them } } if (move.flags & (BITS.KSIDE_CASTLE | BITS.QSIDE_CASTLE)) { var castling_to, castling_from if (move.flags & BITS.KSIDE_CASTLE) { castling_to = move.to + 1 castling_from = move.to - 1 } else if (move.flags & BITS.QSIDE_CASTLE) { castling_to = move.to - 2 castling_from = move.to + 1 } board[castling_to] = board[castling_from] board[castling_from] = null } return move } /* this function is used to uniquely identify ambiguous moves */ function get_disambiguator(move, moves) { var from = move.from var to = move.to var piece = move.piece var ambiguities = 0 var same_rank = 0 var same_file = 0 for (var i = 0, len = moves.length; i < len; i++) { var ambig_from = moves[i].from var ambig_to = moves[i].to var ambig_piece = moves[i].piece /* if a move of the same piece type ends on the same to square, we'll * need to add a disambiguator to the algebraic notation */ if (piece === ambig_piece && from !== ambig_from && to === ambig_to) { ambiguities++ if (rank(from) === rank(ambig_from)) { same_rank++ } if (file(from) === file(ambig_from)) { same_file++ } } } if (ambiguities > 0) { /* if there exists a similar moving piece on the same rank and file as * the move in question, use the square as the disambiguator */ if (same_rank > 0 && same_file > 0) { return algebraic(from) } else if (same_file > 0) { /* if the moving piece rests on the same file, use the rank symbol as the * disambiguator */ return algebraic(from).charAt(1) } else { /* else use the file symbol */ return algebraic(from).charAt(0) } } return '' } function infer_piece_type(san) { var piece_type = san.charAt(0) if (piece_type >= 'a' && piece_type <= 'h') { var matches = san.match(/[a-h]\d.*[a-h]\d/) if (matches) { return undefined } return PAWN } piece_type = piece_type.toLowerCase() if (piece_type === 'o') { return KING } return piece_type } function ascii() { var s = ' +------------------------+\n' for (var i = SQUARES.a8; i <= SQUARES.h1; i++) { /* display the rank */ if (file(i) === 0) { s += ' ' + '87654321'[rank(i)] + ' |' } /* empty piece */ if (board[i] == null) { s += ' . ' } else { var piece = board[i].type var color = board[i].color var symbol = color === WHITE ? piece.toUpperCase() : piece.toLowerCase() s += ' ' + symbol + ' ' } if ((i + 1) & 0x88) { s += '|\n' i += 8 } } s += ' +------------------------+\n' s += ' a b c d e f g h\n' return s } // convert a move from Standard Algebraic Notation (SAN) to 0x88 coordinates function move_from_san(move, sloppy) { // strip off any move decorations: e.g Nf3+?! becomes Nf3 var clean_move = stripped_san(move) var overly_disambiguated = false if (sloppy) { // The sloppy parser allows the user to parse non-standard chess // notations. This parser is opt-in (by specifying the // '{ sloppy: true }' setting) and is only run after the Standard // Algebraic Notation (SAN) parser has failed. // // When running the sloppy parser, we'll run a regex to grab the piece, // the to/from square, and an optional promotion piece. This regex will // parse common non-standard notation like: Pe2-e4, Rc1c4, Qf3xf7, f7f8q, // b1c3 // NOTE: Some positions and moves may be ambiguous when using the sloppy // parser. For example, in this position: 6k1/8/8/B7/8/8/8/BN4K1 w - - 0 1, // the move b1c3 may be interpreted as Nc3 or B1c3 (a disambiguated // bishop move). In these cases, the sloppy parser will default to the // most most basic interpretation - b1c3 parses to Nc3. var matches = clean_move.match( /([pnbrqkPNBRQK])?([a-h][1-8])x?-?([a-h][1-8])([qrbnQRBN])?/ ) if (matches) { var piece = matches[1] var from = matches[2] var to = matches[3] var promotion = matches[4] if (from.length == 1) { overly_disambiguated = true } } else { // The [a-h]?[1-8]? portion of the regex below handles moves that may // be overly disambiguated (e.g. Nge7 is unnecessary and non-standard // when there is one legal knight move to e7). In this case, the value // of 'from' variable will be a rank or file, not a square. var matches = clean_move.match( /([pnbrqkPNBRQK])?([a-h]?[1-8]?)x?-?([a-h][1-8])([qrbnQRBN])?/ ) if (matches) { var piece = matches[1] var from = matches[2] var to = matches[3] var promotion = matches[4] if (from.length == 1) { var overly_disambiguated = true } } } } var piece_type = infer_piece_type(clean_move) var moves = generate_moves({ legal: true, piece: piece ? piece : piece_type, }) for (var i = 0, len = moves.length; i < len; i++) { // try the strict parser first, then the sloppy parser if requested // by the user if (clean_move === stripped_san(move_to_san(moves[i], moves))) { return moves[i] } else { if (sloppy && matches) { // hand-compare move properties with the results from our sloppy // regex if ( (!piece || piece.toLowerCase() == moves[i].piece) && SQUARES[from] == moves[i].from && SQUARES[to] == moves[i].to && (!promotion || promotion.toLowerCase() == moves[i].promotion) ) { return moves[i] } else if (overly_disambiguated) { // SPECIAL CASE: we parsed a move string that may have an unneeded // rank/file disambiguator (e.g. Nge7). The 'from' variable will var square = algebraic(moves[i].from) if ( (!piece || piece.toLowerCase() == moves[i].piece) && SQUARES[to] == moves[i].to && (from == square[0] || from == square[1]) && (!promotion || promotion.toLowerCase() == moves[i].promotion) ) { return moves[i] } } } } } return null } /***************************************************************************** * UTILITY FUNCTIONS ****************************************************************************/ function rank(i) { return i >> 4 } function file(i) { return i & 15 } function algebraic(i) { var f = file(i), r = rank(i) return 'abcdefgh'.substring(f, f + 1) + '87654321'.substring(r, r + 1) } function swap_color(c) { return c === WHITE ? BLACK : WHITE } function is_digit(c) { return '0123456789'.indexOf(c) !== -1 } /* pretty = external move object */ function make_pretty(ugly_move) { var move = clone(ugly_move) move.san = move_to_san(move, generate_moves({ legal: true })) move.to = algebraic(move.to) move.from = algebraic(move.from) var flags = '' for (var flag in BITS) { if (BITS[flag] & move.flags) { flags += FLAGS[flag] } } move.flags = flags return move } function clone(obj) { var dupe = obj instanceof Array ? [] : {} for (var property in obj) { if (typeof property === 'object') { dupe[property] = clone(obj[property]) } else { dupe[property] = obj[property] } } return dupe } function trim(str) { return str.replace(/^\s+|\s+$/g, '') } /***************************************************************************** * DEBUGGING UTILITIES ****************************************************************************/ function perft(depth) { var moves = generate_moves({ legal: false }) var nodes = 0 var color = turn for (var i = 0, len = moves.length; i < len; i++) { make_move(moves[i]) if (!king_attacked(color)) { if (depth - 1 > 0) { var child_nodes = perft(depth - 1) nodes += child_nodes } else { nodes++ } } undo_move() } return nodes } return { /*************************************************************************** * PUBLIC CONSTANTS (is there a better way to do this?) **************************************************************************/ WHITE: WHITE, BLACK: BLACK, PAWN: PAWN, KNIGHT: KNIGHT, BISHOP: BISHOP, ROOK: ROOK, QUEEN: QUEEN, KING: KING, SQUARES: (function () { /* from the ECMA-262 spec (section 12.6.4): * "The mechanics of enumerating the properties ... is * implementation dependent" * so: for (var sq in SQUARES) { keys.push(sq); } might not be * ordered correctly */ var keys = [] for (var i = SQUARES.a8; i <= SQUARES.h1; i++) { if (i & 0x88) { i += 7 continue } keys.push(algebraic(i)) } return keys })(), FLAGS: FLAGS, /*************************************************************************** * PUBLIC API **************************************************************************/ load: function (fen) { return load(fen) }, reset: function () { return reset() }, moves: function (options) { /* The internal representation of a chess move is in 0x88 format, and * not meant to be human-readable. The code below converts the 0x88 * square coordinates to algebraic coordinates. It also prunes an * unnecessary move keys resulting from a verbose call. */ var ugly_moves = generate_moves(options) var moves = [] for (var i = 0, len = ugly_moves.length; i < len; i++) { /* does the user want a full move object (most likely not), or just * SAN */ if ( typeof options !== 'undefined' && 'verbose' in options && options.verbose ) { moves.push(make_pretty(ugly_moves[i])) } else { moves.push( move_to_san(ugly_moves[i], generate_moves({ legal: true })) ) } } return moves }, in_check: function () { return in_check() }, in_checkmate: function () { return in_checkmate() }, in_stalemate: function () { return in_stalemate() }, in_draw: function () { return ( half_moves >= 100 || in_stalemate() || insufficient_material() || in_threefold_repetition() ) }, insufficient_material: function () { return insufficient_material() }, in_threefold_repetition: function () { return in_threefold_repetition() }, game_over: function () { return ( half_moves >= 100 || in_checkmate() || in_stalemate() || insufficient_material() || in_threefold_repetition() ) }, validate_fen: function (fen) { return validate_fen(fen) }, fen: function () { return generate_fen() }, board: function () { var output = [], row = [] for (var i = SQUARES.a8; i <= SQUARES.h1; i++) { if (board[i] == null) { row.push(null) } else { row.push({ type: board[i].type, color: board[i].color }) } if ((i + 1) & 0x88) { output.push(row) row = [] i += 8 } } return output }, pgn: function (options) { /* using the specification from http://www.chessclub.com/help/PGN-spec * example for html usage: .pgn({ max_width: 72, newline_char: "
" }) */ var newline = typeof options === 'object' && typeof options.newline_char === 'string' ? options.newline_char : '\n' var max_width = typeof options === 'object' && typeof options.max_width === 'number' ? options.max_width : 0 var result = [] var header_exists = false /* add the PGN header headerrmation */ for (var i in header) { /* TODO: order of enumerated properties in header object is not * guaranteed, see ECMA-262 spec (section 12.6.4) */ result.push('[' + i + ' "' + header[i] + '"]' + newline) header_exists = true } if (header_exists && history.length) { result.push(newline) } var append_comment = function (move_string) { var comment = comments[generate_fen()] if (typeof comment !== 'undefined') { var delimiter = move_string.length > 0 ? ' ' : '' move_string = `${move_string}${delimiter}{${comment}}` } return move_string } /* pop all of history onto reversed_history */ var reversed_history = [] while (history.length > 0) { reversed_history.push(undo_move()) } var moves = [] var move_string = '' /* special case of a commented starting position with no moves */ if (reversed_history.length === 0) { moves.push(append_comment('')) } /* build the list of moves. a move_string looks like: "3. e3 e6" */ while (reversed_history.length > 0) { move_string = append_comment(move_string) var move = reversed_history.pop() /* if the position started with black to move, start PGN with 1. ... */ if (!history.length && move.color === 'b') { move_string = move_number + '. ...' } else if (move.color === 'w') { /* store the previous generated move_string if we have one */ if (move_string.length) { moves.push(move_string) } move_string = move_number + '.' } move_string = move_string + ' ' + move_to_san(move, generate_moves({ legal: true })) make_move(move) } /* are there any other leftover moves? */ if (move_string.length) { moves.push(append_comment(move_string)) } /* is there a result? */ if (typeof header.Result !== 'undefined') { moves.push(header.Result) } /* history should be back to what it was before we started generating PGN, * so join together moves */ if (max_width === 0) { return result.join('') + moves.join(' ') } var strip = function () { if (result.length > 0 && result[result.length - 1] === ' ') { result.pop() return true } return false } /* NB: this does not preserve comment whitespace. */ var wrap_comment = function (width, move) { for (var token of move.split(' ')) { if (!token) { continue } if (width + token.length > max_width) { while (strip()) { width-- } result.push(newline) width = 0 } result.push(token) width += token.length result.push(' ') width++ } if (strip()) { width-- } return width } /* wrap the PGN output at max_width */ var current_width = 0 for (var i = 0; i < moves.length; i++) { if (current_width + moves[i].length > max_width) { if (moves[i].includes('{')) { current_width = wrap_comment(current_width, moves[i]) continue } } /* if the current move will push past max_width */ if (current_width + moves[i].length > max_width && i !== 0) { /* don't end the line with whitespace */ if (result[result.length - 1] === ' ') { result.pop() } result.push(newline) current_width = 0 } else if (i !== 0) { result.push(' ') current_width++ } result.push(moves[i]) current_width += moves[i].length } return result.join('') }, load_pgn: function (pgn, options) { // allow the user to specify the sloppy move parser to work around over // disambiguation bugs in Fritz and Chessbase var sloppy = typeof options !== 'undefined' && 'sloppy' in options ? options.sloppy : false function mask(str) { return str.replace(/\\/g, '\\') } function has_keys(object) { for (var key in object) { return true } return false } function parse_pgn_header(header, options) { var newline_char = typeof options === 'object' && typeof options.newline_char === 'string' ? options.newline_char : '\r?\n' var header_obj = {} var headers = header.split(new RegExp(mask(newline_char))) var key = '' var value = '' for (var i = 0; i < headers.length; i++) { key = headers[i].replace(/^\[([A-Z][A-Za-z]*)\s.*\]$/, '$1') value = headers[i].replace(/^\[[A-Za-z]+\s"(.*)"\ *\]$/, '$1') if (trim(key).length > 0) { header_obj[key] = value } } return header_obj } var newline_char = typeof options === 'object' && typeof options.newline_char === 'string' ? options.newline_char : '\r?\n' // RegExp to split header. Takes advantage of the fact that header and movetext // will always have a blank line between them (ie, two newline_char's). // With default newline_char, will equal: /^(\[((?:\r?\n)|.)*\])(?:\r?\n){2}/ var header_regex = new RegExp( '^(\\[((?:' + mask(newline_char) + ')|.)*\\])' + '(?:' + mask(newline_char) + '){2}' ) // If no header given, begin with moves. var header_string = header_regex.test(pgn) ? header_regex.exec(pgn)[1] : '' // Put the board in the starting position reset() /* parse PGN header */ var headers = parse_pgn_header(header_string, options) for (var key in headers) { set_header([key, headers[key]]) } /* load the starting position indicated by [Setup '1'] and * [FEN position] */ if (headers['SetUp'] === '1') { if (!('FEN' in headers && load(headers['FEN'], true))) { // second argument to load: don't clear the headers return false } } /* NB: the regexes below that delete move numbers, recursive * annotations, and numeric annotation glyphs may also match * text in comments. To prevent this, we transform comments * by hex-encoding them in place and decoding them again after * the other tokens have been deleted. * * While the spec states that PGN files should be ASCII encoded, * we use {en,de}codeURIComponent here to support arbitrary UTF8 * as a convenience for modern users */ var to_hex = function (string) { return Array.from(string) .map(function (c) { /* encodeURI doesn't transform most ASCII characters, * so we handle these ourselves */ return c.charCodeAt(0) < 128 ? c.charCodeAt(0).toString(16) : encodeURIComponent(c).replace(/\%/g, '').toLowerCase() }) .join('') } var from_hex = function (string) { return string.length == 0 ? '' : decodeURIComponent('%' + string.match(/.{1,2}/g).join('%')) } var encode_comment = function (string) { string = string.replace(new RegExp(mask(newline_char), 'g'), ' ') return `{${to_hex(string.slice(1, string.length - 1))}}` } var decode_comment = function (string) { if (string.startsWith('{') && string.endsWith('}')) { return from_hex(string.slice(1, string.length - 1)) } } /* delete header to get the moves */ var ms = pgn .replace(header_string, '') .replace( /* encode comments so they don't get deleted below */ new RegExp(`(\{[^}]*\})+?|;([^${mask(newline_char)}]*)`, 'g'), function (match, bracket, semicolon) { return bracket !== undefined ? encode_comment(bracket) : ' ' + encode_comment(`{${semicolon.slice(1)}}`) } ) .replace(new RegExp(mask(newline_char), 'g'), ' ') /* delete recursive annotation variations */ var rav_regex = /(\([^\(\)]+\))+?/g while (rav_regex.test(ms)) { ms = ms.replace(rav_regex, '') } /* delete move numbers */ ms = ms.replace(/\d+\.(\.\.)?/g, '') /* delete ... indicating black to move */ ms = ms.replace(/\.\.\./g, '') /* delete numeric annotation glyphs */ ms = ms.replace(/\$\d+/g, '') /* trim and get array of moves */ var moves = trim(ms).split(new RegExp(/\s+/)) /* delete empty entries */ moves = moves.join(',').replace(/,,+/g, ',').split(',') var move = '' var result = '' for (var half_move = 0; half_move < moves.length; half_move++) { var comment = decode_comment(moves[half_move]) if (comment !== undefined) { comments[generate_fen()] = comment continue } move = move_from_san(moves[half_move], sloppy) /* invalid move */ if (move == null) { /* was the move an end of game marker */ if (TERMINATION_MARKERS.indexOf(moves[half_move]) > -1) { result = moves[half_move] } else { return false } } else { /* reset the end of game marker if making a valid move */ result = '' make_move(move) } } /* Per section 8.2.6 of the PGN spec, the Result tag pair must match * match the termination marker. Only do this when headers are present, * but the result tag is missing */ if (result && Object.keys(header).length && !header['Result']) { set_header(['Result', result]) } return true }, header: function () { return set_header(arguments) }, ascii: function () { return ascii() }, turn: function () { return turn }, move: function (move, options) { /* The move function can be called with in the following parameters: * * .move('Nxb7') <- where 'move' is a case-sensitive SAN string * * .move({ from: 'h7', <- where the 'move' is a move object (additional * to :'h8', fields are ignored) * promotion: 'q', * }) */ // allow the user to specify the sloppy move parser to work around over // disambiguation bugs in Fritz and Chessbase var sloppy = typeof options !== 'undefined' && 'sloppy' in options ? options.sloppy : false var move_obj = null if (typeof move === 'string') { move_obj = move_from_san(move, sloppy) } else if (typeof move === 'object') { var moves = generate_moves() /* convert the pretty move object to an ugly move object */ for (var i = 0, len = moves.length; i < len; i++) { if ( move.from === algebraic(moves[i].from) && move.to === algebraic(moves[i].to) && (!('promotion' in moves[i]) || move.promotion === moves[i].promotion) ) { move_obj = moves[i] break } } } /* failed to find move */ if (!move_obj) { return null } /* need to make a copy of move because we can't generate SAN after the * move is made */ var pretty_move = make_pretty(move_obj) make_move(move_obj) return pretty_move }, undo: function () { var move = undo_move() return move ? make_pretty(move) : null }, clear: function () { return clear() }, put: function (piece, square) { return put(piece, square) }, get: function (square) { return get(square) }, remove: function (square) { return remove(square) }, perft: function (depth) { return perft(depth) }, square_color: function (square) { if (square in SQUARES) { var sq_0x88 = SQUARES[square] return (rank(sq_0x88) + file(sq_0x88)) % 2 === 0 ? 'light' : 'dark' } return null }, history: function (options) { var reversed_history = [] var move_history = [] var verbose = typeof options !== 'undefined' && 'verbose' in options && options.verbose while (history.length > 0) { reversed_history.push(undo_move()) } while (reversed_history.length > 0) { var move = reversed_history.pop() if (verbose) { move_history.push(make_pretty(move)) } else { move_history.push(move_to_san(move, generate_moves({ legal: true }))) } make_move(move) } return move_history }, get_comment: function () { return comments[generate_fen()] }, set_comment: function (comment) { comments[generate_fen()] = comment.replace('{', '[').replace('}', ']') }, delete_comment: function () { var comment = comments[generate_fen()] delete comments[generate_fen()] return comment }, get_comments: function () { prune_comments() return Object.keys(comments).map(function (fen) { return { fen: fen, comment: comments[fen] } }) }, delete_comments: function () { prune_comments() return Object.keys(comments).map(function (fen) { var comment = comments[fen] delete comments[fen] return { fen: fen, comment: comment } }) }, } } /* export Chess object if using node or any other CommonJS compatible * environment */ if (typeof exports !== 'undefined') exports.Chess = Chess /* export Chess object for any RequireJS compatible environment */ if (typeof define !== 'undefined') define(function () { return Chess }) The full puzzle dataset is provided separately as puzzles.json in this same directory. Build with npm install --ignore-scripts, then esbuild main.js --bundle --format=iife --target=es2020 --outfile=app.js. feedback.js was adapted verbatim from useChessguessr.ts by removing TypeScript annotations.