In this section
- Rules ingest · cosmic / tools/explore/chess/rules.py lines 456–557
- Chess render · cosmic / tools/explore/chess/template/chess.css lines 1–113
- Chess render · cosmic / tools/explore/chess/template/chess.js lines 1–245
- Chess — Template Page render · cosmic / tools/explore/chess/template/index.html lines 1–79
Rules
A Python command-line tool in the chess folder of Cosmic that starts piece (`start_piece_ids`), sets fen (`set_fen`) and parses uci (`parse_uci`).
ingestcosmic / tools/explore/chess/rules.py · lines 456–557 of 557 (continued from section 1087) · Entry point · pattern outcome (shared by 2 files)
- What it does
- Defines 36 functions or classes, including sq_name, sq_parse, square_colour, start_piece_ids, Board. Uses libraries sys, time.
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- Used directly by 7 files: Board (cosmic); Furnace (cosmic); Players (cosmic); Test Board (cosmic); and 3 more. Reached from 7 other entry points, including Extras (cosmic); Page (cosmic); Ship (cosmic).
- What it achieves
- It is built from the sq name helper (`sq_name`), the sq parse helper (`sq_parse`) and the square colour helper (`square_colour`). Chess rules engine in pure Python (no dependencies): chess-rules-v1.
- Why it matters
- Imported by 5 files, including Board, Furnace and Players. Checked by 2 tests, including Test Board.
- Application
- cosmic · tools/explore/chess · Python CLI
- Uses
- sys, time
- Used by
- imported by Board (import), imported by Furnace (import), imported by Players (import), imported by Test Board (import), imported by Test Rules (import), imported by Tournament (import), imported by CI Chess Gate (sys.path import)
- Produces
- sq_name, sq_parse, square_colour, start_piece_ids, Board
- Defines here
- move_record, is_check, is_checkmate, is_stalemate, is_insufficient_material, is_threefold, is_fifty_moves, outcome, perft
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/chess/rules.py:456-557 · blob ac7f35044a66bdd39de3a575ea440c404d8d9f60 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
if promo:
s += '=' + PIECE_LETTERS[promo].upper()
else:
legal = self.legal_moves() if legal is None else legal
rivals = [o[0] for o in legal if o[1] == to and o[0] != frm and abs(b[o[0]]) == t]
dis = ''
if rivals:
if all((r & 7) != (frm & 7) for r in rivals):
dis = 'abcdefgh'[frm & 7]
elif all((r >> 4) != (frm >> 4) for r in rivals):
dis = str((frm >> 4) + 1)
else:
dis = sq_name(frm)
s = PIECE_LETTERS[t].upper() + dis + ('x' if cap else '') + sq_name(to)
self._make(m)
if self.in_check():
s += '#' if not self.legal_moves() else '+'
self._unmake()
return s
def move_record(self, m, legal=None):
"""games.json move fields for m (before it is played): piece id, from, to, capture id, check, san."""
frm, to, promo, flag = m
cap_sq = to - 16 * self.side if flag == EP else to
cap = None
if self.b[cap_sq]:
cap = self.ids[cap_sq] if self.ids is not None else PIECE_NAMES[abs(self.b[cap_sq])]
san = self.san(m, legal)
return {'piece': self.ids[frm] if self.ids is not None else PIECE_NAMES[abs(self.b[frm])],
'from': sq_name(frm), 'to': sq_name(to), 'capture': cap, 'check': san[-1] in '+#',
'san': san, 'promotion': PIECE_NAMES[promo] if promo else None,
'castle': flag == CASTLE, 'en_passant': flag == EP}
# ---------------------------------------------------------------- game end
def is_check(self):
return self.in_check()
def is_checkmate(self):
return self.in_check() and not self.legal_moves()
def is_stalemate(self):
return not self.in_check() and not self.legal_moves()
def is_insufficient_material(self):
minors = []
for sq in SQUARES:
p = self.b[sq]
if not p or abs(p) == KING:
continue
t = abs(p)
if t in (PAWN, ROOK, QUEEN):
return False
minors.append((t, p > 0, square_colour(sq)))
if len(minors) <= 1:
return True
# only bishops, all on one square colour (any sides): no mate possible
return all(t == BISHOP for t, _, _ in minors) and len({c for _, _, c in minors}) == 1
def is_threefold(self):
return self.rep.get(self.keys[-1], 0) >= 3
def is_fifty_moves(self):
return self.halfmove >= 100
def outcome(self, claim_draw=True):
"""None while the game goes on, else (result, reason). With claim_draw (default) threefold
repetition and the fifty-move rule end the game as if claimed; mate takes precedence."""
legal = self.legal_moves()
if not legal:
if self.in_check():
return ('0-1' if self.side == WHITE else '1-0', 'checkmate')
return ('1/2-1/2', 'stalemate')
if self.is_insufficient_material():
return ('1/2-1/2', 'insufficient material')
if self.rep.get(self.keys[-1], 0) >= (3 if claim_draw else 5):
return ('1/2-1/2', 'threefold repetition' if claim_draw else 'fivefold repetition')
if self.halfmove >= (100 if claim_draw else 150):
return ('1/2-1/2', 'fifty-move rule' if claim_draw else 'seventy-five-move rule')
return None
# ---------------------------------------------------------------- perft
def perft(self, depth):
if depth == 0:
return 1
side = self.side
n = 0
for m in self.pseudo_moves():
self._make(m)
if not self.attacked(self.kings[side + 1], -side):
n += 1 if depth == 1 else self.perft(depth - 1)
self._unmake()
return n
if __name__ == '__main__':
import sys
import time
fen = sys.argv[2] if len(sys.argv) > 2 else START_FEN
d = int(sys.argv[1]) if len(sys.argv) > 1 else 4
t = time.time()
n = Board(fen).perft(d)
print('perft(%d) = %d in %.2fs' % (d, n, time.time() - t))Chess
A style sheet in the template folder of Cosmic. Served with the page at https://ventusltd.github.io/cosmic/tools/explore/chess/template/.
rendercosmic / tools/explore/chess/template/chess.css · lines 1–113 of 113 · Not reached from any entry point (candidate for review)
- What it does
- Side effects: changes the web page (DOM).
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- No other file in the estate was found to import it.
- Application
- cosmic · tools/explore/chess/template · style sheet
- Uses
- none found
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/chess/template/chess.css:1-113 · blob 8ecd10645900496e3fc4373b7b719e7a949f24c4 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unreached_review
:root{--bg:#000;--panel:#0b0e14;--line:#2f343d;--ink:#fff;--muted:#a6adbb;--link:#66ccff;--accent:#00ffff;
--light:#e4e7ec;--dark:#06080c;--wfill:#f6f7f9;--wink:#000;--bfill:#000;--bink:#fff;--coord:#5d6573;
--wring:#000;--bring:#c9ced6}
/* Red theme: red and near-black squares; white pieces stay white (red glyph), black pieces stay black (white glyph),
each with an outer ring of the opposite colour, so the two sides never blur into the squares. */
body[data-theme=rb]{--light:#b3141e;--dark:#2a0507;--wfill:#ffffff;--wink:#a3121b;--bfill:#000;--bink:#fff;--coord:#ff8a90;
--wring:#000;--bring:#fff}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
html,body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.5 ui-monospace,"DejaVu Sans Mono",Menlo,Consolas,monospace;overflow-x:hidden}
a{color:var(--link)}a:focus-visible,button:focus-visible,input:focus-visible,summary:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
button{background:var(--panel);color:var(--ink);border:1px solid var(--line);font:inherit;border-radius:0;cursor:pointer;min-height:44px;min-width:44px;padding:0 10px}
button:hover{border-color:var(--accent)}
h1{font-size:20px;margin:6px 0 4px;letter-spacing:.04em}h2{font-size:14px;color:var(--accent);margin:22px 0 6px;letter-spacing:.06em;text-transform:uppercase;font-weight:normal}
.m{color:var(--muted)}
.lead{margin:2px 0 6px;color:var(--muted)}
.stars{position:fixed;inset:0;z-index:-1;pointer-events:none;opacity:.55;background-image:
radial-gradient(1px 1px at 12% 18%,#fff 50%,transparent 51%),radial-gradient(1px 1px at 72% 9%,#9ff 50%,transparent 51%),
radial-gradient(1px 1px at 33% 64%,#fff 50%,transparent 51%),radial-gradient(1px 1px at 88% 42%,#cff 50%,transparent 51%),
radial-gradient(1px 1px at 52% 88%,#fff 50%,transparent 51%),radial-gradient(1.5px 1.5px at 6% 79%,#0ff 50%,transparent 51%),
radial-gradient(1px 1px at 64% 31%,#fff 50%,transparent 51%),radial-gradient(1px 1px at 93% 73%,#fff 50%,transparent 51%),
radial-gradient(1px 1px at 22% 41%,#8cf 50%,transparent 51%),radial-gradient(1px 1px at 41% 7%,#fff 50%,transparent 51%);
background-size:420px 420px}
#bar{position:sticky;top:0;z-index:30;display:flex;align-items:center;gap:8px;padding:4px 10px;padding-top:max(4px,env(safe-area-inset-top));background:rgba(0,0,0,.92);border-bottom:1px solid var(--line)}
.brand{color:var(--link);letter-spacing:.08em;text-decoration:none;font-weight:bold;display:inline-flex;align-items:center;min-height:44px}
.crumb{color:var(--muted)}
.switch{margin-left:auto;display:inline-flex;align-items:center;gap:8px;border-color:var(--line)}
.switch .knob{width:34px;height:18px;border:1px solid var(--accent);position:relative;background:linear-gradient(90deg,#fff 50%,#000 50%)}
.switch .knob:after{content:'';position:absolute;top:2px;left:2px;width:12px;height:12px;background:var(--accent);transition:left .15s}
.switch[aria-checked=true] .knob{background:linear-gradient(90deg,#e01b24 50%,#000 50%)}
.switch[aria-checked=true] .knob:after{left:18px}
.switch .lbl{font-size:12px;color:var(--muted)}
#app{padding:0 8px 24px;max-width:1800px;margin:0 auto}
#intro details{background:rgba(11,14,20,.9);border:1px solid var(--line);border-left:2px solid var(--accent);padding:2px 12px;margin:6px 0}
#intro summary{cursor:pointer;color:var(--accent);min-height:44px;display:flex;align-items:center}
#intro ul{padding-left:18px;margin:4px 0}#intro li{margin:4px 0}
.fixture{border:1px dashed #ffd24a;color:#ffd24a;padding:6px 10px;margin:6px 0}
#gamehead{min-height:22px;margin:10px 0 4px;font-size:13px}
#boardbox{width:min(100%,calc(100vh - 210px));min-width:min(100%,300px);margin:0 auto;container-type:inline-size}
#board{display:grid;grid-template-columns:repeat(8,1fr);border:1px solid var(--line);aspect-ratio:1/1;box-shadow:0 0 0 1px #000,0 0 24px rgba(0,255,255,.08)}
.sq{position:relative;aspect-ratio:1/1;border:0;padding:0;min-width:0;min-height:0;display:flex;align-items:center;justify-content:center;outline:1px solid rgba(47,52,61,.55);outline-offset:-1px;cursor:default}
.slot{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;pointer-events:none}
.sq.l{background:var(--light)}.sq.d{background:var(--dark)}
.sq.has{cursor:pointer}
.sq .co{position:absolute;font-size:max(8px,calc(100cqw/8*.16));color:var(--coord);line-height:1;pointer-events:none}
.sq .co.f{right:2px;bottom:1px}.sq .co.r{left:2px;top:1px}
.sq.mv{box-shadow:inset 0 0 0 3px var(--accent)}
.sq.cap:after{content:'';position:absolute;inset:18%;border:2px dashed #ff6666;border-radius:50%;pointer-events:none}
.pc{width:82%;height:82%;flex:0 0 auto;overflow:hidden;border-radius:50%;border:max(3px,calc(100cqw/8*.08)) solid var(--role);display:flex;flex-direction:column;align-items:center;justify-content:center;
font-family:"DejaVu Sans","Segoe UI Symbol","Noto Sans Symbols 2",sans-serif;font-size:calc(100cqw/8*.48);line-height:1;transition:transform .2s;pointer-events:none}
.pc{box-shadow:0 0 0 1px rgba(0,0,0,.75)}
.pc.white{background:var(--wfill);color:var(--wink);box-shadow:0 0 0 2px var(--wring)}
.pc.black{background:var(--bfill);color:var(--bink);box-shadow:0 0 0 2px var(--bring)}
.pc .pl{display:none;font:calc(100cqw/8*.11)/1 ui-monospace,"DejaVu Sans Mono",monospace;max-width:92%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin-top:1px}
@container (min-width:560px){.pc .pl{display:block}.pc{font-size:calc(100cqw/8*.38)}}
.sq.sel .pc{box-shadow:0 0 0 2px var(--accent),0 0 14px var(--accent)}
#note{min-height:66px;margin:8px auto 0;max-width:820px;background:rgba(11,14,20,.92);border:1px solid var(--line);border-left:2px solid var(--accent);padding:8px 10px;font-size:13px}
#note b{color:var(--accent);font-weight:normal}
#controls{position:sticky;bottom:0;z-index:20;display:flex;flex-wrap:wrap;align-items:center;justify-content:center;gap:6px;margin:8px -8px 0;padding:8px;padding-bottom:max(8px,env(safe-area-inset-bottom));background:rgba(0,0,0,.94);border-top:1px solid var(--line)}
#controls button{font-size:20px;flex:0 0 auto;width:52px;height:48px;padding:0}
#controls button.big{width:64px;border-color:var(--accent);color:var(--accent)}
#scrub{flex:1 1 100%;order:9;height:44px;accent-color:#00ffff;margin:0;min-width:0}
#plyout{flex:0 0 auto;font-size:12px;min-width:56px;text-align:center}
#players{display:grid;grid-template-columns:1fr 1fr;gap:6px}
.pcol h3{font-size:12px;color:var(--muted);margin:0 0 4px;font-weight:normal;text-transform:uppercase;letter-spacing:.08em}
.pl-btn{display:block;width:100%;text-align:left;margin:0 0 6px;padding:6px 8px;line-height:1.35}
.pl-btn b{display:block;font-weight:normal}.pl-btn small{display:block;color:var(--muted);font-size:11px}
.pl-btn[aria-pressed=true]{border-color:var(--accent);box-shadow:inset 2px 0 0 var(--accent)}
.side-dot{display:inline-block;width:10px;height:10px;border:1px solid var(--muted);margin-right:6px;vertical-align:-1px}
.side-dot.white{background:var(--wfill)}.side-dot.black{background:#000}
#games{display:grid;gap:6px}
.g-btn{display:flex;justify-content:space-between;gap:8px;width:100%;text-align:left;padding:6px 10px;align-items:center}
.g-btn[aria-current=true]{border-color:var(--accent);color:var(--accent)}
.g-btn .res{white-space:nowrap}
.tw{overflow-x:auto}
table{border-collapse:collapse;width:100%;font-size:13px}td,th{border-bottom:1px solid var(--line);padding:6px 6px;text-align:right}
th{color:var(--accent);font-weight:normal}td:first-child,th:first-child{text-align:left}
#pieces{display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:6px}
.p-btn{display:flex;align-items:center;gap:8px;text-align:left;padding:4px 8px;width:100%;overflow:hidden}
.p-btn .gl{font-family:"DejaVu Sans",sans-serif;font-size:22px;width:30px;height:30px;flex:0 0 30px;border-radius:50%;border:3px solid var(--role);display:flex;align-items:center;justify-content:center}
.p-btn .gl.white{background:var(--wfill);color:var(--wink);box-shadow:0 0 0 2px var(--wring)}.p-btn .gl.black{background:#000;color:#fff}
.p-btn span.t{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px}
.p-btn.out{opacity:.45}
#legend{list-style:none;padding:0;margin:0;display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:2px 12px;font-size:12px}
#legend i{display:inline-block;width:11px;height:11px;margin-right:6px;vertical-align:-1px}
#scrim{position:fixed;inset:0;z-index:40;background:rgba(0,0,0,.55)}
#card{position:fixed;z-index:50;left:0;right:0;bottom:0;max-height:80vh;max-height:80dvh;overflow:auto;background:rgba(11,14,20,.98);border-top:2px solid var(--accent);padding:12px 14px calc(18px + env(safe-area-inset-bottom))}
#card .x{position:sticky;top:0;float:right;font-size:18px;z-index:2}
#card h3{font-size:17px;margin:0 52px 2px 0;color:var(--ink);font-weight:normal;overflow-wrap:anywhere}
#card h4{font-size:12px;color:var(--accent);margin:14px 0 4px;font-weight:normal;text-transform:uppercase;letter-spacing:.08em}
#card .why{border-left:2px solid var(--role,var(--accent));padding:2px 8px;margin:8px 0}
#card dl{display:grid;grid-template-columns:max-content 1fr;gap:2px 12px;margin:6px 0}#card dt{color:var(--muted)}#card dd{margin:0;overflow-wrap:anywhere}
.bar{display:grid;grid-template-columns:80px 1fr 44px;align-items:center;gap:8px;margin:5px 0;font-size:12px}
.bar .tr{height:10px;border:1px solid var(--line);background:#000}.bar .fi{height:100%;background:var(--accent)}
#card ul{list-style:none;padding:0;margin:0}#card li a{display:block;padding:10px 0;border-bottom:1px solid #161a20;overflow-wrap:anywhere;text-decoration:none}
#card li a small{color:var(--muted);display:block}
#card .tags a{display:inline-flex;align-items:center;min-height:44px;border:1px solid var(--line);padding:0 10px;margin:0 6px 6px 0;text-decoration:none}
#card .more{width:100%;margin-top:6px}
.roledot{display:inline-block;width:11px;height:11px;margin-right:6px;vertical-align:-1px}
.ns{padding:12px}.ns li{margin:6px 0}
/* Phones and narrow screens: the board comes first, the introduction after it. */
@media (max-width:999px){#app{display:flex;flex-direction:column}#play{order:1}#intro{order:2}#side{order:3}
#gamehead{margin-top:6px}}
@media (min-width:1000px){
#app{display:grid;grid-template-columns:minmax(0,1fr) minmax(340px,460px);grid-template-rows:auto 1fr;grid-template-areas:"play intro" "play side";column-gap:28px;align-items:start;padding:0 16px 24px}
#intro{grid-area:intro}#play{grid-area:play;position:sticky;top:53px}#side{grid-area:side}
#boardbox{width:min(100%,calc(100vh - 250px))}
#side h2:first-child{margin-top:10px}
#controls{position:static;margin:8px auto 0;max-width:820px;border:1px solid var(--line)}
#scrub{flex:1 1 200px;order:0}
#card{left:auto;top:0;width:440px;max-height:none;border-top:0;border-left:2px solid var(--accent)}
}
@media (prefers-reduced-motion:reduce){.pc,.switch .knob:after{transition:none}}Chess
A JavaScript file in the template folder of Cosmic that starts pos (`startPos`), loads game (`loadGame`) and renders games (`renderGames`). Served with the page at https://ventusltd.github.io/cosmic/tools/explore/chess/template/.
rendercosmic / tools/explore/chess/template/chess.js · lines 1–245 of 245 · Not reached from any entry point (candidate for review) · pattern colour (shared by 4 files)
- What it does
- It draws its content. Defines 22 functions or classes, including $, esc, colour, roleTitle, pname. Side effects: changes the web page (DOM); uses storage (browser storage, DuckDB or Parquet).
- Inputs & outputs
- In: browser storage (getItem). Out: browser storage (setItem).
- What it achieves
- It starts pos (`startPos`), loads game (`loadGame`) and renders games (`renderGames`). Defines `esc`, `colour`, `roleTitle` and 17 more. It responds to keydown events.
- Why it matters
- No other file in the estate was found to import it.
- Application
- cosmic · tools/explore/chess/template · script
- Uses
- none found
- Used by
- none found
- Produces
- $, esc, colour, roleTitle, pname, pct, startPos, compute, draw, go, stop, play
- Defines here
- $, esc, colour, roleTitle, pname, pct, startPos, compute, draw, go, stop, play, loadGame, renderGames, renderPlayers, renderTable, renderPieces, bar, fileItems, openCard, closeCard, setTheme
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/chess/template/chess.js:1-245 · blob 90e91b68c386991c7b8c98581bcc6715ea390226 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, storage · domain stage: unknown · users: none · canonical: unreached_review
(function () {
'use strict';
var D = JSON.parse(document.getElementById('data').textContent);
var GLYPH = {king: '♚', queen: '♛', rook: '♜', bishop: '♝', knight: '♞', pawn: '♟'};
var LETTER = {king: 'K', queen: 'Q', rook: 'R', bishop: 'B', knight: 'N', pawn: ''};
var ORDER = ['king', 'queen', 'rook', 'bishop', 'knight', 'pawn'];
var FILES = 'abcdefgh';
var $ = function (id) { return document.getElementById(id); };
var ROLE = {}; D.roles.forEach(function (r) { ROLE[r.id] = r; });
var PIECE = {}; D.pieces.forEach(function (p) { PIECE[p.id] = p; });
var PLAYER = {}; D.players.forEach(function (p) { PLAYER[p.id] = p; });
function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return {'&': '&', '<': '<', '>': '>', '"': '"', "'": '''}[c]; }); }
function colour(p) { var r = ROLE[p.role]; return r ? r.colour : '#4c5a65'; }
function roleTitle(p) { var r = ROLE[p.role]; return r ? r.title : (p.role || 'other'); }
function pname(id) { var p = PLAYER[id]; return p ? p.name : id; }
function pct(x) { return Math.round((+x || 0) * 100); }
/* ---------- state ---------- */
var S = {game: -1, ply: 0, timer: null, player: null, sel: null, pos: {}, types: {}, last: null};
function startPos() {
var pos = {}; D.pieces.forEach(function (p) { if (p.square) pos[p.square] = p.id; }); return pos;
}
/* Replays moves 1..ply from the start (cheap: at most a few hundred plies). Handles captures, en passant,
castling and promotion from from/to alone, so it does not depend on the generator's notation. */
function compute(ply) {
var pos = startPos(), types = {}, last = null;
var g = D.games[S.game]; var mv = g ? g.moves : [];
for (var i = 0; i < ply && i < mv.length; i++) {
var m = mv[i], id = pos[m.from] || m.piece; if (!id) continue;
var p = PIECE[id] || {type: 'pawn'}, t = types[id] || p.type, capSq = null;
if (pos[m.to]) capSq = m.to;
else if (t === 'pawn' && m.from[0] !== m.to[0]) { capSq = m.to[0] + m.from[1]; if (!pos[capSq]) capSq = null; }
if (capSq) delete pos[capSq];
delete pos[m.from];
if (t === 'king' && Math.abs(FILES.indexOf(m.from[0]) - FILES.indexOf(m.to[0])) === 2) {
var r = m.from[1], kside = m.to[0] === 'g' || FILES.indexOf(m.to[0]) > 4;
var rf = (kside ? 'h' : 'a') + r, rt = (kside ? 'f' : 'd') + r;
if (pos[rf]) { pos[rt] = pos[rf]; delete pos[rf]; }
}
pos[m.to] = id;
if (t === 'pawn' && (m.to[1] === '8' || m.to[1] === '1')) {
var pr = String(m.promotion || 'queen').toLowerCase();
types[id] = {q: 'queen', r: 'rook', b: 'bishop', n: 'knight'}[pr] || (GLYPH[pr] ? pr : 'queen');
}
last = {from: m.from, to: m.to, cap: capSq};
}
S.pos = pos; S.types = types; S.last = last;
}
/* ---------- board ---------- */
var board = $('board'), squares = {};
(function buildBoard() {
for (var r = 8; r >= 1; r--) for (var f = 0; f < 8; f++) {
var sq = FILES[f] + r, b = document.createElement('button');
b.className = 'sq ' + ((f + r) % 2 ? 'l' : 'd'); b.dataset.sq = sq; b.setAttribute('role', 'gridcell');
b.innerHTML = (f === 0 ? '<span class="co r">' + r + '</span>' : '') + (r === 1 ? '<span class="co f">' + FILES[f] + '</span>' : '') + '<span class="slot"></span>';
squares[sq] = b; board.appendChild(b);
}
})();
function draw() {
Object.keys(squares).forEach(function (sq) {
var b = squares[sq], id = S.pos[sq], slot = b.querySelector('.slot');
b.classList.toggle('mv', !!(S.last && (S.last.from === sq || S.last.to === sq)));
b.classList.toggle('cap', !!(S.last && S.last.cap === sq && S.last.cap !== S.last.to));
b.classList.toggle('sel', !!id && id === S.sel);
if (!id) {
slot.innerHTML = ''; b.classList.remove('has'); b.removeAttribute('data-id');
b.setAttribute('aria-label', sq + ' empty'); b.tabIndex = -1; return;
}
var p = PIECE[id] || {id: id, side: id[0] === 'w' ? 'white' : 'black', type: 'pawn', label: id}, t = S.types[id] || p.type;
b.classList.add('has'); b.dataset.id = id; b.tabIndex = 0;
b.setAttribute('aria-label', sq + ': ' + p.side + ' ' + t + ', ' + (p.label || '') + ' (' + roleTitle(p) + ')');
slot.innerHTML = '<span class="pc ' + p.side + '" style="--role:' + colour(p) + '">' + GLYPH[t] + '︎<span class="pl">' + esc(p.label || '') + '</span></span>';
});
var g = D.games[S.game], n = g ? g.moves.length : 0;
$('scrub').max = n; $('scrub').value = S.ply;
$('plyout').textContent = S.ply + ' / ' + n;
var note = $('note');
if (!g) { note.innerHTML = 'Pick a game to replay.'; }
else if (S.ply === 0) {
note.innerHTML = '<b>Start.</b> ' + esc(pname(g.white)) + ' (white) against ' + esc(pname(g.black)) + ' (black). Press play or step forward.';
} else {
var m = g.moves[S.ply - 1], p2 = PIECE[m.piece] || PIECE[S.pos[m.to]] || {}, mvno = Math.ceil(m.ply / 2) + (m.ply % 2 ? '.' : '...');
var df = FILES.indexOf(m.to[0]) - FILES.indexOf(m.from[0]);
var pr = m.promotion ? '=' + (LETTER[String(m.promotion).toLowerCase()] || String(m.promotion).charAt(0).toUpperCase()) : '';
var mvs = m.san || ((p2.type === 'king' && Math.abs(df) === 2) ? (df > 0 ? 'O-O' : 'O-O-O') :
(LETTER[p2.type] || '') + m.from + (m.capture ? 'x' : '-') + m.to + pr) + (m.check ? '+' : '');
var san = mvno + ' ' + mvs;
var end = S.ply === n ? ' <b>Result ' + esc(g.result) + '.</b>' : '';
note.innerHTML = '<b>' + esc(san) + '</b> ' + esc(m.note || '') + end;
}
$('first').disabled = $('prev').disabled = !g || S.ply === 0;
$('next').disabled = $('last').disabled = !g || S.ply >= n;
var playing = !!S.timer;
$('playbtn').innerHTML = playing ? '❚❚' : '▶︎';
$('playbtn').setAttribute('aria-label', playing ? 'Pause' : 'Play');
var onBoard = {}; Object.keys(S.pos).forEach(function (k) { onBoard[S.pos[k]] = 1; });
Array.prototype.forEach.call(document.querySelectorAll('.p-btn'), function (el) { el.classList.toggle('out', !onBoard[el.dataset.id]); });
}
function go(ply) {
var g = D.games[S.game]; if (!g) return;
S.ply = Math.max(0, Math.min(g.moves.length, ply)); compute(S.ply); draw();
}
function stop() { if (S.timer) { clearInterval(S.timer); S.timer = null; } }
function play() {
var g = D.games[S.game]; if (!g) return;
if (S.timer) { stop(); draw(); return; }
if (S.ply >= g.moves.length) go(0);
S.timer = setInterval(function () {
if (S.ply >= g.moves.length) { stop(); draw(); return; }
go(S.ply + 1);
}, 1100);
draw();
}
$('playbtn').onclick = play;
$('first').onclick = function () { stop(); go(0); };
$('prev').onclick = function () { stop(); go(S.ply - 1); };
$('next').onclick = function () { stop(); go(S.ply + 1); };
$('last').onclick = function () { stop(); go(1e9); };
$('scrub').oninput = function () { stop(); go(+this.value); };
document.addEventListener('keydown', function (e) {
if (e.target.tagName === 'INPUT' && e.target.type !== 'range') return;
if (e.key === 'Escape' && !$('card').hidden) { closeCard(); return; }
if (!$('card').hidden) return;
if (e.key === 'ArrowRight') { stop(); go(S.ply + 1); e.preventDefault(); }
else if (e.key === 'ArrowLeft') { stop(); go(S.ply - 1); e.preventDefault(); }
else if (e.key === ' ' && e.target === document.body) { play(); e.preventDefault(); }
});
/* ---------- games, players, table ---------- */
function loadGame(i) {
stop(); S.game = i; S.ply = 0; compute(0);
var g = D.games[i];
$('gamehead').innerHTML = g ? 'Game ' + (i + 1) + ': <span class="side-dot white"></span>' + esc(pname(g.white)) + ' v <span class="side-dot black"></span>' + esc(pname(g.black)) + ' · ' + esc(g.result) + ' · ' + g.moves.length + ' plies' : '';
Array.prototype.forEach.call(document.querySelectorAll('.g-btn'), function (b) { b.setAttribute('aria-current', +b.dataset.i === i ? 'true' : 'false'); });
draw();
}
function renderGames() {
var box = $('games'), html = '';
D.games.forEach(function (g, i) {
if (S.player && g.white !== S.player && g.black !== S.player) return;
html += '<button class="g-btn" role="listitem" data-i="' + i + '" aria-current="' + (i === S.game) + '"><span>' + (i + 1) + '. ' + esc(pname(g.white)) + ' v ' + esc(pname(g.black)) + '</span><span class="res">' + esc(g.result) + ' · ' + g.moves.length + '</span></button>';
});
box.innerHTML = html || '<p class="m">No games for this player.</p>';
}
$('games').onclick = function (e) {
var b = e.target.closest('.g-btn'); if (!b) return;
loadGame(+b.dataset.i);
$('play').scrollIntoView({behavior: 'smooth', block: 'start'});
};
function renderPlayers() {
var html = '';
['white', 'black'].forEach(function (side) {
html += '<div class="pcol"><h3><span class="side-dot ' + side + '"></span>' + side + '</h3>';
D.players.filter(function (p) { return p.side === side; }).forEach(function (p) {
html += '<button class="pl-btn" data-id="' + esc(p.id) + '" aria-pressed="' + (S.player === p.id) + '"><b>' + esc(p.name) + '</b><small>' + esc(p.strategy) + '</small></button>';
});
html += '</div>';
});
$('players').innerHTML = html;
}
$('players').onclick = function (e) {
var b = e.target.closest('.pl-btn'); if (!b) return;
S.player = S.player === b.dataset.id ? null : b.dataset.id;
renderPlayers(); renderGames();
};
function renderTable() {
var rows = D.table.map(function (r) { var o = {}; for (var k in r) o[k] = r[k]; o.pts = (r.won || 0) + 0.5 * (r.drawn || 0); return o; });
rows.sort(function (a, b) { return b.pts - a.pts || (b.won || 0) - (a.won || 0) || String(a.player).localeCompare(b.player); });
$('table').tBodies[0].innerHTML = rows.map(function (r) {
var p = PLAYER[r.player] || {side: ''};
return '<tr><td><span class="side-dot ' + esc(p.side) + '"></span>' + esc(pname(r.player)) + '</td><td>' + (r.played || 0) + '</td><td>' + (r.won || 0) + '</td><td>' + (r.drawn || 0) + '</td><td>' + (r.lost || 0) + '</td><td>' + r.pts + '</td></tr>';
}).join('');
}
function renderPieces() {
var ps = D.pieces.slice().sort(function (a, b) { return (a.side < b.side ? 1 : a.side > b.side ? -1 : 0) || ORDER.indexOf(a.type) - ORDER.indexOf(b.type) || String(a.square).localeCompare(b.square); });
$('pieces').innerHTML = ps.map(function (p) {
return '<button class="p-btn" data-id="' + esc(p.id) + '" style="--role:' + colour(p) + '" aria-label="' + esc(p.side + ' ' + p.type + ': ' + p.label) + '"><span class="gl ' + p.side + '">' + GLYPH[p.type] + '︎</span><span class="t">' + esc(p.label) + '</span></button>';
}).join('');
var used = {}; D.pieces.forEach(function (p) { used[p.role] = 1; });
$('legend').innerHTML = D.roles.filter(function (r) { return used[r.id]; }).map(function (r) { return '<li><i style="background:' + esc(r.colour) + '"></i>' + esc(r.title) + '</li>'; }).join('');
var s = D.sides || {}, t = [];
if (s.white) t.push('White: ' + s.white + '.'); if (s.black) t.push('Black: ' + s.black + '.');
$('sides').textContent = t.join(' ');
}
$('pieces').onclick = function (e) { var b = e.target.closest('.p-btn'); if (b) openCard(b.dataset.id, b); };
board.onclick = function (e) { var b = e.target.closest('.sq'); if (b && b.dataset.id) openCard(b.dataset.id, b); };
/* ---------- card ---------- */
var opener = null;
function bar(name, v) {
return '<div class="bar"><span>' + name + '</span><span class="tr" role="img" aria-label="' + name + ' ' + pct(v) + '%"><span class="fi" style="display:block;width:' + pct(v) + '%"></span></span><span>' + pct(v) + '%</span></div>';
}
function fileItems(p, from, to) {
return p.files.slice(from, to).map(function (fid) {
var f = D.files[String(fid)];
if (!f) return '<li><a>file ' + esc(fid) + '</a></li>';
return '<li><a href="' + esc(f.u || '#') + '">' + esc(f.t) + '<small>' + esc(f.r) + ' / ' + esc(f.p) + '</small></a></li>';
}).join('');
}
function openCard(id, from) {
var p = PIECE[id]; if (!p) return;
stop(); draw();
S.sel = id; opener = from || null;
var t = S.types[id] || p.type, onb = Object.keys(S.pos).some(function (k) { return S.pos[k] === id; });
var h = '<h3 id="cardtitle"><span class="roledot" style="background:' + colour(p) + '"></span>' + esc(p.label) + '</h3>';
h += '<div class="m">' + GLYPH[t] + '︎ ' + esc(p.side) + ' ' + esc(t) + (t !== p.type ? ' (promoted ' + esc(p.type) + ')' : '') + ' · starts on ' + esc(p.square) + (S.game >= 0 && !onb ? ' · captured in this game' : '') + '</div>';
h += '<div class="why" style="--role:' + colour(p) + '">' + esc(p.why || '') + '</div>';
h += '<dl><dt>role</dt><dd>' + esc(roleTitle(p)) + '</dd><dt>size</dt><dd>' + (p.size || 0) + ' files' + (p.lines ? ', ' + Number(p.lines).toLocaleString('en-GB') + ' lines' : '') + '</dd>' +
'<dt>repos</dt><dd>' + esc((p.repos || []).join(', ') || 'none') + '</dd><dt>community</dt><dd>#' + esc(p.community) + '</dd></dl>';
h += bar('reach', p.reach) + bar('unique', p.unique) + (p.centrality != null ? bar('centrality', p.centrality) : '');
h += '<p class="m" style="font-size:12px">Reach: share of its files reachable from an entry point. Unique: share not flagged as a likely duplicate. Signals for review, never for deletion.</p>';
if (p.topics && p.topics.length) h += '<h4>Explore Code topics</h4><div class="tags">' + p.topics.map(function (tp) { return '<a href="' + esc(tp.u) + '">' + esc(tp.title) + ' (' + tp.n + ')</a>'; }).join('') + '</div>';
h += '<h4>Files (' + p.files.length + (p.size > p.files.length ? ' of ' + p.size : '') + ', most central first)</h4><ul id="flist">' + fileItems(p, 0, 12) + '</ul>';
if (p.files.length > 12) h += '<button class="more" id="fmore">show all ' + p.files.length + ' files</button>';
$('cardbody').innerHTML = h;
$('card').style.setProperty('--role', colour(p));
$('card').hidden = false; $('scrim').hidden = false; $('card').scrollTop = 0;
var more = $('fmore'); if (more) more.onclick = function () { $('flist').insertAdjacentHTML('beforeend', fileItems(p, 12, p.files.length)); more.remove(); };
draw();
$('cardx').focus({preventScroll: true});
}
function closeCard() {
$('card').hidden = true; $('scrim').hidden = true; S.sel = null; draw();
if (opener && opener.focus) opener.focus({preventScroll: true});
}
$('cardx').onclick = closeCard; $('scrim').onclick = closeCard;
/* ---------- theme ---------- */
function setTheme(rb) {
document.body.dataset.theme = rb ? 'rb' : 'bw';
$('theme').setAttribute('aria-checked', rb ? 'true' : 'false');
$('theme').querySelector('.lbl').textContent = rb ? 'red & black' : 'black & white';
try { localStorage.setItem('chess-theme', rb ? 'rb' : 'bw'); } catch (e) { /* private mode */ }
}
$('theme').onclick = function () { setTheme(document.body.dataset.theme !== 'rb'); };
try { if (localStorage.getItem('chess-theme') === 'rb') setTheme(true); } catch (e) { /* ignore */ }
/* ---------- start ---------- */
if (window.innerWidth >= 1000) $('how').open = true;
renderPlayers(); renderGames(); renderTable(); renderPieces();
if (D.games.length) loadGame(0); else { compute(0); draw(); }
window.CHESS = {data: D, go: go, loadGame: loadGame, openCard: openCard, state: S};
})();Chess — Template Page
A web page in the explore folder of Cosmic that reads inputs for scrub. Published at https://ventusltd.github.io/cosmic/tools/explore/chess/template/.
rendercosmic / tools/explore/chess/template/index.html · lines 1–79 of 79 · Entry point
- What it does
- It draws its content. Side effects: changes the web page (DOM).
- Why it exists in the grid workflow
- README: "`build_graph.json` (see `GRAPH-CONTRACT.md`) feeds `visualise.py`, which writes `visual/index.html`: pipeline (Ingest / Transform / Output), estate map and topic flow, coloured by role, topic, stage or pattern, with a reachability overlay."
- Inputs & outputs
- In: form fields (user input). Out: web page.
- Downstream impact
- It is itself an entry point, published at https://ventusltd.github.io/cosmic/tools/explore/chess/template/.
- What it achieves
- A playful chess board where each piece is a community of code files in the GlobalGrid2050 estate.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- cosmic · tools/explore/chess/template · page
- Uses
- none found
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/chess/template/index.html:1-79 · blob d1f41cc1af75b298a713a4190b9d19ef6334e539 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Code chess — Explore Code — GlobalGrid2050</title>
<meta name="author" content="Ventus Ltd — GlobalGrid2050">
<meta name="description" content="A playful chess board where each piece is a community of code files in the GlobalGrid2050 estate. Replay games between ten players and tap a piece to read its code.">
<meta name="theme-color" content="#000000">
<style>
{{CSS}}
</style>
</head>
<body data-theme="bw">
<div class="stars" aria-hidden="true"></div>
<header id="bar">
<a class="brand" href="../index.html">EXPLORE CODE</a><span class="crumb">/ chess</span>
<button id="theme" class="switch" role="switch" aria-checked="false" aria-label="Red and black theme" title="Flip theme">
<span class="knob" aria-hidden="true"></span><span class="lbl">black & white</span>
</button>
</header>
<main id="app">
<section id="intro">
<h1>Code chess</h1>
<p class="lead">Each piece is a community of code files. A playful map of how they relate, not a judgement. Tap a piece, or pick a game and press play.</p>
{{FIXTURE}}
<details id="how">
<summary>How to read this</summary>
<ul>
<li>This is a playful map of how communities of code relate. It is <b>not a judgement</b> of any code or anyone who wrote it.</li>
<li>Each piece is a <b>community</b>: a group of files that import or mention each other. Its colour is the community's main job (its role), and its label comes from words the files share.</li>
<li>The most central community on each side is its king, the largest its queen; the rest follow in order.</li>
<li>Pick a game and press play. Each move has a short note about what it means for the communities, using only facts from the board.</li>
<li>Tap any piece to see its files, how much of it is reachable and unique, and links to read the code.</li>
</ul>
<p class="m">Cut {{CUT}}. <span id="sides"></span></p>
</details>
</section>
<section id="play" aria-label="Board and replay">
<div id="gamehead" class="m" aria-live="polite"></div>
<div id="boardbox"><div id="board" role="grid" aria-label="Chess board; each piece is a code community"></div></div>
<div id="note" aria-live="polite"></div>
<div id="controls" role="toolbar" aria-label="Replay controls">
<button id="first" aria-label="Back to start" title="Start">«</button>
<button id="prev" aria-label="Step back" title="Step back">‹</button>
<button id="playbtn" class="big" aria-label="Play">▶︎</button>
<button id="next" aria-label="Step forward" title="Step forward">›</button>
<button id="last" aria-label="Go to end" title="End">»</button>
<input id="scrub" type="range" min="0" max="0" value="0" aria-label="Move scrubber">
<span id="plyout" class="m"></span>
</div>
</section>
<section id="side">
<h2>Players</h2>
<p class="m">Five players take white, five take black. Pick one to see their games.</p>
<div id="players"></div>
<h2>Games</h2>
<div id="games" role="list"></div>
<h2>Results</h2>
<div class="tw"><table id="table"><thead><tr><th>player</th><th>P</th><th>W</th><th>D</th><th>L</th><th>pts</th></tr></thead><tbody></tbody></table></div>
<h2>Pieces</h2>
<p class="m">Every community on the board. Tap one for its card.</p>
<div id="pieces"></div>
<h2>Colours</h2>
<ul id="legend"></ul>
</section>
</main>
<div id="scrim" hidden></div>
<aside id="card" role="dialog" aria-modal="true" aria-labelledby="cardtitle" hidden>
<button id="cardx" class="x" aria-label="Close card">✕︎</button>
<div id="cardbody"></div>
</aside>
{{NOSCRIPT}}
<script type="application/json" id="data">{{DATA}}</script>
<script>
{{JS}}
</script>
</body>
</html>