'use strict'; var App = { screen: 'menu', games: [], game: null, selected: null, // player id or 'self-move' pollTimer: null, tickTimer: null, replay: null, // { events, index, timer, snapshot } rulesDirty: false, savingRules: false }; function $(id) { return document.getElementById(id); } function showScreen(name) { ['menu', 'lobby', 'game'].forEach(function (s) { var el = $(s); if (el) { el.hidden = s !== name; } }); App.screen = name; $('top-bar').hidden = name !== 'game'; if (name !== 'game') { App.stopReplay(); } } function showError(id, err) { var el = $(id); if (!el) { return; } if (!err) { el.hidden = true; el.textContent = ''; return; } var msg = err && (err.code || err.message) ? I18n.error(err.code || err.message) : String(err); if (err && err.status) { msg = I18n.t('error.serverStatus', { status: err.status }); } el.textContent = msg; el.hidden = false; } function initials(name) { if (!name) { return '?'; } var parts = String(name).trim().split(/\s+/); var s = parts[0].charAt(0); if (parts.length > 1) { s += parts[parts.length - 1].charAt(0); } return s.toUpperCase(); } function avatarNode(player, size, fixed) { size = size || 40; var wrap = document.createElement('span'); wrap.className = 'avatar-wrap'; wrap.style.setProperty('--c', player.color || '#fff'); wrap.style.setProperty('--sz', size + 'px'); if (fixed) { wrap.classList.add('avatar-wrap-fixed'); wrap.style.width = size + 'px'; wrap.style.height = size + 'px'; } function stylePiece(el) { el.className = (el.className ? el.className + ' ' : '') + 'piece' + (player.alive === false ? ' dead' : ''); if (fixed) { el.classList.add('piece-fixed'); el.style.width = size + 'px'; el.style.height = size + 'px'; el.style.borderColor = player.color || '#fff'; } else { el.style.borderColor = player.color || '#fff'; } } if (player.avatar) { var img = document.createElement('img'); img.alt = player.name || ''; img.width = size; img.height = size; stylePiece(img); img.src = player.avatar; img.addEventListener('error', function () { img.remove(); var fb = document.createElement('span'); fb.className = 'piece-initials'; stylePiece(fb); fb.textContent = initials(player.name); wrap.appendChild(fb); }); wrap.appendChild(img); } else { var fb = document.createElement('span'); fb.className = 'piece-initials'; stylePiece(fb); fb.textContent = initials(player.name); wrap.appendChild(fb); } return wrap; } function findPlayer(id) { if (!App.game || !App.game.players) { return null; } for (var i = 0; i < App.game.players.length; i++) { if (App.game.players[i].id === id) { return App.game.players[i]; } } return null; } function you() { return App.game ? findPlayer(App.game.you) : null; } /* ---------- init ---------- */ App.init = function () { I18n.init(); I18n.bindPicker(); I18n.onChange(function () { App.render(); }); this.bind(); this.localLinks(); var params = new URLSearchParams(location.search); var join = params.get('join'); Api.loadMe().then(function (data) { if (data.locale) { I18n.applyFromProfile(data.locale); } App.games = data.games || []; App.renderMenu(data); if (join) { if (!Api.me) { location.href = 'auth.php?next=' + encodeURIComponent('index.html?join=' + join); return; } App.doJoin(join); } }).catch(function (err) { showError('menu-error', err); App.renderMenu({}); }); this.tickTimer = setInterval(function () { App.tickClocks(); }, 250); document.addEventListener('visibilitychange', function () { if (document.hidden) { App.stopPoll(); } else if (App.game && App.screen !== 'menu') { App.refreshFull(); App.startPoll(); } }); }; App.localLinks = function () { var span = $('local-links'); if (!span) { return; } span.innerHTML = ''; for (var i = 1; i <= 8; i++) { if (i > 1) { span.appendChild(document.createTextNode(' · ')); } var a = document.createElement('a'); a.href = 'auth.php?test=' + i; a.textContent = 'test_user_' + i; span.appendChild(a); } }; App.bind = function () { $('btn-create').addEventListener('click', function () { App.createLobby(); }); $('join-form').addEventListener('submit', function (e) { e.preventDefault(); App.doJoin($('join-code').value); }); $('lobby-back').addEventListener('click', function () { App.toMenu(); }); $('btn-copy').addEventListener('click', function () { App.copyInvite(); }); $('btn-start').addEventListener('click', function () { App.startGame(); }); $('btn-leave').addEventListener('click', function () { App.leaveLobby(); }); $('btn-upgrade').addEventListener('click', function () { App.act({ type: 'upgrade' }); }); $('btn-settings').addEventListener('click', function () { $('settings-panel').hidden = false; }); $('settings-close').addEventListener('click', function () { $('settings-panel').hidden = true; }); $('btn-to-menu').addEventListener('click', function () { $('settings-panel').hidden = true; App.toMenu(); }); $('btn-surrender').addEventListener('click', function () { App.confirmSurrender(); }); $('modal-close').addEventListener('click', function () { App.closeModal(); }); $('modal').addEventListener('click', function (e) { if (e.target === $('modal')) { App.closeModal(); } }); $('sheet-close').addEventListener('click', function () { App.closeSheet(); }); $('sheet').addEventListener('click', function (e) { if (e.target === $('sheet')) { App.closeSheet(); } }); $('tl-play').addEventListener('click', function () { App.toggleReplay(); }); $('tl-live').addEventListener('click', function () { App.jumpToPresent(); }); if ($('tl-back')) { $('tl-back').addEventListener('click', function () { App.stepReplay(-1); }); } if ($('tl-fwd')) { $('tl-fwd').addEventListener('click', function () { App.stepReplay(1); }); } this.bindTimelineScrub(); this.bindRuleEditors(); document.addEventListener('keydown', function (e) { if (e.key === 'Escape') { App.closeModal(); App.closeSheet(); $('settings-panel').hidden = true; return; } App.onGameKey(e); }); }; App.onGameKey = function (e) { if (App.screen !== 'game' || !App.game) { return; } var t = e.target; var tag = (t && t.tagName) ? t.tagName.toUpperCase() : ''; if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || (t && t.isContentEditable)) { return; } if (e.altKey || e.ctrlKey || e.metaKey) { return; } if (e.key === 'ArrowLeft') { e.preventDefault(); App.stepReplay(-1); } else if (e.key === 'ArrowRight') { e.preventDefault(); App.stepReplay(1); } else if (e.key === ' ' || e.key === 'Spacebar' || e.code === 'Space') { e.preventDefault(); App.toggleReplay(); } else if (e.key === 'End') { e.preventDefault(); App.jumpToPresent(); } }; App.jumpToPresent = function () { App.stopReplay(); if (App.game) { App.renderGame(); } }; App.stepReplay = function (dir) { if (!App.game || App.game.status === 'lobby') { return; } var n = this.spendEvents(App.game).length; if (!n && dir) { return; } var idx = App.replay ? App.replay.index : n; var next = Math.max(0, Math.min(n, idx + dir)); if (App.replay && App.replay.timer) { clearInterval(App.replay.timer); App.replay.timer = null; } if (next >= n) { this.jumpToPresent(); return; } this.jumpReplay(next, { animate: dir > 0 }); }; App.bindRuleEditors = function () { ['rule-jury', 'rule-shrink', 'rule-ceasefire', 'rule-shrink-days', 'rule-ap-loot', 'rule-ap-time'].forEach(function (id) { if ($(id)) { $(id).addEventListener('change', function () { App.onRulesChange(); }); } }); if ($('rule-grid')) { $('rule-grid').addEventListener('input', function () { App.gridAuto = false; App.echoGridSide(); App.updateGridHint(); }); $('rule-grid').addEventListener('change', function () { App.gridAuto = false; var v = Rules.clampGrid($('rule-grid').value); $('rule-grid').value = String(v); App.echoGridSide(); App.onRulesChange(); }); } if ($('grid-use-suggested')) { $('grid-use-suggested').addEventListener('click', function () { App.gridAuto = true; var n = (App.game && App.game.players) ? App.game.players.length : 1; $('rule-grid').value = String(Rules.suggestedGrid(n)); App.echoGridSide(); App.onRulesChange(); }); } $('cf-add').addEventListener('click', function () { var ranges = App.currentCfRanges(); ranges.push({ start: '22:00', end: '06:00' }); App.setCfRanges(ranges); App.onRulesChange(); }); var vis = $('lobby-visibility'); if (vis) { vis.addEventListener('change', function () { App.onRulesChange(); }); } }; App.visKeys = ['vis_shots', 'vis_gifts', 'vis_ap', 'vis_range', 'vis_lives']; App.syncVisRadios = function (r, isHost) { App.visKeys.forEach(function (k) { var val = (r && r[k]) || 'public'; document.querySelectorAll('input[name="' + k + '"]').forEach(function (inp) { inp.checked = inp.value === val; inp.disabled = !isHost; }); }); }; App.readVisRules = function () { var o = {}; App.visKeys.forEach(function (k) { var inp = document.querySelector('input[name="' + k + '"]:checked'); o[k] = inp ? inp.value : 'public'; }); return o; }; App.render = function () { I18n.apply(); I18n.renderPicker(); if (App.screen === 'menu') { App.renderMenu({ games: App.games, me: Api.me, configured: Api.configured, local: Api.local }); } else if (App.screen === 'lobby') { App.renderLobby(); } else if (App.screen === 'game') { App.renderGame(); } }; /* ---------- menu ---------- */ App.renderMenu = function (data) { showScreen('menu'); App.stopPoll(); data = data || {}; var me = data.me !== undefined ? data.me : Api.me; $('menu-guest').hidden = !!me; $('menu-user').hidden = !me; $('menu-guest-hint').hidden = !!me; $('menu-actions').hidden = !me; $('my-games').hidden = !me; $('menu-unconfigured').hidden = !!Api.configured || !!Api.local; $('menu-local-login').hidden = !Api.local; if (me) { $('menu-name').textContent = me.name; var av = $('menu-avatar'); if (me.avatar) { av.src = me.avatar; av.hidden = false; } else { av.hidden = true; } } App.games = data.games || App.games || []; var list = $('games-list'); list.innerHTML = ''; $('no-games').hidden = App.games.length > 0; App.games.forEach(function (g) { var li = document.createElement('li'); var info = document.createElement('div'); info.style.flex = '1'; var st = g.status === 'lobby' ? I18n.t('menu.statusLobby') : g.status === 'finished' ? I18n.t('menu.statusFinished') : I18n.t('menu.statusRunning'); var sub = I18n.plural('lobby.playerCount', g.players); if (g.status === 'finished') { if (g.draw) { sub = I18n.t('menu.draw'); } else if (g.you_won) { sub = I18n.t('menu.youWon'); } else { var w = (g.names || []).filter(function (p) { return p.id === g.winner_id; })[0]; sub = I18n.t('menu.winnerIs', { name: w ? w.name : '?' }); } } info.innerHTML = '' + st + ' · ' + escapeHtml(g.code) + '
' + escapeHtml(sub) + ''; var btn = document.createElement('button'); btn.type = 'button'; btn.textContent = I18n.t(g.status === 'finished' ? 'menu.open' : 'menu.continue'); btn.addEventListener('click', function () { App.openGame(g.id, g.status); }); li.appendChild(info); li.appendChild(btn); list.appendChild(li); }); I18n.apply($('menu')); }; App.toMenu = function () { App.game = null; App.selected = null; App.stopPoll(); Api.games().then(function (data) { App.games = data.games || []; App.renderMenu(data); }).catch(function () { App.renderMenu({}); }); // clean join from URL if (location.search) { history.replaceState({}, '', 'index.html'); } }; App.createLobby = function () { showError('menu-error'); Api.createLobby(Rules.defaultRules()).then(function (data) { App.enter(data.game); }).catch(function (err) { showError('menu-error', err); }); }; App.doJoin = function (code) { showError('menu-error'); code = String(code || '').trim(); if (!code) { return; } Api.join(code).then(function (data) { App.enter(data.game); }).catch(function (err) { // Already a member of a game that has started: open it from the list. if (err && err.code === 'game_started') { var want = String(code).toUpperCase(); var existing = (App.games || []).filter(function (g) { return String(g.code || '').toUpperCase() === want; })[0]; if (existing) { App.openGame(existing.id, existing.status); return; } } showError('menu-error', err); }); }; App.openGame = function (id, status) { Api.game(id).then(function (data) { App.enter(data.game); }).catch(function (err) { showError('menu-error', err); }); }; App.enter = function (game) { App.game = game; App.gridAuto = !(game.rules && game.rules.grid_auto === false); if (game.status === 'lobby') { showScreen('lobby'); App.renderLobby(); } else { showScreen('game'); App.renderGame(); } App.startPoll(); if (game && game.code) { history.replaceState({}, '', 'index.html?join=' + encodeURIComponent(game.code)); } }; /* ---------- lobby ---------- */ App.renderLobby = function () { var g = App.game; if (!g) { return; } $('lobby-code').textContent = g.code; var url = location.origin + location.pathname.replace(/index\.html$/, '') + 'index.html?join=' + encodeURIComponent(g.code); $('invite-link').value = url; var isHost = g.host_id === g.you; var list = $('lobby-players'); list.innerHTML = ''; (g.players || []).forEach(function (p) { var li = document.createElement('li'); li.appendChild(avatarNode(p, 40, true)); var name = document.createElement('span'); name.style.flex = '1'; name.textContent = p.name + (p.is_you ? ' (' + I18n.t('lobby.you') + ')' : '') + (p.is_host ? ' · ' + I18n.t('lobby.host') : ''); li.appendChild(name); var dot = document.createElement('span'); dot.className = 'player-dot'; dot.style.background = p.color; li.appendChild(dot); list.appendChild(li); }); var n = (g.players || []).length; $('lobby-need').hidden = n >= 2; $('btn-start').hidden = !isHost; $('btn-start').disabled = n < 2; $('lobby-waiting').hidden = isHost; // Rules var r = g.rules || Rules.defaultRules(); $('rule-jury').checked = !!r.jury; if ($('rule-ap-loot')) { $('rule-ap-loot').checked = !!r.ap_loot; } if ($('rule-ap-time')) { $('rule-ap-time').value = r.ap_time || '00:00'; } if (!isHost) { App.gridAuto = r.grid_auto !== false; } var suggested = Rules.suggestedGrid(n); if (App.gridAuto) { $('rule-grid').value = String(suggested); } else { $('rule-grid').value = String(Rules.clampGrid(r.grid || suggested)); } App.echoGridSide(); $('rule-shrink').checked = !!r.shrinking_arena; $('rule-shrink-days').value = r.shrink_interval_days || 7; $('rule-ceasefire').checked = !!r.ceasefire; $('shrink-days-wrap').hidden = !r.shrinking_arena; $('ceasefire-editor').hidden = !r.ceasefire; ['rule-jury', 'rule-shrink', 'rule-ceasefire', 'rule-shrink-days', 'cf-add', 'rule-ap-loot', 'rule-ap-time', 'rule-grid', 'grid-use-suggested'].forEach(function (id) { if ($(id)) { $(id).disabled = !isHost; } }); App.renderCfEditor(r.ceasefire_ranges || [], isHost); App.syncVisRadios(r, isHost); I18n.apply($('lobby')); App.updateGridHint(); }; App.echoGridSide = function () { if ($('grid-side-echo') && $('rule-grid')) { $('grid-side-echo').textContent = String(Rules.clampGrid($('rule-grid').value)); } }; App.updateGridHint = function () { var n = (App.game && App.game.players) ? App.game.players.length : 1; var size = Rules.suggestedGrid(n); if ($('grid-hint')) { $('grid-hint').textContent = I18n.t('lobby.gridHint', { n: n, size: size }); } if ($('grid-use-suggested')) { var current = $('rule-grid') ? Rules.clampGrid($('rule-grid').value) : size; $('grid-use-suggested').hidden = App.gridAuto !== false || current === size; } }; App.currentCfRanges = function () { return (App.game && App.game.rules && App.game.rules.ceasefire_ranges) || []; }; App.setCfRanges = function (ranges) { if (!App.game.rules) { App.game.rules = Rules.defaultRules(); } App.game.rules.ceasefire_ranges = Rules.normalizeRanges(ranges); App.renderCfEditor(App.game.rules.ceasefire_ranges, App.game.host_id === App.game.you); }; App.renderCfEditor = function (ranges, editable) { CeasefireClock.render($('cf-clock'), ranges, { editable: editable, onChange: function (next) { App.setCfRanges(next); App.onRulesChange(); } }); var ul = $('cf-ranges'); ul.innerHTML = ''; if (!ranges.length) { var empty = document.createElement('li'); empty.className = 'hint'; empty.setAttribute('data-i18n', 'lobby.ceasefireEmpty'); empty.textContent = I18n.t('lobby.ceasefireEmpty'); ul.appendChild(empty); return; } ranges.forEach(function (r, i) { var li = document.createElement('li'); var a = document.createElement('input'); a.type = 'time'; a.value = r.start; a.setAttribute('aria-label', I18n.t('lobby.ceasefireStart')); a.disabled = !editable; var b = document.createElement('input'); b.type = 'time'; b.value = r.end; b.setAttribute('aria-label', I18n.t('lobby.ceasefireEnd')); b.disabled = !editable; function commit() { var next = App.currentCfRanges().slice(); next[i] = { start: a.value, end: b.value }; App.setCfRanges(next); App.onRulesChange(); } a.addEventListener('change', commit); b.addEventListener('change', commit); var rm = document.createElement('button'); rm.type = 'button'; rm.className = 'btn-secondary'; rm.textContent = I18n.t('lobby.ceasefireRemove'); rm.disabled = !editable; rm.addEventListener('click', function () { var next = App.currentCfRanges().slice(); next.splice(i, 1); App.setCfRanges(next); App.onRulesChange(); }); li.appendChild(a); li.appendChild(document.createTextNode('–')); li.appendChild(b); li.appendChild(rm); ul.appendChild(li); }); }; App.onRulesChange = function () { if (!App.game || App.game.status !== 'lobby') { return; } if (App.game.host_id !== App.game.you) { return; } $('shrink-days-wrap').hidden = !$('rule-shrink').checked; $('ceasefire-editor').hidden = !$('rule-ceasefire').checked; var rules = { jury: $('rule-jury').checked, shrinking_arena: $('rule-shrink').checked, shrink_interval_days: parseInt($('rule-shrink-days').value, 10) || 7, ceasefire: $('rule-ceasefire').checked, ceasefire_ranges: App.currentCfRanges(), ap_loot: $('rule-ap-loot') ? $('rule-ap-loot').checked : false, ap_time: ($('rule-ap-time') && $('rule-ap-time').value) ? $('rule-ap-time').value : '00:00', grid: Rules.clampGrid($('rule-grid') ? $('rule-grid').value : Rules.SUGGEST_MIN_GRID), grid_auto: App.gridAuto !== false }; Object.assign(rules, App.readVisRules()); App.game.rules = Object.assign({}, App.game.rules, rules); App.rulesDirty = true; if (App._rulesTimer) { clearTimeout(App._rulesTimer); } App._rulesTimer = setTimeout(function () { if (!App.rulesDirty) { return; } App.rulesDirty = false; Api.setRules(App.game.id, App.game.rules).then(function (data) { App.game = data.game; if (data.game && data.game.rules) { App.gridAuto = data.game.rules.grid_auto !== false; } App.renderLobby(); }).catch(function (err) { showError('lobby-error', err); }); }, 350); }; App.copyInvite = function () { var v = $('invite-link').value; function ok() { $('copy-status').hidden = false; setTimeout(function () { $('copy-status').hidden = true; }, 1500); } if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(v).then(ok).catch(function () { $('invite-link').select(); try { document.execCommand('copy'); ok(); } catch (e) {} }); } else { $('invite-link').select(); try { document.execCommand('copy'); ok(); } catch (e) {} } }; App.startGame = function () { showError('lobby-error'); Api.start(App.game.id).then(function (data) { App.enter(data.game); }).catch(function (err) { showError('lobby-error', err); }); }; App.leaveLobby = function () { Api.leave(App.game.id).then(function () { App.toMenu(); }) .catch(function (err) { showError('lobby-error', err); }); }; /* ---------- game ---------- */ App.renderGame = function () { var g = App.replay ? App.replay.view : App.game; if (!g) { return; } this.renderHud(g); this.renderBoard(g); this.renderJury(g); this.renderTimeline(App.game); // ticks from the (already filtered) event list this.tickClocks(); I18n.apply($('game')); I18n.apply($('top-bar')); if (!App.replay) { this.clearBoardFx(); } }; App.renderHud = function (g) { var me = findIn(g.players, g.you) || you(); var stats = $('you-stats'); if (me) { stats.innerHTML = '' + escapeHtml(me.name) + ' · ' + I18n.t('game.lives') + ' ' + me.lives + ' · ' + I18n.t('game.ap') + ' ' + me.ap + ' · ' + I18n.t('game.range') + ' ' + me.range + ''; } var legal = g.legal || {}; $('btn-upgrade').hidden = !legal.upgrade; $('btn-upgrade').disabled = !legal.upgrade; $('day-label').textContent = I18n.t('game.day', { n: g.day || 0 }); var sb = $('shrink-banner'); if (g.rules && g.rules.shrinking_arena && g.shrink_in_days != null) { sb.hidden = false; if (g.shrink_in_days === 0) { sb.textContent = I18n.t('game.shrinkToday'); } else if (g.shrink_in_days === 1) { sb.textContent = I18n.t('game.shrinkTomorrow'); } else { sb.textContent = I18n.plural('game.shrinkInDays', g.shrink_in_days); } } else { sb.hidden = true; } var banner = $('game-banner'); if (g.status === 'finished') { banner.hidden = false; if (g.draw) { banner.textContent = I18n.t('game.draw'); } else if (g.winner_id === g.you) { banner.textContent = I18n.t('game.youWin'); } else { var w = findIn(g.players, g.winner_id); banner.textContent = I18n.t('game.winner', { name: w ? w.name : '?' }); } } else if (me && !me.alive) { banner.hidden = false; banner.textContent = I18n.t('game.spectating'); } else { banner.hidden = true; } }; function findIn(list, id) { if (!list) { return null; } for (var i = 0; i < list.length; i++) { if (list[i].id === id) { return list[i]; } } return null; } App.renderBoard = function (g) { var board = $('board'); var size = g.grid || 6; var inset = g.arena_inset || 0; var nextInset = (g.rules && g.rules.shrinking_arena && g.shrink_in_days != null && g.max_inset > inset) ? inset + 1 : null; board.style.setProperty('--n', String(size)); board.style.gridTemplateColumns = 'repeat(' + size + ', 1fr)'; board.style.gridTemplateRows = 'repeat(' + size + ', 1fr)'; board.innerHTML = ''; var legal = (!App.replay && g.legal) ? g.legal : { move: [], shoot: [] }; var moveSet = {}; (legal.move || []).forEach(function (t) { moveSet[t.x + ',' + t.y] = true; }); var me = findIn(g.players, g.you); var showMoves = App.selected && me && App.selected === me.id; for (var y = 0; y < size; y++) { for (var x = 0; x < size; x++) { var cell = document.createElement('button'); cell.type = 'button'; cell.className = 'cell'; cell.setAttribute('role', 'gridcell'); cell.dataset.x = String(x); cell.dataset.y = String(y); var passable = Rules.isPassable(size, inset, x, y); if (!passable) { cell.classList.add('impassable'); cell.disabled = true; cell.title = I18n.t('game.impassable'); } else if (nextInset != null && !Rules.isPassable(size, nextInset, x, y)) { cell.classList.add('threat'); cell.title = I18n.t('game.willShrink'); } if (showMoves && moveSet[x + ',' + y]) { cell.classList.add('move-target'); } var occupant = null; (g.players || []).forEach(function (p) { if (p.x === x && p.y === y) { occupant = p; } }); // Prefer living occupant if two (dead + living shouldn't share, but dead stay visually) (g.players || []).forEach(function (p) { if (p.x === x && p.y === y && p.alive) { occupant = p; } }); if (occupant) { var node = avatarNode(occupant, 48); var pic = node.firstChild; if (pic) { cell.appendChild(pic); } if (App.selected === occupant.id) { cell.classList.add('selected'); } if (!App.replay && legal.shoot && legal.shoot.indexOf(occupant.id) >= 0) { cell.classList.add('in-range'); } } (function (cx, cy, occ) { cell.addEventListener('click', function () { App.onCell(cx, cy, occ); }); })(x, y, occupant); board.appendChild(cell); } } }; App.onCell = function (x, y, occupant) { if (App.replay) { this.stopReplay(); } var g = App.game; if (!g || g.status !== 'running') { if (occupant) { this.openInfo(occupant); } return; } var me = you(); var legal = g.legal || {}; // Move onto highlighted tile if (me && App.selected === me.id && !occupant) { var ok = (legal.move || []).some(function (t) { return t.x === x && t.y === y; }); if (ok) { this.act({ type: 'move', x: x, y: y }); App.selected = null; return; } } if (occupant) { if (occupant.is_you || occupant.id === g.you) { App.selected = occupant.id; this.renderGame(); return; } this.openPlayerOptions(occupant); return; } App.selected = null; this.renderGame(); }; App.openPlayerOptions = function (p) { App.selected = p.id; this.renderGame(); var g = App.game; var legal = g.legal || {}; var body = document.createElement('div'); body.className = 'opt-list'; function add(label, fn, disabled, reason) { var b = document.createElement('button'); b.type = 'button'; b.textContent = label; if (disabled) { b.disabled = true; if (reason) { b.title = reason; } } else { b.addEventListener('click', function () { App.closeSheet(); fn(); }); } body.appendChild(b); } add(I18n.t('opt.info'), function () { App.openInfo(p); }); var canAttack = legal.shoot && legal.shoot.indexOf(p.id) >= 0; var cfBlock = legal.ceasefire || (g.ceasefire && g.ceasefire.active); add(I18n.t('opt.attack'), function () { App.act({ type: 'shoot', target: p.id }); }, !canAttack, cfBlock ? I18n.t('game.attackDisabledReason') : (I18n.t('error.out_of_range'))); var canGive = legal.give && legal.give.indexOf(p.id) >= 0; add(I18n.t('opt.give'), function () { App.openGive(p); }, !canGive); add(I18n.t('opt.message'), function () { App.openChat(p); }); $('sheet-body').innerHTML = ''; var head = document.createElement('h2'); head.textContent = p.name; $('sheet-body').appendChild(head); $('sheet-body').appendChild(body); $('sheet').hidden = false; }; App.openInfo = function (p) { var body = document.createElement('div'); function stat(label, val) { var shown = (val == null) ? I18n.t('info.hidden') : String(val); return '

' + label + ': ' + shown + '

'; } body.innerHTML = stat(I18n.t('info.lives'), p.lives) + stat(I18n.t('info.ap'), p.ap) + stat(I18n.t('info.range'), p.range); if (!p.alive) { body.innerHTML += '

' + I18n.t(p.surrendered ? 'game.surrendered' : 'game.dead') + '

'; } var lab = document.createElement('label'); lab.textContent = I18n.t('info.notes'); var ta = document.createElement('textarea'); ta.rows = 5; ta.value = p.note || ''; ta.setAttribute('maxlength', '2000'); var hint = document.createElement('p'); hint.className = 'hint'; hint.textContent = I18n.t('info.notesHint'); var save = document.createElement('button'); save.type = 'button'; save.textContent = I18n.t('info.saveNotes'); var st = document.createElement('span'); st.className = 'hint'; save.addEventListener('click', function () { Api.note(App.game.id, p.id, ta.value).then(function (data) { App.game = data.game; st.textContent = I18n.t('info.saved'); }).catch(function (err) { st.textContent = I18n.error(err.code || err.message); }); }); body.appendChild(lab); body.appendChild(ta); body.appendChild(hint); body.appendChild(save); body.appendChild(st); App.openModal(I18n.t('info.title') + ' — ' + p.name, body); }; App.openGive = function (p) { var me = you(); var max = me ? me.ap : 1; var body = document.createElement('div'); var lab = document.createElement('label'); lab.textContent = I18n.t('give.howMany'); var inp = document.createElement('input'); inp.type = 'number'; inp.min = '1'; inp.max = String(max); inp.value = '1'; inp.inputMode = 'numeric'; var have = document.createElement('p'); have.className = 'hint'; have.textContent = I18n.t('give.youHave', { n: max }); var btn = document.createElement('button'); btn.type = 'button'; btn.textContent = I18n.t('give.send'); btn.addEventListener('click', function () { var n = parseInt(inp.value, 10); App.closeModal(); App.act({ type: 'give', target: p.id, amount: n }); }); body.appendChild(lab); body.appendChild(inp); body.appendChild(have); body.appendChild(btn); App.openModal(I18n.t('give.title') + ' — ' + p.name, body); }; App.openChat = function (p) { var body = document.createElement('div'); var log = document.createElement('div'); log.className = 'chat-log'; function fill(game) { log.innerHTML = ''; var msgs = (game.messages || []).filter(function (m) { return (m.from === p.id && m.to === game.you) || (m.to === p.id && m.from === game.you); }); if (!msgs.length) { var em = document.createElement('p'); em.className = 'hint'; em.textContent = I18n.t('chat.empty'); log.appendChild(em); } msgs.forEach(function (m) { var b = document.createElement('div'); b.className = 'chat-bubble' + (m.from === game.you ? ' mine' : ''); b.textContent = m.text; log.appendChild(b); }); log.scrollTop = log.scrollHeight; } fill(App.game); var row = document.createElement('form'); row.className = 'chat-compose'; row.action = '#'; var inp = document.createElement('input'); inp.type = 'text'; inp.maxLength = 1000; inp.placeholder = I18n.t('chat.placeholder'); inp.setAttribute('data-i18n-placeholder', 'chat.placeholder'); var send = document.createElement('button'); send.type = 'submit'; send.textContent = I18n.t('chat.send'); row.appendChild(inp); row.appendChild(send); row.addEventListener('submit', function (e) { e.preventDefault(); var t = inp.value.trim(); if (!t) { return; } inp.value = ''; Api.message(App.game.id, p.id, t).then(function (data) { App.game = data.game; fill(App.game); }).catch(function (err) { showError('game-error', err); }); }); body.appendChild(log); body.appendChild(row); App.openModal(I18n.t('chat.title', { name: p.name }), body); // Keep a hook so polls refresh an open chat App._openChat = { id: p.id, fill: fill }; inp.focus(); }; App.openModal = function (title, body) { $('modal-title').textContent = title; $('modal-body').innerHTML = ''; $('modal-body').appendChild(body); $('modal').hidden = false; }; App.closeModal = function () { $('modal').hidden = true; App._openChat = null; }; App.closeSheet = function () { $('sheet').hidden = true; }; App.renderJury = function (g) { var panel = $('jury-panel'); var legal = g.legal || {}; if (App.replay || !legal.vote) { panel.hidden = true; return; } panel.hidden = false; var ul = $('jury-list'); ul.innerHTML = ''; legal.vote.forEach(function (id) { var p = findIn(g.players, id); if (!p) { return; } var li = document.createElement('li'); li.appendChild(avatarNode(p, 32, true)); var n = document.createElement('span'); n.style.flex = '1'; n.textContent = p.name; li.appendChild(n); var b = document.createElement('button'); b.type = 'button'; if (legal.my_vote === id) { b.textContent = I18n.t('jury.votedFor', { name: p.name }); b.disabled = true; } else { b.textContent = legal.my_vote ? I18n.t('jury.change') : I18n.t('jury.vote'); b.addEventListener('click', function () { App.act({ type: 'vote', target: id }); }); } li.appendChild(b); ul.appendChild(li); }); }; App.confirmSurrender = function () { $('settings-panel').hidden = true; var body = document.createElement('div'); var p = document.createElement('p'); p.textContent = I18n.t('game.surrenderConfirm'); var yes = document.createElement('button'); yes.type = 'button'; yes.className = 'btn-danger'; yes.textContent = I18n.t('game.surrenderConfirmBtn'); yes.addEventListener('click', function () { App.closeModal(); App.act({ type: 'surrender' }); }); var no = document.createElement('button'); no.type = 'button'; no.className = 'btn-secondary'; no.textContent = I18n.t('game.surrenderCancel'); no.addEventListener('click', function () { App.closeModal(); }); body.appendChild(p); body.appendChild(yes); body.appendChild(document.createTextNode(' ')); body.appendChild(no); App.openModal(I18n.t('game.surrender'), body); }; App.act = function (action) { showError('game-error'); Api.act(App.game.id, action).then(function (data) { App.game = data.game; App.selected = action.type === 'move' ? null : App.selected; App.renderGame(); }).catch(function (err) { showError('game-error', err); }); }; /* ---------- clocks & polling ---------- */ App.tickClocks = function () { if (App.screen !== 'game' || !App.game) { return; } var now = Api.now(); var next = App.game.next_distribution_at; if (next && App.game.status === 'running') { $('ap-hms').textContent = Rules.formatHms(next - now); $('ap-countdown').hidden = false; } else { $('ap-countdown').hidden = App.game.status !== 'running'; if (App.game.status !== 'running') { $('ap-hms').textContent = '00:00:00'; } } var cf = App.game.ceasefire; var box = $('cf-countdown'); if (cf && cf.enabled && cf.until && App.game.status === 'running') { box.hidden = false; box.classList.toggle('active', !!cf.active); $('cf-label').textContent = I18n.t(cf.active ? 'game.ceasefireLeft' : 'game.ceasefireUntil'); $('cf-hms').textContent = Rules.formatHms(cf.until - now); } else { box.hidden = true; } }; App.startPoll = function () { this.stopPoll(); this.pollTimer = setInterval(function () { App.poll(); }, 3000); }; App.stopPoll = function () { if (this.pollTimer) { clearInterval(this.pollTimer); this.pollTimer = null; } }; App.poll = function () { if (document.hidden || !App.game) { return; } var id = App.game.id; var v = App.game.version || 0; Api.sync(id, v).then(function (data) { if (!App.game || App.game.id !== id) { return; } if (data.next_distribution_at != null) { App.game.next_distribution_at = data.next_distribution_at; } if (data.ceasefire !== undefined) { App.game.ceasefire = data.ceasefire; } if (data.server_now) { /* Api already stored */ } if (data.changed && data.game) { var stayOn = App._openChat && App._openChat.id; App.game = data.game; if (App.screen === 'lobby' && data.game.status === 'lobby') { App.renderLobby(); } else if (data.game.status !== 'lobby') { if (App.screen !== 'game') { showScreen('game'); } if (!App.replay) { App.renderGame(); } else { App.renderTimeline(App.game); } } if (stayOn && App._openChat) { App._openChat.fill(App.game); } } App.tickClocks(); }).catch(function () { /* transient; next poll retries */ }); }; App.refreshFull = function () { if (!App.game) { return; } var id = App.game.id; Api.game(id).then(function (data) { if (!App.game || App.game.id !== id) { return; } App.game = data.game; if (data.game.status === 'lobby') { App.renderLobby(); } else { App.renderGame(); } if (App._openChat) { App._openChat.fill(App.game); } }).catch(function () {}); }; /* ---------- timeline ---------- */ App.spendEvents = function (game) { return (game.events || []).filter(function (e) { return e.spend; }); }; App.renderTimeline = function (game) { var spends = this.spendEvents(game); var track = $('tl-track'); var ticks = $('tl-ticks'); ticks.innerHTML = ''; var n = spends.length; track.setAttribute('aria-valuemax', String(Math.max(n, 0))); spends.forEach(function (e, i) { var t = document.createElement('div'); t.className = 'tl-tick'; // Align with playhead: spend i is at index i+1, position (i+1)/n. t.style.left = ((n <= 0 ? 0 : (i + 1) / n) * 100) + '%'; ticks.appendChild(t); }); var idx = App.replay ? App.replay.index : n; this.setPlayhead(idx, n); $('tl-play').textContent = (App.replay && App.replay.timer) ? '❚❚' : '▶'; $('tl-play').title = I18n.t((App.replay && App.replay.timer) ? 'timeline.pause' : 'timeline.play'); this.setCaption(); track.setAttribute('aria-valuetext', idx + ' / ' + n); }; App.setPlayhead = function (idx, n) { var head = $('tl-head'); if (n <= 0) { head.style.left = '0%'; } else if (n === 1) { head.style.left = (idx <= 0 ? '0%' : '100%'); } else { head.style.left = (Math.max(0, Math.min(n, idx)) / n) * 100 + '%'; } $('tl-track').setAttribute('aria-valuenow', String(idx)); }; App.setCaption = function () { // No direct text log: events are shown only as playback visuals. var el = $('tl-caption'); if (el) { el.hidden = true; el.textContent = ''; } }; App.eventLabel = function (ev, game) { function name(id) { var p = findIn(game.players, id); return p ? p.name : (id || ''); } switch (ev.type) { case 'start': return I18n.t('timeline.event.start'); case 'move': return I18n.t('timeline.event.move', { name: name(ev.player) }); case 'shoot': return I18n.t('timeline.event.shoot', { name: name(ev.player), target: name(ev.target) }); case 'give': return I18n.t('timeline.event.give', { name: name(ev.player), target: name(ev.target), n: ev.amount }); case 'upgrade': return I18n.t('timeline.event.upgrade', { name: name(ev.player), n: ev.range }); case 'surrender': return I18n.t('timeline.event.surrender', { name: name(ev.player) }); case 'daily': var s = I18n.t('timeline.event.daily', { n: ev.day }); if (ev.jury && ev.jury.winners && ev.jury.winners.length) { var names = ev.jury.winners.map(name); s += ' — ' + (names.length === 1 ? I18n.t('timeline.event.jury', { name: names[0] }) : I18n.t('timeline.event.juryTie', { names: names.join(', ') })); } return s; case 'shrink': return I18n.t('timeline.event.shrink'); case 'win': return I18n.t('timeline.event.win', { name: name(ev.player) }); case 'draw': return I18n.t('timeline.event.draw'); case 'death': if (ev.cause === 'shot') { return I18n.t('timeline.event.deathShot', { name: name(ev.player), by: name(ev.by) }); } if (ev.cause === 'shrink') { return I18n.t('timeline.event.deathShrink', { name: name(ev.player) }); } if (ev.cause === 'crushed') { return I18n.t('timeline.event.deathCrushed', { name: name(ev.player) }); } return I18n.t('timeline.event.death', { name: name(ev.player) }); default: return ev.type; } }; App.bindTimelineScrub = function () { var track = $('tl-track'); var dragging = false; function clientX(ev) { if (ev.clientX != null && ev.clientX !== 0) { return ev.clientX; } if (ev.touches && ev.touches[0]) { return ev.touches[0].clientX; } if (ev.changedTouches && ev.changedTouches[0]) { return ev.changedTouches[0].clientX; } return ev.clientX; } function pos(ev) { var r = track.getBoundingClientRect(); var x = clientX(ev) - r.left; var t = r.width <= 0 ? 0 : x / r.width; var n = App.spendEvents(App.game).length; return Rules.timelineIndex(t, n); } function go(ev, scrub) { if (!App.game) { return; } // Click/tap: jump to the nearest event. Drag: scrub through them. App.jumpReplay(pos(ev), { animate: false, scrub: !!scrub }); } function down(e) { if (e.button != null && e.button !== 0) { return; } dragging = true; if (track.setPointerCapture && e.pointerId != null) { try { track.setPointerCapture(e.pointerId); } catch (err) {} } if (e.preventDefault) { e.preventDefault(); } go(e, false); } function move(e) { if (!dragging) { return; } if (e.preventDefault) { e.preventDefault(); } go(e, true); } function up() { dragging = false; } track.addEventListener('pointerdown', down); track.addEventListener('pointermove', move); track.addEventListener('pointerup', up); track.addEventListener('pointercancel', up); // Fallback for older browsers / mixed input: same handlers on touch. track.addEventListener('touchstart', down, { passive: false }); track.addEventListener('touchmove', move, { passive: false }); track.addEventListener('touchend', up); track.addEventListener('touchcancel', up); }; App.toggleReplay = function () { if (App.replay && App.replay.timer) { clearInterval(App.replay.timer); App.replay.timer = null; this.renderTimeline(App.game); return; } var n = this.spendEvents(App.game).length; if (!n) { return; } var startAt = (App.replay && App.replay.index < n) ? App.replay.index : 0; this.jumpReplay(startAt); App.replay.timer = setInterval(function () { if (!App.replay) { return; } if (App.replay.index >= n) { App.stopReplay(); return; } App.jumpReplay(App.replay.index + 1); }, 500); this.renderTimeline(App.game); }; App.jumpReplay = function (index, opts) { opts = opts || {}; var game = App.game; var spends = this.spendEvents(game); var n = spends.length; index = Math.max(0, Math.min(n, index)); var prev = App.replay && App.replay.view; var prevIndex = App.replay ? App.replay.index : null; var view = this.viewAtSpend(game, index); if (!App.replay) { App.replay = { timer: null }; } var stepping = prevIndex != null && index === prevIndex + 1; var animate = opts.animate !== false && (opts.animate || (App.replay.timer && stepping)); App.replay.index = index; App.replay.view = view; this.renderBoard(view); this.renderHud(view); this.renderJury(view); this.renderTimeline(game); this.setCaption(); var ev = index > 0 ? spends[index - 1] : null; this.playBoardFx(view, ev, prev, !!animate); }; App.viewAtSpend = function (game, spendCount) { // Walk a shallow clone of players from the start event / initial, applying // events until `spendCount` spend-ticks have been applied. var players = (game.players || []).map(function (p) { return Object.assign({}, p); }); // Remember which numeric stats the server hid from this viewer, so replay // never invents values the live state would not show. var hidden = {}; players.forEach(function (p) { hidden[p.id] = { lives: p.lives == null, ap: p.ap == null, range: p.range == null }; }); var events = game.events || []; var applied = 0; var start = events.filter(function (e) { return e.type === 'start'; })[0]; if (start && start.players) { start.players.forEach(function (sp) { players.forEach(function (p) { if (p.id === sp.id) { p.x = sp.x; p.y = sp.y; if (!hidden[p.id] || !hidden[p.id].lives) { p.lives = 3; } if (!hidden[p.id] || !hidden[p.id].ap) { p.ap = 1; } if (!hidden[p.id] || !hidden[p.id].range) { p.range = 2; } p.alive = true; p.surrendered = false; } }); }); } var inset = 0; var day = 0; function apply(ev) { var p; if (ev.type === 'move') { p = findIn(players, ev.player); if (p && ev.to) { p.x = ev.to.x; p.y = ev.to.y; if (p.ap > 0) { p.ap--; } } } else if (ev.type === 'shoot') { p = findIn(players, ev.player); if (p && p.ap != null && p.ap > 0) { p.ap--; } var t = findIn(players, ev.target); if (t) { if (ev.lives_left != null && t.lives != null) { t.lives = ev.lives_left; } if (ev.killed) { t.alive = false; if (t.ap != null) { t.ap = 0; } if (t.lives != null) { t.lives = 0; } } } } else if (ev.type === 'give') { p = ev.player ? findIn(players, ev.player) : null; var t2 = findIn(players, ev.target); if (p && p.ap != null) { p.ap = Math.max(0, p.ap - (ev.amount || 1)); } if (t2 && t2.ap != null) { t2.ap += (ev.amount || 1); } } else if (ev.type === 'upgrade') { p = findIn(players, ev.player); if (p) { if (p.range != null && ev.range != null) { p.range = ev.range; } if (p.ap != null && p.ap > 0) { p.ap--; } } } else if (ev.type === 'surrender') { p = findIn(players, ev.player); if (p) { p.alive = false; p.surrendered = true; p.lives = 0; p.ap = 0; } } else if (ev.type === 'daily' && ev.grants) { day = ev.day || day; players.forEach(function (pl) { if (ev.grants[pl.id]) { pl.ap += ev.grants[pl.id]; } }); } else if (ev.type === 'shrink') { inset = ev.inset || inset; (ev.moved || []).forEach(function (m) { var q = findIn(players, m.id); if (q && m.to) { q.x = m.to.x; q.y = m.to.y; if (q.lives > 0 && ev.hurt && ev.hurt.indexOf(m.id) >= 0) { /* already in lives? */ } } }); (ev.hurt || []).forEach(function (id) { var q = findIn(players, id); if (q && ev.killed && ev.killed.indexOf(id) < 0 && q.lives > 0) { q.lives = Math.max(1, q.lives); } }); (ev.killed || []).forEach(function (id) { var q = findIn(players, id); if (q) { q.alive = false; q.lives = 0; q.ap = 0; } }); } } for (var i = 0; i < events.length; i++) { var ev = events[i]; if (ev.spend) { if (applied >= spendCount) { break; } apply(ev); applied++; } else { // Apply non-spend events that occurred before this point (start, // daily, shrink, death) — only those before the next unapplied spend. // If we have already reached the target spend count, stop before later dailies. if (applied >= spendCount && ev.type !== 'start') { continue; } apply(ev); } } players.forEach(function (p) { var h = hidden[p.id]; if (!h) { return; } if (h.lives) { p.lives = null; } if (h.ap) { p.ap = null; } if (h.range) { p.range = null; } }); return { you: game.you, players: players, grid: game.grid, arena_inset: inset, max_inset: game.max_inset, shrink_in_days: null, rules: game.rules, legal: { move: [], shoot: [], give: [], upgrade: false, vote: null }, day: day, status: game.status, winner_id: null, draw: false, next_distribution_at: null, ceasefire: null }; }; App.stopReplay = function () { if (App.replay && App.replay.timer) { clearInterval(App.replay.timer); } App.replay = null; this.clearBoardFx(); if (App.game && App.screen === 'game') { this.renderGame(); } }; App.clearBoardFx = function () { var fx = $('board-fx'); if (fx) { fx.innerHTML = ''; } var wrap = $('board-wrap'); if (wrap) { wrap.querySelectorAll('.fx-float').forEach(function (n) { n.remove(); }); } document.querySelectorAll('#board .piece.moving, #board .piece.range-pulse, #board .piece-initials.moving, #board .piece-initials.range-pulse').forEach(function (el) { el.classList.remove('moving', 'range-pulse'); el.style.transform = ''; el.style.transition = ''; }); }; App.cellCenter = function (x, y) { var cell = document.querySelector('#board .cell[data-x="' + x + '"][data-y="' + y + '"]'); var wrap = $('board-wrap'); if (!cell || !wrap) { return null; } var wr = wrap.getBoundingClientRect(); var r = cell.getBoundingClientRect(); return { x: r.left + r.width / 2 - wr.left, y: r.top + r.height / 2 - wr.top, s: Math.min(r.width, r.height) }; }; App.playerCell = function (view, id) { var p = findIn(view && view.players, id); if (!p) { return null; } return App.cellCenter(p.x, p.y); }; App.pieceInCell = function (x, y) { var cell = document.querySelector('#board .cell[data-x="' + x + '"][data-y="' + y + '"]'); return cell ? cell.querySelector('.piece, .piece-initials') : null; }; App.playBoardFx = function (view, ev, prev, animate) { this.clearBoardFx(); if (!ev || !view) { return; } var wrap = $('board-wrap'); var fx = $('board-fx'); if (!wrap || !fx) { return; } fx.setAttribute('width', String(wrap.clientWidth)); fx.setAttribute('height', String(wrap.clientHeight)); fx.setAttribute('viewBox', '0 0 ' + wrap.clientWidth + ' ' + wrap.clientHeight); if (ev.type === 'shoot' && ev.target) { var from = ev.player ? App.playerCell(prev || view, ev.player) : null; var to = App.playerCell(view, ev.target); // If the shooter is known (not filtered), draw a red arrow; the number // is damage, not remaining lives, so it does not leak hidden life totals. if (from && to && ev.player) { App.drawArrow(from, to, '#e85d5d', ev.damage != null ? ev.damage : 1); } else if (to) { App.floatNumber(to, ev.damage != null ? ev.damage : 1, '#e85d5d'); } if (ev.loot && ev.player) { var lootAt = App.playerCell(view, ev.player); if (lootAt) { App.floatNumber(lootAt, '+' + ev.loot, '#4ecb8d'); } } } else if (ev.type === 'give') { var tTo = ev.target ? App.playerCell(view, ev.target) : null; var amount = ev.amount != null ? ev.amount : 1; if (ev.anonymous || !ev.player) { // Must not reveal the giver: show the AP gain on the recipient only, // with no source arrow (an arrow "from nowhere" would still suggest a direction). if (tTo) { App.floatNumber(tTo, '+' + amount, '#4ecb8d'); } } else { var gFrom = App.playerCell(prev || view, ev.player); if (gFrom && tTo) { App.drawArrow(gFrom, tTo, '#4ecb8d', amount); } else if (tTo) { App.floatNumber(tTo, '+' + amount, '#4ecb8d'); } } } else if (ev.type === 'move' && ev.to && ev.from && ev.player && animate) { App.animateMove(ev.from, ev.to); } else if (ev.type === 'upgrade' && ev.player) { var p = findIn(view.players, ev.player); if (p) { var piece = App.pieceInCell(p.x, p.y); if (piece) { piece.classList.remove('range-pulse'); void piece.offsetWidth; piece.classList.add('range-pulse'); } } } }; App.drawArrow = function (from, to, color, number) { var fx = $('board-fx'); if (!fx || !from || !to) { return; } var ns = 'http://www.w3.org/2000/svg'; var dx = to.x - from.x, dy = to.y - from.y; var len = Math.sqrt(dx * dx + dy * dy) || 1; var ux = dx / len, uy = dy / len; var inset = Math.min(from.s || 24, to.s || 24) * 0.38; if (inset * 2 >= len) { inset = len * 0.22; } var x1 = from.x + ux * inset, y1 = from.y + uy * inset; var x2 = to.x - ux * inset, y2 = to.y - uy * inset; var mid = 'm' + Math.round(x1) + '-' + Math.round(y1) + '-' + Math.round(x2) + '-' + Math.round(y2); var defs = document.createElementNS(ns, 'defs'); var marker = document.createElementNS(ns, 'marker'); marker.setAttribute('id', mid); marker.setAttribute('viewBox', '0 0 10 10'); marker.setAttribute('refX', '8'); marker.setAttribute('refY', '5'); marker.setAttribute('markerWidth', '7'); marker.setAttribute('markerHeight', '7'); marker.setAttribute('orient', 'auto'); var tip = document.createElementNS(ns, 'path'); tip.setAttribute('d', 'M 0 0 L 10 5 L 0 10 z'); tip.setAttribute('fill', color); marker.appendChild(tip); defs.appendChild(marker); fx.appendChild(defs); var line = document.createElementNS(ns, 'line'); line.setAttribute('x1', String(x1)); line.setAttribute('y1', String(y1)); line.setAttribute('x2', String(x2)); line.setAttribute('y2', String(y2)); line.setAttribute('stroke', color); line.setAttribute('stroke-width', '4'); line.setAttribute('stroke-linecap', 'round'); line.setAttribute('marker-end', 'url(#' + mid + ')'); fx.appendChild(line); if (number != null && number !== '') { var mx = x1 + (x2 - x1) * 0.55; var my = y1 + (y2 - y1) * 0.55; var circ = document.createElementNS(ns, 'circle'); circ.setAttribute('cx', String(mx)); circ.setAttribute('cy', String(my)); circ.setAttribute('r', '13'); circ.setAttribute('fill', color); circ.setAttribute('stroke', '#0c1020'); circ.setAttribute('stroke-width', '2'); fx.appendChild(circ); var tx = document.createElementNS(ns, 'text'); tx.setAttribute('x', String(mx)); tx.setAttribute('y', String(my + 1)); tx.setAttribute('text-anchor', 'middle'); tx.setAttribute('dominant-baseline', 'middle'); tx.setAttribute('fill', '#fff'); tx.setAttribute('font-size', '13'); tx.setAttribute('font-weight', '700'); tx.setAttribute('font-family', 'ui-sans-serif, system-ui, sans-serif'); tx.textContent = String(number); fx.appendChild(tx); } }; App.floatNumber = function (at, text, color) { var wrap = $('board-wrap'); if (!wrap || !at) { return; } var el = document.createElement('div'); el.className = 'fx-float'; el.textContent = String(text); el.style.left = at.x + 'px'; el.style.top = at.y + 'px'; if (color) { el.style.color = color; } wrap.appendChild(el); }; App.animateMove = function (from, to) { var piece = App.pieceInCell(to.x, to.y); var a = App.cellCenter(from.x, from.y); var b = App.cellCenter(to.x, to.y); if (!piece || !a || !b) { return; } var dx = a.x - b.x, dy = a.y - b.y; if (Math.abs(dx) < 1 && Math.abs(dy) < 1) { return; } piece.classList.add('moving'); piece.style.transition = 'none'; piece.style.transform = 'translate(' + dx + 'px, ' + dy + 'px)'; requestAnimationFrame(function () { requestAnimationFrame(function () { piece.style.transition = 'transform 0.4s ease'; piece.style.transform = 'translate(0, 0)'; }); }); }; function escapeHtml(s) { return String(s).replace(/[&<>"']/g, function (c) { return ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]; }); } /* ---------- 24-hour cease-fire clock ---------- */ var CeasefireClock = { size: 320, cx: 160, cy: 160, r: 128 }; CeasefireClock.minsToAngle = function (mins) { // 0 at top, clockwise, 1440 minutes = 360°. return (mins / 1440) * 2 * Math.PI - Math.PI / 2; }; CeasefireClock.angleToMins = function (ang) { // atan2: 0 at 3 o'clock, CCW. Convert to clockwise from top. var a = ang + Math.PI / 2; if (a < 0) { a += 2 * Math.PI; } var mins = Math.round((a / (2 * Math.PI)) * 1440 / 5) * 5; if (mins >= 1440) { mins = 0; } if (mins < 0) { mins = 0; } return mins; }; CeasefireClock.arcPath = function (r, startMin, endMin) { var cx = this.cx, cy = this.cy; var a1 = this.minsToAngle(startMin); var a2 = this.minsToAngle(endMin); var x1 = cx + r * Math.cos(a1), y1 = cy + r * Math.sin(a1); var x2 = cx + r * Math.cos(a2), y2 = cy + r * Math.sin(a2); var delta = endMin - startMin; if (delta <= 0) { delta += 1440; } var large = delta > 720 ? 1 : 0; return 'M ' + cx + ' ' + cy + ' L ' + x1 + ' ' + y1 + ' A ' + r + ' ' + r + ' 0 ' + large + ' 1 ' + x2 + ' ' + y2 + ' Z'; }; CeasefireClock.handlePos = function (mins) { var a = this.minsToAngle(mins); return { x: this.cx + this.r * Math.cos(a), y: this.cy + this.r * Math.sin(a) }; }; CeasefireClock.render = function (container, ranges, opts) { opts = opts || {}; var self = this; ranges = Rules.normalizeRanges(ranges || []); var size = this.size; var svgNS = 'http://www.w3.org/2000/svg'; container.innerHTML = ''; var svg = document.createElementNS(svgNS, 'svg'); svg.setAttribute('viewBox', '0 0 ' + size + ' ' + size); svg.setAttribute('width', String(size)); svg.setAttribute('height', String(size)); svg.setAttribute('role', 'img'); function el(name, attrs) { var n = document.createElementNS(svgNS, name); Object.keys(attrs).forEach(function (k) { n.setAttribute(k, attrs[k]); }); return n; } // Allowed (gold) background disc svg.appendChild(el('circle', { cx: this.cx, cy: this.cy, r: this.r, fill: '#3a3420', stroke: '#e8c547', 'stroke-width': '3' })); // Cease-fire slices (red) ranges.forEach(function (r, i) { var s = Rules.hmToMinutes(r.start); var e = Rules.hmToMinutes(r.end); var slices = e > s ? [[s, e]] : [[s, 1440], [0, e]]; slices.forEach(function (sl) { if (sl[1] === sl[0]) { return; } svg.appendChild(el('path', { d: self.arcPath(self.r - 1, sl[0], sl[1]), fill: '#8a2a2a', 'fill-opacity': '0.92', 'data-range': String(i) })); }); }); // Ticks and labels (0 at top, then 3, 6, 12, 18…) for (var h = 0; h < 24; h++) { var mins = h * 60; var a = this.minsToAngle(mins); var inner = this.r - (h % 3 === 0 ? 14 : 7); var outer = this.r; svg.appendChild(el('line', { x1: this.cx + inner * Math.cos(a), y1: this.cy + inner * Math.sin(a), x2: this.cx + outer * Math.cos(a), y2: this.cy + outer * Math.sin(a), stroke: '#e8eaf2', 'stroke-width': h % 6 === 0 ? '2.2' : '1', 'stroke-opacity': '0.7' })); if (h % 3 === 0) { var tx = this.cx + (this.r + 22) * Math.cos(a); var ty = this.cy + (this.r + 22) * Math.sin(a); var lab = el('text', { x: tx, y: ty, fill: '#e8c547', 'font-size': '13', 'font-weight': '700', 'text-anchor': 'middle', 'dominant-baseline': 'middle', 'pointer-events': 'none' }); lab.textContent = String(h); svg.appendChild(lab); } } // Inner hole so it looks like a ring-pie (keep a smaller gold disc for “now” later) svg.appendChild(el('circle', { cx: this.cx, cy: this.cy, r: 36, fill: '#0c1020', stroke: '#e8c54755', 'stroke-width': '1.5' })); var mid = el('text', { x: this.cx, y: this.cy + 1, fill: '#e8eaf2', 'font-size': '11', 'text-anchor': 'middle', 'dominant-baseline': 'middle', 'pointer-events': 'none' }); mid.textContent = '24h'; svg.appendChild(mid); // Handles if (opts.editable) { ranges.forEach(function (r, i) { ['start', 'end'].forEach(function (which) { var pos = self.handlePos(Rules.hmToMinutes(r[which])); var c = el('circle', { cx: pos.x, cy: pos.y, r: 14, fill: '#e8c547', stroke: '#1a1404', 'stroke-width': '2', 'data-range': String(i), 'data-which': which, style: 'cursor:grab; touch-action:none' }); // invisible larger hit target var hit = el('circle', { cx: pos.x, cy: pos.y, r: 22, fill: 'transparent', 'data-range': String(i), 'data-which': which, style: 'cursor:grab; touch-action:none' }); svg.appendChild(hit); svg.appendChild(c); }); }); } container.appendChild(svg); if (!opts.editable) { return; } var drag = null; var painting = null; function localMins(ev) { var rect = svg.getBoundingClientRect(); var cx = ev.clientX != null ? ev.clientX : ev.touches[0].clientX; var cy = ev.clientY != null ? ev.clientY : ev.touches[0].clientY; var x = (cx - rect.left) / rect.width * size; var y = (cy - rect.top) / rect.height * size; return self.angleToMins(Math.atan2(y - self.cy, x - self.cx)); } function commit(next) { if (opts.onChange) { opts.onChange(next); } } svg.addEventListener('pointerdown', function (e) { e.preventDefault(); svg.setPointerCapture(e.pointerId); var t = e.target; var ri = t.getAttribute && t.getAttribute('data-range'); var which = t.getAttribute && t.getAttribute('data-which'); if (ri != null && which) { drag = { i: parseInt(ri, 10), which: which }; return; } // Start a new range from this angle, drag to set the end. var m = localMins(e); painting = { start: m, end: (m + 60) % 1440 }; }); svg.addEventListener('pointermove', function (e) { if (!drag && !painting) { return; } e.preventDefault(); var m = localMins(e); if (drag) { var next = ranges.map(function (r) { return { start: r.start, end: r.end }; }); if (!next[drag.i]) { return; } next[drag.i][drag.which] = Rules.minutesToHm(m); // Live preview self.render(container, next, opts); // re-bind happens via render → we need to keep dragging. Store on object. CeasefireClock._pending = { drag: drag, ranges: next, opts: opts, container: container }; } else if (painting) { painting.end = m; var preview = ranges.concat([{ start: Rules.minutesToHm(painting.start), end: Rules.minutesToHm(painting.end === painting.start ? (painting.start + 5) % 1440 : painting.end) }]); self.render(container, preview, opts); CeasefireClock._pending = { painting: painting, ranges: ranges, opts: opts, container: container }; } }); function endDrag(e) { var pending = CeasefireClock._pending; CeasefireClock._pending = null; if (drag && pending && pending.ranges) { var d = drag; drag = null; commit(pending.ranges); return; } if (painting) { var p = painting; painting = null; if (p.start === p.end) { self.render(container, ranges, opts); return; } commit(ranges.concat([{ start: Rules.minutesToHm(p.start), end: Rules.minutesToHm(p.end) }])); } drag = null; } svg.addEventListener('pointerup', endDrag); svg.addEventListener('pointercancel', endDrag); }; // Re-attach pointer handlers after a live-preview re-render by using // event delegation on the container (already on svg after each render). // The _pending flag lets pointermove after re-render continue: we also // bind at the document level during a drag. (function () { var active = false; document.addEventListener('pointermove', function (e) { var p = CeasefireClock._pending; if (!p || !p.opts) { return; } if (!p.drag && !p.painting) { return; } // The new svg already has handlers; this is a safety net no-op if they fire. }); })(); /* boot */ if (typeof document !== 'undefined') { if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { App.init(); }); } else { App.init(); } } if (typeof module !== 'undefined' && module.exports) { module.exports = { App: App, CeasefireClock: CeasefireClock, Rules: (typeof Rules !== 'undefined' ? Rules : null) }; }