chamesle

chamesle.org: the site of Chamesle, a small Linux distribution
git clone https://github.com/tortr-rs/chamesle
Log | Files | Refs | README

play.js (7199B)


      1 // the board on chess.html. chess.js knows the rules, stockfish picks its moves, this draws the board
      2 // and passes moves between them. click a piece, then where it goes.
      3 import { Chess } from './chess.js';
      4 
      5 const $ = (id) => document.getElementById(id);
      6 const boardEl = $('board'), statusEl = $('status'), movesEl = $('moves');
      7 
      8 // how hard stockfish tries, easiest first. skill is stockfish's own 0 to 20 setting
      9 const LEVELS = [
     10 	{ skill: 0, depth: 1, time: 100 },
     11 	{ skill: 4, depth: 4, time: 250 },
     12 	{ skill: 9, depth: 8, time: 500 },
     13 	{ skill: 15, depth: 14, time: 900 },
     14 	{ skill: 20, depth: 22, time: 1500 },
     15 ];
     16 // the pieces are Cburnett's drawings, the ones on wikipedia: pieces/wk.svg is the white king and so on
     17 const NAME = { k: 'king', q: 'queen', r: 'rook', b: 'bishop', n: 'knight', p: 'pawn' };
     18 
     19 let game = new Chess();
     20 let you = 'w';          // which side you play
     21 let flipped = false;    // board drawn from black's side
     22 let picked = null;      // the square you clicked first
     23 let thinking = false;   // stockfish is choosing a move
     24 let ask = 0;            // the request that counts right now
     25 const sent = [];        // every request still waiting for its bestmove, oldest first
     26 let ready = false;
     27 
     28 function remember(k, v) { try { localStorage.setItem('chess-' + k, v); } catch (e) { /* private window, fine */ } }
     29 function recall(k) { try { return localStorage.getItem('chess-' + k); } catch (e) { return null; } }
     30 
     31 // the engine runs in a worker so the page doesn't freeze while it thinks
     32 const engine = new Worker(new URL('./stockfish-19-lite-single.js', import.meta.url));
     33 engine.onmessage = (ev) => {
     34 	const line = typeof ev.data === 'string' ? ev.data : '';
     35 	if (line === 'uciok') engine.postMessage('isready');
     36 	else if (line === 'readyok' && !ready) { ready = true; update(); maybeEngine(); }
     37 	// stockfish answers every go exactly once and in order, even the stopped ones
     38 	else if (line.startsWith('bestmove')) answer(line.split(' ')[1], sent.shift());
     39 };
     40 engine.onerror = () => { statusEl.textContent = "Stockfish didn't load. Try reloading the page."; };
     41 engine.postMessage('uci');
     42 
     43 function maybeEngine() {
     44 	if (!ready || thinking || game.isGameOver() || game.turn() === you) return;
     45 	const lv = LEVELS[Number($('level').value)];
     46 	thinking = true;
     47 	sent.push(++ask);
     48 	engine.postMessage('setoption name Skill Level value ' + lv.skill);
     49 	engine.postMessage('position fen ' + game.fen());
     50 	engine.postMessage('go depth ' + lv.depth + ' movetime ' + lv.time);
     51 	update();
     52 }
     53 
     54 function answer(uci, id) {
     55 	if (id !== ask || !thinking) return;   // a move for a game that's gone
     56 	thinking = false;
     57 	if (uci && uci !== '(none)') {
     58 		try { game.move({ from: uci.slice(0, 2), to: uci.slice(2, 4), promotion: uci[4] || 'q' }); } catch (e) { /* can't happen, but don't die */ }
     59 	}
     60 	update();
     61 }
     62 
     63 function stopEngine() {
     64 	ask++;
     65 	if (thinking) engine.postMessage('stop');
     66 	thinking = false;
     67 }
     68 
     69 function click(sq) {
     70 	if (!ready || thinking || game.isGameOver() || game.turn() !== you) return;
     71 	const piece = game.get(sq);
     72 	if (picked && picked !== sq) {
     73 		const legal = game.moves({ square: picked, verbose: true }).filter((m) => m.to === sq);
     74 		if (legal.length) {
     75 			game.move({ from: picked, to: sq, promotion: legal[0].promotion ? $('promo').value : undefined });
     76 			picked = null;
     77 			update();
     78 			setTimeout(maybeEngine, 150);
     79 			return;
     80 		}
     81 	}
     82 	// pick up one of your own pieces, or put it back down
     83 	picked = piece && piece.color === you && picked !== sq ? sq : null;
     84 	update();
     85 }
     86 
     87 function draw() {
     88 	const last = game.history({ verbose: true }).slice(-1)[0];
     89 	const targets = picked ? game.moves({ square: picked, verbose: true }).map((m) => m.to) : [];
     90 	const checked = game.inCheck() ? findKing(game.turn()) : null;
     91 	const files = 'abcdefgh';
     92 	boardEl.textContent = '';
     93 	for (let row = 0; row < 8; row++) {
     94 		for (let col = 0; col < 8; col++) {
     95 			const f = flipped ? 7 - col : col, r = flipped ? row : 7 - row;
     96 			const sq = files[f] + (r + 1);
     97 			const p = game.get(sq);
     98 			const b = document.createElement('button');
     99 			b.type = 'button';
    100 			b.className = 'sq ' + ((f + r) % 2 ? 'light' : 'dark');
    101 			if (sq === picked) b.classList.add('picked');
    102 			if (last && (sq === last.from || sq === last.to)) b.classList.add('last');
    103 			if (targets.includes(sq)) b.classList.add(p ? 'take' : 'to');
    104 			if (sq === checked) b.classList.add('check');
    105 			if (p) {
    106 				const img = document.createElement('img');
    107 				img.src = new URL('./pieces/' + p.color + p.type + '.svg', import.meta.url);
    108 				img.alt = '';
    109 				img.draggable = false;
    110 				b.appendChild(img);
    111 			}
    112 			b.setAttribute('aria-label', sq + (p ? ', ' + (p.color === 'w' ? 'white ' : 'black ') + NAME[p.type] : ''));
    113 			// the letters and numbers along the edges
    114 			if (row === 7) b.appendChild(label('file', files[f]));
    115 			if (col === 0) b.appendChild(label('rank', r + 1));
    116 			b.onclick = () => click(sq);
    117 			boardEl.appendChild(b);
    118 		}
    119 	}
    120 }
    121 
    122 function label(kind, text) {
    123 	const e = document.createElement('span');
    124 	e.className = kind;
    125 	e.setAttribute('aria-hidden', 'true');
    126 	e.textContent = text;
    127 	return e;
    128 }
    129 
    130 function findKing(color) {
    131 	for (const row of game.board()) for (const p of row) if (p && p.type === 'k' && p.color === color) return p.square;
    132 	return null;
    133 }
    134 
    135 function moves() {
    136 	const h = game.history();
    137 	movesEl.textContent = '';
    138 	for (let i = 0; i < h.length; i += 2) {
    139 		const li = document.createElement('li');
    140 		li.textContent = h[i] + (h[i + 1] ? ' ' + h[i + 1] : '');
    141 		movesEl.appendChild(li);
    142 	}
    143 	movesEl.parentElement.scrollTop = movesEl.parentElement.scrollHeight;
    144 }
    145 
    146 function status() {
    147 	if (!ready) return 'Loading Stockfish...';
    148 	if (game.isCheckmate()) return game.turn() === you ? 'Checkmate. Stockfish wins.' : 'Checkmate! You win!';
    149 	if (game.isStalemate()) return 'Stalemate, a draw. No legal moves and not in check.';
    150 	if (game.isThreefoldRepetition()) return 'A draw: the same position three times.';
    151 	if (game.isInsufficientMaterial()) return "A draw: nobody has enough left to checkmate.";
    152 	if (game.isDraw()) return 'A draw: fifty moves without a capture or a pawn move.';
    153 	if (thinking) return 'Stockfish is thinking...';
    154 	return game.inCheck() ? 'Check! Your move.' : 'Your move.';
    155 }
    156 
    157 function update() {
    158 	draw();
    159 	moves();
    160 	statusEl.textContent = status();
    161 	statusEl.className = 'status' + (game.isGameOver() ? ' over' : '');
    162 }
    163 
    164 function newGame() {
    165 	stopEngine();
    166 	game = new Chess();
    167 	you = $('side').value;
    168 	flipped = you === 'b';
    169 	picked = null;
    170 	engine.postMessage('ucinewgame');
    171 	update();
    172 	maybeEngine();
    173 }
    174 
    175 $('new').onclick = newGame;
    176 $('side').onchange = () => { remember('side', $('side').value); newGame(); };
    177 $('level').onchange = () => remember('level', $('level').value);
    178 $('flip').onclick = () => { flipped = !flipped; update(); };
    179 $('undo').onclick = () => {
    180 	// back to your last turn: take back stockfish's move and yours
    181 	stopEngine();
    182 	picked = null;
    183 	game.undo();
    184 	if (game.turn() !== you) game.undo();
    185 	update();
    186 	maybeEngine();
    187 };
    188 
    189 const lv = recall('level'), sd = recall('side');
    190 if (lv !== null && LEVELS[Number(lv)]) $('level').value = lv;
    191 if (sd === 'w' || sd === 'b') $('side').value = sd;
    192 you = $('side').value;
    193 flipped = you === 'b';
    194 update();