'use strict'; const $ = (s, root = document) => root.querySelector(s); const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); const assetVersion = document.querySelector('meta[name="asset-version"]')?.content || ''; const withAssetVersion = url => { if (!assetVersion) return url; return url + (url.includes('?') ? '&' : '?') + 'v=' + encodeURIComponent(assetVersion); }; (() => { if (!assetVersion) return; const key = 'synhex-asset-version'; const prev = localStorage.getItem(key); if (prev === assetVersion) return; localStorage.setItem(key, assetVersion); if (prev) location.reload(); })(); const PIECE_COLOR_ORDER = ['White', 'Black', 'Red', 'Blue', 'Green', 'Yellow']; const CUSTOM_PIECE_SKINS = new Set(['Red', 'Blue', 'Green', 'Yellow']); const pieceFileNames = { k: 'king', q: 'queen', r: 'rook', b: 'bishop', n: 'knight', p: 'pawn' }; const HEX_DIRS = [[1, 0], [1, -1], [0, -1], [-1, 0], [-1, 1], [0, 1]]; const HEX_SIZE = 12; function customColoursDisabled () { return !!(state?.user?.disableCustomColours); } const classicPieceUrl = p => withAssetVersion(`assets/pieces/${p.toLowerCase()}${p === p.toUpperCase() ? 'l' : 'd'}t.svg`); const pieceUrl = (p, skin) => { if (!skin || customColoursDisabled() || !CUSTOM_PIECE_SKINS.has(skin)) return classicPieceUrl(p); return withAssetVersion(`assets/avatars/${skin.toLowerCase()}-${pieceFileNames[p.toLowerCase()]}.png`); }; function unitLetter (u) { if (u.role === 'vip') return 'k'; if (u.weapon === 'shotgun') return 'r'; return 'n'; } function unitPiece (u) { const g = unitLetter(u); return u.team === 'w' ? g.toUpperCase() : g; } function unitLabel (u) { if (u.role === 'vip') return 'VIP (pistol)'; if (u.weapon === 'shotgun') return 'Soldier (shotgun)'; return 'Soldier (SMG)'; } function skinForUnit (g, u) { if (!g) return null; return u.team === 'w' ? (g.pieceSkinWhite || 'White') : (g.pieceSkinBlack || 'Black'); } function displayColorFor (g) { if (!g) return 'White'; if (customColoursDisabled()) return g.color === 'w' ? 'White' : 'Black'; return g.displayColor || (g.color === 'w' ? (g.pieceSkinWhite || 'White') : (g.pieceSkinBlack || 'Black')); } function rulesColorLabel (g) { return g.color === 'w' ? 'White' : 'Black'; } function colorTagMarkup (g) { const display = displayColorFor(g); const rules = rulesColorLabel(g); const tip = !customColoursDisabled() && display !== rules ? `Playing as ${display} (${rules})` : `Playing as ${display}`; return `${esc(display)}`; } function kingAvatarUrl (color) { return withAssetVersion(`assets/avatars/${color.toLowerCase()}-king.png`); } function nextColorSkipping (current, skip) { let i = PIECE_COLOR_ORDER.indexOf(current); if (i < 0) i = 0; for (let n = 0; n < PIECE_COLOR_ORDER.length; n++) { i = (i + 1) % PIECE_COLOR_ORDER.length; if (PIECE_COLOR_ORDER[i] !== skip) return PIECE_COLOR_ORDER[i]; } return current; } const initials = name => esc(name.slice(0, 2).toUpperCase()); const avatarUrl = id => withAssetVersion(`assets/avatars/${encodeURIComponent(id)}.png`); function avatarMarkup (name, id, editable = false) { const content = id ? `` : initials(name); return editable ? `` : `${content}`; } let avatarOptions = null, avatarGroup = 'all', avatarColor = 'all'; async function chooseAvatar () { if (!state) return; showModal('

Loading the pieces…

'); modal.classList.add('avatar-picker'); try { if (!avatarOptions) { const response = await fetch(withAssetVersion('assets/avatars/catalog.json')); if (!response.ok) throw new Error('Unable to load avatars. Please try again.'); avatarOptions = await response.json(); } if (!modal.open || !modal.classList.contains('avatar-picker')) return; avatarGroup = 'all'; avatarColor = 'all'; $('#modal-content').innerHTML = `MAKE IT YOURS

A little character for your next rivalry. Select a piece to save it.

${[['all', 'All pieces'], ['standard', 'Chess'], ['fairy', 'Fairy chess']].map(([id, label]) => ``).join('')}

Pieces by Wikimedia Commons contributors. Sources & licenses ↗

`; renderAvatarChoices(); } catch (e) { toast(e.message); if (modal.classList.contains('avatar-picker')) closeModal(); } } function renderAvatarChoices () { const options = avatarOptions.filter(a => (avatarGroup === 'all' || a.group === avatarGroup) && (avatarColor === 'all' || a.color === avatarColor)); $('#avatar-choices').innerHTML = options.map(a => ``).join('') || '

No pieces in this color. Try another color.

'; $('#avatar-option-count').textContent = `${options.length} pieces`; document.querySelectorAll('[data-avatar-group]').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.avatarGroup === avatarGroup))); } function openColorPreferences () { if (!state) return; const pref = { mode: state.user.colorMode === 'custom' ? 'custom' : 'default', preferred: state.user.preferredColor || 'White', alternative: state.user.alternativeColor || 'Black' }; if (pref.preferred === pref.alternative) pref.alternative = nextColorSkipping(pref.alternative, pref.preferred); const paint = () => { showModal(`YOUR SIDE

Choose how your operatives look in new games. Opponents may use a different colour when both prefer the same one.

`); $('#color-mode-default').onchange = () => { pref.mode = 'default'; paint(); }; $('#color-mode-custom').onchange = () => { pref.mode = 'custom'; paint(); }; document.querySelectorAll('[data-color-role]').forEach(btn => { btn.onclick = () => { if (btn.dataset.colorRole === 'preferred') pref.preferred = nextColorSkipping(pref.preferred, pref.alternative); else pref.alternative = nextColorSkipping(pref.alternative, pref.preferred); paint(); }; }); $('#save-color-prefs').onclick = async () => { await action({ action: 'set_piece_colors', colorMode: pref.mode, preferredColor: pref.preferred, alternativeColor: pref.alternative }, () => { closeModal(); toast('Colour preference saved.'); }); }; }; paint(); } let state, selected = null, busy = false, drag = null, lastRender = '', toastTimer, inviteShown = false; const playback = new Map(); let inviteToken = new URLSearchParams(location.search).get('invite'); const modal = $('#modal'); function toast (message) { $('#toast').textContent = message; $('#toast').classList.add('visible'); clearTimeout(toastTimer); toastTimer = setTimeout(() => $('#toast').classList.remove('visible'), 5000); } function showModal (html) { delete $('#modal-content').dataset.rivalry; stopReplay(); modal.classList.remove('avatar-picker', 'replay-modal'); $('#modal-content').innerHTML = html; if (!modal.open) modal.showModal(); } function clearReplay () { stopReplay(); if (modal?.classList.contains('replay-modal')) { $('#modal-content').innerHTML = ''; modal.classList.remove('replay-modal'); } } function closeModal () { if (!modal) return; clearReplay(); modal.close(); } if ($('#modal-close')) $('#modal-close').onclick = closeModal; modal?.addEventListener('click', e => { if (e.target === modal) { const r = modal.getBoundingClientRect(); if (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom) closeModal(); } }); function dismissInvite () { inviteToken = null; history.replaceState(null, '', location.pathname); } modal?.addEventListener('close', () => { if (!modal.open) clearReplay(); if (inviteShown) dismissInvite(); }); const mobileLayout = matchMedia('(max-width: 760px)'); function showSidebar (open) { const sidebar = $('#sidebar'); if (!sidebar) return; sidebar.classList.toggle('open', open); sidebar.inert = mobileLayout.matches && !open; $('#sidebar-backdrop').hidden = !open; $('#friends-toggle').setAttribute('aria-expanded', String(open)); $('#main').inert = mobileLayout.matches && open; document.body.classList.toggle('sidebar-open', mobileLayout.matches && open); if (open) { $('#friends-close').focus(); animateSavedGames(); } else if (mobileLayout.matches) $('#friends-toggle').focus(); } mobileLayout.addEventListener('change', () => showSidebar(false)); if ($('#sidebar')) $('#sidebar').inert = mobileLayout.matches; if ($('#friends-toggle')) $('#friends-toggle').onclick = () => showSidebar(!$('#sidebar').classList.contains('open')); if ($('#friends-close')) $('#friends-close').onclick = () => showSidebar(false); if ($('#sidebar-backdrop')) $('#sidebar-backdrop').onclick = () => showSidebar(false); document.addEventListener('keydown', e => { if (e.key === 'Escape') { showSidebar(false); selected = null; renderGames(); } }); async function api (data) { const response = await fetch('api.php', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': state.csrf }, body: JSON.stringify(data) }); const result = await response.json(); if (!response.ok) throw new Error(result.error || 'Request failed.'); return result; } async function action (data, success) { if (busy) return; busy = true; try { const result = await api(data); selected = null; if (success) await success(result); await refresh(true); } catch (e) { toast(e.message); await refresh(true); } finally { busy = false; } } async function refresh (force = false) { if (!$('#your-games') || (busy && !force) || drag) return; try { const response = await fetch('api.php' + (inviteToken ? '?invite=' + encodeURIComponent(inviteToken) : '')); const data = await response.json(); if (response.status === 401) { showModal('

Sign in to continue

Your session has expired. Your games are saved.

Sign in'); return; } if (!response.ok) throw new Error(data.error || 'Unable to load games.'); state = data; window.synhexPwa?.sync(); if (selected) { const g = state.games.find(g => g.id === selected.game); if (!g?.yourTurn || g.version !== selected.version || g.state?.phase !== 'planning') selected = null; } const signature = JSON.stringify(data); if (signature !== lastRender) { lastRender = signature; renderGames(); renderFriends(); renderMatchmaking(); refreshRivalry(); animateSavedGames(); } if (data.invite && !inviteShown) { inviteShown = true; const i = data.invite; if (i.error) showModal(`

Invitation

${esc(i.error)}

`); else showModal(`${i.kind === 'friend' ? 'FRIEND REQUEST' : 'YOU’RE INVITED'}

${esc(i.name)} ${i.kind === 'friend' ? 'wants to be friends.' : 'challenges you.'}

${i.kind === 'friend' ? 'Accept to add each other to your friends lists.' : 'Lock your plan. The act plays when you both commit.'}

`); } window.synhexPwa?.intro(); } catch (e) { toast(e.message || 'Connection lost. We’ll try again shortly.'); } } function empty (yours) { return `
⬡

${yours ? 'Your next rivalry starts here.' : 'All caught up.'}

${yours ? 'Challenge a friend or share a game link. Your games and invitations will appear here.' : 'Games appear here while your opponent is planning or watching playback.'}

${yours ? '' : ''}
`; } function renderGames () { if (!state) return; const yours = state.games.filter(g => g.yourTurn || g.status === 'ended' && !g.rematch || g.status === 'pending' && g.incoming).sort((a, b) => a.turnOrder - b.turnOrder || a.id - b.id); const waiting = state.games.filter(g => !yours.includes(g)); $('#your-count').textContent = yours.length; $('#waiting-count').textContent = waiting.length + (state.matchmaking ? 1 : 0); $('#your-games').innerHTML = yours.map(card).join('') || empty(true); $('#waiting-games').innerHTML = (state.matchmaking ? matchmakingCard() : '') + waiting.map(card).join('') || empty(false); for (const el of document.querySelectorAll('#main .material-bar')) { const fill = $('.material-white', el), share = Number(el.dataset.share); fill.animate([{ transform: `scaleX(${share})` }], { duration: 0, fill: 'forwards' }); } window.synhexPwa?.highlight(); } function card (g) { let content = ''; if (g.replay) content = board(g); else if (g.status === 'pending') content = `
⬡

${g.incoming ? 'A little challenge?' : 'Challenge sent.'}

${g.incoming ? `${esc(g.opponent)} invited you to play.
Your board is waiting.` : `Waiting for ${esc(g.opponent)}
to accept your challenge.`}

${g.incoming ? `
` : ''}
`; else if (g.status === 'ended') content = `
${board(g)}

${g.outcome === 'win' ? 'You won!' : g.outcome === 'loss' ? 'You lost' : 'A game well matched.'}

${esc(g.reason)}${g.opponentRematch && g.canRematch ? `${esc(g.opponent)} wants a rematch.` : ''}
${g.canRematch ? `` : ''}
`; else content = board(g) + footer(g); return `
${avatarMarkup(g.opponent, g.opponentAvatar)}
${g.opponentRating}${g.status !== 'pending' ? materialBar(g) : ''}
${g.status !== 'pending' ? colorTagMarkup(g) : ''}${g.inactiveDays >= 7 ? '' : ''}
${content}
`; } function footer (g) { const phase = g.state?.phase; let status = 'Waiting'; let extra = ''; if (phase === 'planning') { status = g.state.committed ? 'Plan locked' : (g.yourTurn ? 'Plan your act' : 'Waiting for a plan'); if (g.yourTurn && !g.state.committed) extra = ``; else extra = `Act ${g.state.act + 1}`; } else if (phase === 'playback') { status = g.state.acked ? 'Waiting for opponent' : 'Act ready'; if (g.yourTurn && !g.state.acked) extra = ``; else extra = `Act ${g.state.act}`; } return ``; } function materialBarSkinName (name, fallback) { return PIECE_COLOR_ORDER.includes(name) ? name : fallback; } function materialBarSkins (g) { if (customColoursDisabled()) return { left: 'White', right: 'Black' }; return { left: materialBarSkinName(g.pieceSkinWhite, 'White'), right: materialBarSkinName(g.pieceSkinBlack, 'Black') }; } function materialBar (g) { const totals = g.strength || { w: 0, b: 0 }; const total = totals.w + totals.b, share = total ? totals.w / total : .5; const { left, right } = materialBarSkins(g); const you = g.color === 'w' ? left : right; const label = `${left}: ${totals.w} strength. ${right}: ${totals.b} strength. You play ${you}. VIP 3 · Soldier 1.`; return `
`; } function hexKey (q, r) { return q + ',' + r; } function offsetOf (q, r) { return { col: q + Math.floor(r / 2), row: r }; } function axialOf (col, row) { return { q: col - Math.floor(row / 2), r: row }; } function hexDist (a, b) { return (Math.abs(a.q - b.q) + Math.abs(a.q + a.r - b.q - b.r) + Math.abs(a.r - b.r)) / 2; } function hexNeighbors (q, r) { return HEX_DIRS.map(([dq, dr]) => ({ q: q + dq, r: r + dr })); } function hexPixel (col, row, size) { const w = Math.sqrt(3) * size; return { x: w * (col + 0.5 * (row & 1)) + size * Math.sqrt(3), y: size * 1.5 * row + size * 1.2, w }; } function hexPoints (cx, cy, size) { const pts = []; for (let i = 0; i < 6; i++) { const a = Math.PI / 180 * (60 * i - 30); pts.push(`${cx + size * Math.cos(a)},${cy + size * Math.sin(a)}`); } return pts.join(' '); } function walkableSet (g) { const walls = new Set(g.state.walls || []); const set = new Set(); const cols = g.state.grid.cols, rows = g.state.grid.rows; for (let row = 0; row < rows; row++) for (let col = 0; col < cols; col++) { const { q, r } = axialOf(col, row); const k = hexKey(q, r); if (!walls.has(k)) set.add(k); } return set; } function hexPath (from, to, walkable) { const start = hexKey(from.q, from.r), goal = hexKey(to.q, to.r); if (!walkable.has(start) || !walkable.has(goal)) return null; if (start === goal) return [from]; const open = new Map([[start, 0]]), came = new Map(), gScore = new Map([[start, 0]]); while (open.size) { let current = null, best = Infinity; for (const [k, f] of open) if (f < best) { best = f; current = k; } open.delete(current); if (current === goal) { const path = []; while (current !== start) { const [q, r] = current.split(',').map(Number); path.push({ q, r }); current = came.get(current); } path.push(from); return path.reverse(); } const [cq, cr] = current.split(',').map(Number); for (const n of hexNeighbors(cq, cr)) { const nk = hexKey(n.q, n.r); if (!walkable.has(nk)) continue; const tg = gScore.get(current) + 1; if (!gScore.has(nk) || tg < gScore.get(nk)) { came.set(nk, current); gScore.set(nk, tg); open.set(nk, tg + hexDist(n, to)); } } } return null; } function currentUnits (g) { const play = playback.get(g.id); if (play?.units) return play.units; return g.state?.units || []; } function board (g) { if (!g.state?.grid) return '

Loading board…

'; const cols = g.state.grid.cols, rows = g.state.grid.rows; const size = HEX_SIZE; const width = Math.sqrt(3) * size * (cols + 1.2); const height = size * 1.5 * rows + size * 2.2; const walls = new Set(g.state.walls || []); const units = currentUnits(g); const mine = selected?.game === g.id ? selected : null; const pathKeys = new Set((mine?.path || []).map(p => hexKey(p.q, p.r))); const holo = hologramOf(g, mine); const play = playback.get(g.id); let hexes = ''; for (let row = 0; row < rows; row++) { for (let col = 0; col < cols; col++) { const { q, r } = axialOf(col, row); const { x, y } = hexPixel(col, row, size); const k = hexKey(q, r); const wall = walls.has(k); const classes = ['hex-cell', (col + row) % 2 ? 'odd' : '', wall ? 'wall' : '', pathKeys.has(k) ? 'path' : '', holo && holo.q === q && holo.r === r ? 'hologram-hex' : ''].filter(Boolean).join(' '); hexes += ``; } } let sprites = ''; for (const u of units) { const { col, row } = offsetOf(u.q, u.r); const { x, y } = hexPixel(col, row, size); const p = unitPiece(u); const src = pieceUrl(p, skinForUnit(g, u)); const cls = u.hologram ? 'hex-unit hologram' : 'hex-unit'; sprites += ``; const [dq, dr] = HEX_DIRS[u.facing ?? 0]; const fx = x + dq * size * 0.55, fy = y + dr * size * 0.48; sprites += ``; if (u.role === 'vip') sprites += `VIP`; } if (holo && mine) { const unit = units.find(u => u.id === mine.unitId); if (unit) { const { col, row } = offsetOf(holo.q, holo.r); const { x, y } = hexPixel(col, row, size); const p = unitPiece(unit); sprites += ``; const facing = holo.facing ?? unit.facing ?? 0; const front = hexNeighbors(holo.q, holo.r)[facing]; if (front) { const fo = offsetOf(front.q, front.r); const fp = hexPixel(fo.col, fo.row, size); sprites += ``; } } } let shots = ''; if (play?.shots) { for (const sh of play.shots) { const a = units.find(u => u.id === sh.id), b = units.find(u => u.id === (sh.victim || sh.target)); if (!a) continue; const ao = offsetOf(a.q, a.r), ap = hexPixel(ao.col, ao.row, size); const aim = sh.aim || b; if (!aim) continue; const bo = offsetOf(aim.q, aim.r), bp = hexPixel(bo.col, bo.row, size); shots += ``; } } const planning = g.yourTurn && g.state.phase === 'planning' && !g.state.committed; return `
${hexes}${shots}${sprites}
`; } function hologramOf (g, mine) { if (!mine?.path?.length) return null; const idx = mine.hologramAt == null ? mine.path.length - 1 : mine.hologramAt; return mine.path[Math.max(0, Math.min(mine.path.length - 1, idx))]; } function draftPlan (g) { const units = {}; if (selected?.game === g.id && selected.unitId) { const rest = g.state.draft?.units || {}; Object.assign(units, rest); units[selected.unitId] = { path: selected.path || [], facing: selected.facing }; } else Object.assign(units, g.state.draft?.units || {}); return { units }; } function chooseHex (g, q, r) { if (!g.yourTurn || busy || g.state.phase !== 'planning' || g.state.committed) return; const units = currentUnits(g); const unit = units.find(u => u.q === q && u.r === r && u.team === g.color && u.alive && !u.hologram); if (unit) { if (selected?.game === g.id && selected.unitId === unit.id) selected = null; else selected = { game: g.id, unitId: unit.id, path: [], version: g.version, hologramAt: null }; renderGames(); return; } if (!selected || selected.game !== g.id) return; const me = units.find(u => u.id === selected.unitId); if (!me) return; const walkable = walkableSet(g); const last = selected.path.length ? selected.path[selected.path.length - 1] : { q: me.q, r: me.r }; if (hexDist(last, { q, r }) === 1 && walkable.has(hexKey(q, r))) { selected.path = [...selected.path, { q, r }]; selected.hologramAt = selected.path.length - 1; } else { const found = hexPath(last, { q, r }, walkable); if (!found || found.length < 2) { renderGames(); return; } selected.path = selected.path.concat(found.slice(1)); selected.hologramAt = selected.path.length - 1; } renderGames(); } function setFacing (g, q, r) { if (!selected || selected.game !== g.id || !selected.path.length) return; const idx = selected.hologramAt == null ? selected.path.length - 1 : selected.hologramAt; const wp = selected.path[idx]; const dir = HEX_DIRS.findIndex(([dq, dr]) => wp.q + dq === q && wp.r + dr === r); if (dir < 0) { let best = 0, bestD = Infinity; HEX_DIRS.forEach(([dq, dr], i) => { const d = hexDist({ q: wp.q + dq, r: wp.r + dr }, { q, r }); if (d < bestD) { bestD = d; best = i; } }); selected.path[idx] = { ...wp, facing: best }; } else selected.path[idx] = { ...wp, facing: dir }; renderGames(); } function clickPathHex (g, q, r) { if (!selected || selected.game !== g.id) return false; const i = selected.path.findIndex(p => p.q === q && p.r === r); if (i < 0) return false; selected.hologramAt = i; renderGames(); return true; } function matchmakingCard () { const searching = state.matchmaking.status === 'searching'; return `
⬡

${searching ? 'Finding an opponent…' : 'No opponent found'}

${searching ? '' : ''}
`; } function renderMatchmaking () { const target = $('#matchmaking-actions'); if (!target || !state) return; target.innerHTML = state.matchmaking?.status === 'searching' ? '

Finding an opponent…

' : ''; } function renderFriends () { $('#friend-count').textContent = state.friends.length; $('#sidebar-count').textContent = state.friends.length; $('#friend-list').innerHTML = state.friends.map(f => ``).join('') || '

Your friends will appear here.
Send an invitation to get started.

'; const incoming = state.friendRequests.filter(r => r.incoming); $('#friend-requests').innerHTML = incoming.length ? '
PENDING REQUESTS
' + incoming.map(r => `
${avatarMarkup(r.name, r.avatar)}
${esc(r.name)}
`).join('') : ''; $('#friend-count').textContent = state.friends.length + incoming.length; $('#account-summary').innerHTML = `${avatarMarkup(state.user.name, state.user.avatar, true)}`; } function showRivalry (id) { const friend = state.friends.find(f => f.id === id); const game = state.games.find(g => g.opponentId === id); const f = friend || (game && { id, name: game.opponent, ...game.rivalry }); if (!f) return; const request = state.friendRequests.find(r => r.id === id); const actions = friend ? '' : request?.incoming ? `` : request ? '' : ``; showModal(`YOUR FRIENDLY RIVALRY

${esc(f.name)}

${f.wins}Wins
${f.losses}Losses
${f.ties}Ties
${actions}
`); $('#modal-content').dataset.friend = id; $('#modal-content').dataset.rivalry = id; } function refreshRivalry () { const id = $('#modal-content').dataset.rivalry; if (modal.open && id) showRivalry(id); } function options (g) { showModal(`

Your game with ${esc(g.opponent)}

${g.state?.phase === 'planning' ? 'Plan paths for your four operatives, then lock the plan. The act runs when both of you commit.' : 'Watch the same server-computed act, then plan again.'}

${g.drawOffer === 'opponent' ? '' : g.drawOffer === 'you' ? '

Draw offered.

' : ''}
`); $('#modal-content').dataset.game = g.id; } async function createLink (kind) { await action({ action: 'create_link', kind }, r => { showModal(`${kind === 'friend' ? 'GOOD COMPANY' : 'GAME ON'}

${kind === 'friend' ? 'Invite a friend.' : 'Send a little challenge.'}

Share this link. ${kind === 'friend' ? 'You’ll become friends when the other person clicks accept.' : 'The first person to accept starts a game with you.'} It expires in one month.

${kind === 'match' ? '
' : ''}`); renderMatchmaking(); }); } if ($('#match-link')) $('#match-link').onclick = () => createLink('match'); if ($('#friend-link')) $('#friend-link').onclick = () => createLink('friend'); if ($('#settings-button')) $('#settings-button').onclick = () => { if (!state) return; showModal(`

Your account

Signed in as ${esc(state.user.name)}.

${state.user.rating} Elo

${state.local ? `` : ''}Export my data (JSON)
`); $('#disable-custom-colours').onchange = e => { action({ action: 'set_disable_custom_colours', disabled: e.target.checked }, () => toast(e.target.checked ? 'Custom colours hidden.' : 'Custom colours shown.')); }; window.synhexPwa?.settings(); }; if ($('#rules-button')) $('#rules-button').onclick = () => showModal(`SYNHEX

Plan together. Fire together.

Simultaneous-turn hex tactics. Both players plan, then the server simulates a 3-second act.

`); function playTimeline (g) { const tl = g.state?.timeline; if (!tl) { action({ action: 'ack_playback', game: g.id, version: g.version }); return; } const snaps = tl.snapshots || []; if (!snaps.length || matchMedia('(prefers-reduced-motion: reduce)').matches) { playback.set(g.id, { units: tl.endUnits || snaps.at(-1)?.units, shots: tl.shots || [] }); renderGames(); action({ action: 'ack_playback', game: g.id, version: g.version }); return; } let i = 0; const play = { timer: null }; const step = () => { const snap = snaps[Math.min(i, snaps.length - 1)]; const shots = (tl.shots || []).filter(s => s.t === snap.t); playback.set(g.id, { units: snap.units, shots, timer: play.timer }); renderGames(); i++; if (i >= snaps.length) { clearInterval(play.timer); playback.set(g.id, { units: tl.endUnits || snap.units, shots: [] }); renderGames(); action({ action: 'ack_playback', game: g.id, version: g.version }, () => playback.delete(g.id)); } }; step(); play.timer = setInterval(step, Math.max(30, Math.min(120, Math.floor((tl.durationMs || 3000) / Math.max(1, snaps.length))))); } document.addEventListener('click', e => { const el = e.target.closest('button, polygon, image'); if (!el) return; const gameEl = el.closest('[data-game]'); const g = gameEl && state?.games.find(g => g.id === Number(gameEl.dataset.game)); if (el.dataset.requestAction) action({ action: el.dataset.requestAction, friend: el.dataset.requestUser }, () => { if (modal.open) closeModal(); toast(el.dataset.requestAction === 'send_friend_request' ? 'Friend request sent.' : el.dataset.requestAction === 'accept_friend_request' ? 'Friend request accepted.' : 'Friend request rejected.'); }); if (el.dataset.matchmaking) action({ action: el.dataset.matchmaking }, () => { if (modal.open) closeModal(); }); if (el.id === 'history-button') showHistory(); if (el.id === 'avatar-button') chooseAvatar(); if (el.id === 'color-pref-button') openColorPreferences(); if (el.dataset.createLink) createLink(el.dataset.createLink); if (el.dataset.hex && g) { if (suppressClick) { suppressClick = false; return; } const [q, r] = el.dataset.hex.split(',').map(Number); if (el.hasAttribute('data-facing-handle')) { setFacing(g, q, r); return; } if (clickPathHex(g, q, r)) return; chooseHex(g, q, r); } if (el.dataset.unit && g) { const u = currentUnits(g).find(u => u.id === el.dataset.unit); if (u) chooseHex(g, u.q, u.r); } if (el.dataset.gameAction && g) { if (el.dataset.gameAction === 'stop-confirm') showModal(`

This game has been inactive for ${g.inactiveDays} days. Would you like to stop it?

`); else if (el.dataset.gameAction === 'options') options(g); else if (el.dataset.gameAction === 'commit') action({ action: 'commit_plan', game: g.id, version: g.version, plan: draftPlan(g) }); else if (el.dataset.gameAction === 'play') playTimeline(g); else action({ action: el.dataset.gameAction, game: g.id, version: g.version }); } if (el.dataset.friend || el.dataset.opponent) showRivalry(el.dataset.friend || el.dataset.opponent); }); $('#modal-content').addEventListener('click', async e => { const b = e.target.closest('button'); if (!b) return; if (b.dataset.stopGame) { await action({ action: 'stop_inactive', game: Number(b.dataset.stopGame), version: Number(b.dataset.version) }, () => closeModal()); return; } if (b.dataset.avatarGroup) { avatarGroup = b.dataset.avatarGroup; renderAvatarChoices(); return; } if (b.hasAttribute('data-avatar-choice')) { await action({ action: 'set_avatar', avatar: b.dataset.avatarChoice || null }, () => { closeModal(); toast('Avatar updated.'); }); return; } if (b.dataset.modalAction === 'close') closeModal(); if (b.dataset.modalAction === 'accept-invite') await action({ action: 'accept_link', token: inviteToken }, () => { closeModal(); toast('Invitation accepted.'); }); if (b.dataset.modalAction === 'copy') { const input = $('#share-url'); try { await navigator.clipboard.writeText(input.value); b.textContent = 'Copied ✓'; } catch { input.focus(); input.select(); toast('Select and copy the link.'); } } if (b.dataset.modalAction === 'switch') await action({ endpoint: await window.synhexPwa?.endpoint(), action: 'switch_user', user: state.user.name === 'test_user_1' ? 'test_user_2' : 'test_user_1' }, () => { lastRender = ''; closeModal(); }); if (b.dataset.modalAction === 'logout') await action({ action: 'logout', endpoint: await window.synhexPwa?.endpoint() }, () => location.reload()); if (b.dataset.friendAction) { const id = $('#modal-content').dataset.friend; if (b.dataset.friendAction === 'remove') { showModal('

Remove this friend?

You will both be removed from each other’s friends list. Your game history is kept.

'); } else await action({ action: b.dataset.friendAction === 'challenge' ? 'challenge' : 'remove_friend', friend: id }, () => { closeModal(); toast(b.dataset.friendAction === 'challenge' ? 'Challenge sent.' : 'Friend removed.'); }); } if (b.dataset.option) { const g = state.games.find(g => g.id === Number($('#modal-content').dataset.game)); if (!g) return; if (b.dataset.option === 'resign-confirm') { showModal('

Resign this game?

Your opponent will win this game. You can request a rematch afterwards.

'); return; } await action({ action: b.dataset.option, game: g.id, version: g.version }, () => closeModal()); } }); $('#modal-content').addEventListener('change', e => { if (e.target.id === 'avatar-color') { avatarColor = e.target.value; renderAvatarChoices(); } }); let suppressClick = false; document.addEventListener('pointerdown', e => { const cell = e.target.closest('[data-hex], [data-unit]'); if (!cell || e.button !== 0 || busy) return; const g = state?.games.find(g => g.id === Number(cell.closest('[data-game]').dataset.game)); if (!g?.yourTurn || g.state?.phase !== 'planning' || g.state.committed) return; if (cell.hasAttribute('data-facing-handle')) { drag = { kind: 'facing', game: g.id, id: e.pointerId }; return; } const unitId = cell.dataset.unit || currentUnits(g).find(u => hexKey(u.q, u.r) === cell.dataset.hex && u.team === g.color && u.alive && !u.hologram)?.id; if (!unitId) return; const unit = currentUnits(g).find(u => u.id === unitId); selected = { game: g.id, unitId, path: [], version: g.version, hologramAt: null }; drag = { kind: 'path', game: g.id, unitId, last: { q: unit.q, r: unit.r }, id: e.pointerId, moving: false }; renderGames(); }); document.addEventListener('pointermove', e => { if (!drag || e.pointerId !== drag.id) return; const g = state.games.find(g => g.id === drag.game); if (!g) return; const el = document.elementFromPoint(e.clientX, e.clientY)?.closest('[data-hex]'); if (!el) return; const [q, r] = el.dataset.hex.split(',').map(Number); if (drag.kind === 'facing') { setFacing(g, q, r); return; } if (hexDist(drag.last, { q, r }) !== 1) return; if (!walkableSet(g).has(hexKey(q, r))) return; drag.moving = true; selected.path = [...(selected.path || []), { q, r }]; selected.hologramAt = selected.path.length - 1; drag.last = { q, r }; renderGames(); }, { passive: false }); document.addEventListener('pointerup', e => { if (!drag || e.pointerId !== drag.id) return; if (drag.moving) { suppressClick = true; setTimeout(() => suppressClick = false, 100); } drag = null; }); document.addEventListener('pointercancel', () => { drag = null; }); refresh(); setInterval(() => { if (!document.hidden) refresh(); }, 2500); document.addEventListener('visibilitychange', () => { if (!document.hidden) refresh(); }); let replay = null, replayTimer = null, historyRequest = 0; function stopReplay () { clearInterval(replayTimer); replayTimer = null; } async function historyFetch (query) { const response = await fetch('api.php?action=' + query); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Unable to load saved games.'); return data; } async function showHistory () { const request = ++historyRequest; showModal('

Loading saved games…

'); try { const games = await historyFetch('history'); if (request !== historyRequest || !modal.open || $('#modal-title')?.textContent !== 'Game history') return; $('#modal-content').innerHTML = `
${games.map(g => ``).join('') || '

No saved games yet.

'}
`; } catch (e) { toast(e.message); } } async function openReplay (id) { const source = $('#modal-content').firstElementChild; const request = ++historyRequest; try { const game = await historyFetch('replay&id=' + id); if (request !== historyRequest || !modal.open || source !== $('#modal-content').firstElementChild) return; showReplay(game); } catch (e) { toast(e.message); } } function showReplay (game) { const content = '

' + (game.shared ? 'Synhex ↗' : '') + '
'; if ($('#replay-page')) { stopReplay(); $('#modal-content').innerHTML = content; } else { showModal(content); modal.classList.add('replay-modal'); } replay = { ...game, index: 0 }; renderReplay(); } async function copyReplayLink () { const url = new URL('./', location.href); url.searchParams.set('replay', replay.shareToken); try { await navigator.clipboard.writeText(url.href); toast('Game link copied.'); } catch { const input = document.createElement('input'); input.value = url.href; input.readOnly = true; input.setAttribute('aria-label', 'Game link'); $('.replay-bottom').append(input); input.select(); toast('Select and copy the game link.'); } } function renderReplay () { if (!replay || !$('#replay-card')) return; const frame = replay.positions[replay.index] || { units: [], walls: [], grid: { cols: 17, rows: 14 } }; const g = { ...replay, id: 'replay', replay: true, status: 'replay', yourTurn: false, legal: [], state: { phase: 'replay', grid: frame.grid, walls: frame.walls, units: (frame.units || []).map(u => ({ ...u, hologram: false })), act: frame.act } }; const whiteTip = !customColoursDisabled() && (replay.pieceSkinWhite || 'White') !== 'White' ? `Playing as ${replay.pieceSkinWhite} (White)` : 'Playing as White'; const blackTip = !customColoursDisabled() && (replay.pieceSkinBlack || 'Black') !== 'Black' ? `Playing as ${replay.pieceSkinBlack} (Black)` : 'Playing as Black'; $('#replay-card').innerHTML = `
${board(g)}
`; $('#replay-progress').textContent = `${replay.index} / ${Math.max(0, replay.positions.length - 1)} · ${replay.shared ? replay.outcome : replay.outcome === 'win' ? 'Won' : replay.outcome === 'loss' ? 'Lost' : 'Draw'} · ${replay.reason}`; const last = Math.max(0, replay.positions.length - 1); $('[data-replay-control="play"]').textContent = replayTimer ? '⏸' : '▶'; $('[data-replay-control="play"]').setAttribute('aria-label', replayTimer ? 'Pause' : 'Play'); $('[data-replay-control="play"]').disabled = last < 1; $('[data-replay-control="start"]').disabled = $('[data-replay-control="back"]').disabled = replay.index === 0; $('[data-replay-control="next"]').disabled = $('[data-replay-control="end"]').disabled = replay.index === last; } $('#modal-content').addEventListener('click', e => { const b = e.target.closest('button'); if (!b) return; if (b.dataset.replayId) openReplay(b.dataset.replayId); if (b.id === 'history-return') showHistory(); if (b.id === 'replay-share') copyReplayLink(); const control = b.dataset.replayControl; if (!control || !replay) return; if (control === 'play') { if (replayTimer) stopReplay(); else { if (replay.index === replay.positions.length - 1) replay.index = 0; replayTimer = setInterval(() => { replay.index++; if (replay.index >= replay.positions.length - 1) stopReplay(); renderReplay(); }, 500); } } else { stopReplay(); const last = Math.max(0, replay.positions.length - 1); replay.index = control === 'start' ? 0 : control === 'end' ? last : Math.max(0, Math.min(last, replay.index + (control === 'back' ? -1 : 1))); } renderReplay(); }); const savedAnimations = new Set(); function animateSavedGames () { if (!state?.games) return; for (const g of state.games) { if (!g.replayId) continue; const key = `synhex-saved:${state.user.id}:${g.replayId}`; let seen = savedAnimations.has(key); try { seen ||= localStorage.getItem(key) === '1'; } catch {} const tile = $(`#your-games [data-game="${g.id}"]`), target = $('#history-button'); if (seen || !tile || !target || !target.getBoundingClientRect().width) continue; savedAnimations.add(key); try { localStorage.setItem(key, '1'); } catch {} if (matchMedia('(prefers-reduced-motion: reduce)').matches) continue; const start = tile.getBoundingClientRect(), end = target.getBoundingClientRect(); const icon = document.createElement('span'); icon.className = 'saved-hourglass'; icon.textContent = '⌛'; icon.setAttribute('aria-hidden', 'true'); icon.style.left = `${start.left + start.width / 2 - 12}px`; icon.style.top = `${start.top + 45}px`; document.body.append(icon); const flight = icon.animate([{ opacity: 0, transform: 'translate(0,0) scale(.5)' }, { opacity: 1, transform: 'translate(0,0) scale(1)', offset: .2 }, { opacity: 0, transform: `translate(${end.left + end.width / 2 - start.left - start.width / 2}px,${end.top + end.height / 2 - start.top - 57}px) scale(.5)` }], { duration: 1100, easing: 'cubic-bezier(.4,0,.2,1)' }); flight.onfinish = () => { icon.remove(); $('#history-button')?.animate([{ transform: 'translateY(0)' }, { transform: 'translateY(-9px)' }, { transform: 'translateY(0)' }], { duration: 360, easing: 'ease-out' }); }; } } if (new URLSearchParams(location.search).has('replay')) { const token = new URLSearchParams(location.search).get('replay'); fetch('api.php?action=shared_replay&token=' + encodeURIComponent(token), { credentials: 'omit' }).then(async response => { const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Unable to load saved games.'); showReplay(data); }).catch(e => { $('#modal-content').innerHTML = `

Game unavailable

${esc(e.message)}

`; }); }