const demo = document.documentElement.hasAttribute("data-demo"); import { airfield } from "./airfield.js"; import { cardFace, cardLabel, cardCaption } from "./cards.js"; const $ = (id) => document.getElementById(id); const app = $("app"); const names = { purple: "Фиолетовая", red: "Красная", green: "Зелёная", blue: "Синяя", cyan: "Голубая", yellow: "Жёлтая", }; const css = { purple: "#865c9d", red: "#bf4b40", green: "#3d864f", blue: "#3e60a1", cyan: "#4195a5", yellow: "#c6a12b", }; const codes = { purple: "Ф", red: "К", green: "З", blue: "С", cyan: "Г", yellow: "Ж", }; const size = ["", "малый", "средний", "широкофюзеляжный"]; const wx = { SC: "Ясно", FG: "Туман", CW: "Боковой ветер", SN: "Снег", ICE: "Обледенение", "31L": "31L закрыта", "31R": "31R закрыта", }; const types = { start: "Раздача", decision: "Решение бота", play: "Розыгрыш", shuffle: "Перемешивание", weather: "Погода", reveal: "Раскрытие", open_draw: "Открытый добор", draw: "Закрытый добор", move: "Движение", rotate: "Уход в хвост", turn: "Передача хода", choice: "Выбор", winner: "Победа", }; const reasons = { takeoff: "взлёт", card: "розыгрыш", queue: "продвижение очереди", vip: "маршрут VIP", AI: "обработка", FLR: "поломка", DLY: "задержка", }; let cat, games = [], bots = 3, color = "", gid = "", data, selected = "", exchange = [], mode = "move", cmdIndex = 0; let rep, step = 1, eye = "0", ff = "", pf = "", cf = "", ag = "", ar = "", ad = "", liveRev = -1, epoch = 0, fast = false; let busy = false, timer, noticeTimer, retryCommand = null; const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]); const dot = (c) => '' + names[c]; const date = (s) => new Date(s).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", year: "numeric", hour: "2-digit", minute: "2-digit", }); const opts = (vals, cur) => vals .map(([k, v]) => '") .join(""); const btn = (act, label, cls = "", val = "") => '"; const link = (hash, label) => '' + label + ""; function notify(msg) { $("notice").textContent = msg; $("notice").className = "show"; clearTimeout(noticeTimer); noticeTimer = setTimeout(() => ($("notice").className = ""), 5300); } async function api(path, body) { const r = await fetch("/api/" + path, body ? { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), } : {}); if (!r.ok) { const e = await r.json().catch(() => ({})); throw Error(typeof e.detail === "string" ? e.detail : "Ошибка запроса " + r.status); } return r.json(); } function pn(id) { if (!id) return ""; const [c, n] = id.split("-"); return codes[c] + n; } function loc(pos) { if (!pos) return ""; if (pos === "F") return "Вылетел"; if (pos === "H") return "Ангар"; const [k, a, b] = pos.split(":"); if (k === "D") return a + " / " + (b === "0" ? "старт" : "D" + b); if (k === "V1" || k === "V2") return k.replace("V", "VIP") + " / " + (a === "31L" ? "I" : "II"); return k + " / " + a; } function cname(c) { const p = pn(c.plane), to = loc(c.to), pay = (c.cards || []).map(cardCaption).join(" + "); switch (c.kind) { case "weather": return "Установить погоду · " + wx[c.cards[0]]; case "exchange": return "Обменять " + pay; case "move": return p + " → " + to + " · " + pay; case "attack": return cardLabel(c.cards[0]) + " · " + p; case "ice": return "Обработать " + p + " · " + pay; case "runway": return p + " → " + to; case "choose": return "В ангар · " + p; default: return c.kind; } } function textEvent(ev, v) { const d = ev.data; const who = d.seat === undefined ? "" : names[v.colors[d.seat]]; switch (ev.kind) { case "move": return (pn(d.plane) + " · " + loc(d.origin) + " → " + loc(d.to) + " · " + (reasons[d.reason] || d.reason)); case "play": return who + " · " + cname({ kind: d.action, ...d }); case "decision": return (who + " · " + (d.alternatives?.[0]?.reason || d.reason || "решение принято")); case "rotate": return pn(d.plane) + " уступает старт " + d.lane + " · " + wx[d.reason]; case "weather": return wx[d.card]; case "draw": case "open_draw": case "reveal": return [who, types[ev.kind], d.card ? cardCaption(d.card) : ""] .filter(Boolean) .join(" · "); default: return [types[ev.kind], who].filter(Boolean).join(" · "); } } const markedGames = new Set(); function listGames(list, manage = false) { return list.length ? '
Партий пока нет.
'; } function home() { const fleet = color ? cat.fleets[color] : null; const map = airfield({ geometry: cat.board, markers: {}, selected: "", destinations: new Set(), pickable: new Set(), weather: null, }); app.innerHTML = 'Выведите свой флот из ангара, проведите его к полосе и первым отправьте в небо последний борт.
' + (fleet ? fleet.length + " бортов · " + [1, 2, 3] .map((n) => size[n] + ": " + fleet.filter((x) => x === n).length) .join(" / ") : "У каждой компании свой флот. Цвета соперников определит жеребьёвка.") + "
" + btn("start", "Начать партию", "primary wide") + 'Ангар пуст
') + '| Компания | Ангар | Поле | Вылетели |
|---|---|---|---|
| " + dot(c) + (i === 0 ? " · вы" : "") + " | " + h + " | " + (ps.length - h - f) + " | " + f + " / " + ps.length + " |
" + dot(v.colors[v.pending?.seat ?? v.active]) + "
" + (v.pending.type === "runway" ? "VIP-борт готов войти в очередь." : "Вы сидите слева. Цели неприятности равноценны. Продолжит обмен компания «" + names[v.colors[v.active]] + "».") + "
" + acts.map((c, i) => btn("send", cname(c), "", i)).join(" ")); } const options = acts .map((c, i) => [c, i]) .filter(([c]) => c.kind !== "exchange"); const targets = [ ...new Set(options.map(([c]) => c.plane || "weather")), ]; if (!targets.includes(selected)) selected = targets[0] || ""; if (!targets.length) mode = "exchange"; const group = options.filter(([c]) => (c.plane || "weather") === selected); if (!group.some(([, i]) => i === cmdIndex)) cmdIndex = group[0]?.[1] ?? 0; return ('Выберите 1–4 карты для открытого обмена.
" : group.length ? '" + btn("send", "Подтвердить ход", "primary wide", cmdIndex) : "Доступен обмен карт.
") + 'Карты на руке · ' + v.hand.length + "
" + hand(v.hand, mode === "exchange")); } function live() { const v = data.view; const actionPanel = choices(); app.innerHTML = '| " + t + " | ") .join("") + "|
|---|---|
| " + dot(v.colors[i]) + " | " + ["flights", "ex", "ret", "tail", "31L", "31R"] .map((k) => "" + r[k] + " | ") .join("") + "
В колоде ' + v.deck_count + " карт.
" + "" + names[v.colors[i]] + " · " + (Object.entries(known) .map(([c, n]) => cardCaption(c) + " × " + n) .join(", ") || "нет известных") + "
") .join("") + "' + Object.keys(cat.cards).length + " типов · " + Object.values(cat.cards).reduce((sum, n) => sum + n, 0) + " карт в комплекте
" + hand(Object.keys(cat.cards)); } else if (page === "home" || page === "archive") { const rows = await api("games"); if (mark !== epoch) return; markedGames.clear(); games = rows; page === "home" ? home() : archive(); } else if (["game", "replay"].includes(page) && (/^[a-f0-9]{32}$/.test(id) || (page === "replay" && id === "reference"))) { gid = id; liveRev = -1; retryCommand = null; if (page === "game") { await refresh(true); if (mark === epoch) timer = setTimeout(() => poll(mark), 350); } else { eye = "0"; step = 1; ff = pf = cf = ""; await readReplay(); } } else location.hash = "home"; } catch (err) { if (demo && cat) home(); else app.textContent = err.message; notify(err.message); } finally { app.setAttribute("aria-busy", "false"); } } async function send(command) { if (busy) return; busy = true; if (demo) { try { await localPlay({ command }); } catch (err) { notify(err.message); } finally { busy = false; } return; } const packet = JSON.stringify(command); if (!retryCommand || retryCommand.version !== data.version || retryCommand.packet !== packet) retryCommand = { version: data.version, packet, id: crypto.randomUUID?.() ?? "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { const n = crypto.getRandomValues(new Uint8Array(1))[0] % 16; return (c === "x" ? n : (n & 3) | 8).toString(16); }), }; try { await api("games/" + gid + "/commands", { command, expected_version: data.version, command_id: retryCommand.id, }); retryCommand = null; await refresh(true); } catch (e) { notify(e.message); await refresh(); } finally { busy = false; } } app.addEventListener("click", async (e) => { const b = e.target.closest("[data-act]"); if (!b || busy) return; const { act: a, val } = b.dataset; try { if (demo && a === "setup") { home(); return; } if (["dropOne", "dropFinished", "dropMarked"].includes(a)) { await removeArchive(a, val); return; } if (a === "markAll") { const rows = archiveRows().filter(g => g.winner !== null); const clear = rows.every(g => markedGames.has(g.id)); rows.forEach(g => clear ? markedGames.delete(g.id) : markedGames.add(g.id)); archive(); return; } if (a === "zoom") { mapZoom = !mapZoom; const win = app.querySelector(".map-window"); win.classList.toggle("zoomed", mapZoom); b.textContent = mapZoom ? "Вписать поле" : "Увеличить поле"; return; } if (a === "mapdest") { const i = data.actions.findIndex((c) => c.plane === selected && c.to === val); if (i >= 0) { cmdIndex = i; live(); document.getElementById("action")?.focus(); } return; } if (a === "before") { eye = String(rep.timeline[rep.seq - 1].data.seat); step = +val; await readReplay(); } else if (a === "bots") { bots = +val; home(); } else if (a === "start") { busy = true; try { if (demo) { const local = await import("./demo-client.js"); if (await local.current() && !confirm("Заменить сохранённую демопартию новой?")) { await route(); return; } b.textContent = "Подготовка аэродрома…"; try { await localPlay({ reset: true, bots, color }); } finally { b.textContent = "Начать партию"; } return; } const g = await api("games", { bots, color: color || null }); location.hash = "game/" + g.id; } finally { busy = false; } } else if (a === "pick") { selected = val; mode = "move"; live(); } else if (a === "card") { const i = +val; if (exchange.includes(i)) exchange = exchange.filter((k) => k !== i); else if (exchange.length < 4) exchange.push(i); live(); } else if (a === "mode") { mode = val; live(); } else if (a === "send") await send(data.actions[+val]); else if (a === "exchange") await send({ kind: "exchange", cards: exchange.map((i) => data.view.hand[i]), }); else if (rep) { const n = step, turn = rep.timeline[n - 1].turn; const steps = { first: 1, last: rep.last, prev: n - 1, next: n + 1, goto: +val, backturn: rep.timeline.find((e) => e.turn === Math.max(1, turn - 1))?.seq ?? 1, nextturn: rep.timeline.find((e) => e.turn > turn)?.seq ?? rep.last, }; if (a in steps) { step = Math.max(1, Math.min(rep.last, steps[a])); await readReplay(); } } } catch (err) { notify(err.message); } }); app.addEventListener("change", async (e) => { const target = e.target; const id = target.id, v = target.value; try { if (target.dataset.mark) { if (target.checked) markedGames.add(target.dataset.mark); else markedGames.delete(target.dataset.mark); archive(); return; } if (id === "color") { color = v; home(); } else if (id === "plane") { selected = v; live(); } else if (id === "action") { cmdIndex = +v; live(); } else if (id === "fast") fast = target.checked; else if (["ag", "ar", "ad"].includes(id)) { markedGames.clear(); if (id === "ag") ag = v; else if (id === "ar") ar = v; else ad = v; archive(); } else if (["ff", "pf", "cf"].includes(id)) { if (id === "ff") ff = v; else if (id === "pf") pf = v; else cf = v; replay(); } else if (["eye", "step", "jump"].includes(id)) { if (id === "eye") eye = v; else if (id === "step") step = +v; else step = rep.timeline.find((e) => e.turn === +v)?.seq ?? step; await readReplay(); } } catch (err) { notify(err.message); } }); app.addEventListener("keydown", (e) => { const slot = e.target.closest(".map-slot[data-act]"); if (slot && (e.key === "Enter" || e.key === " ")) { e.preventDefault(); slot.dispatchEvent(new MouseEvent("click", { bubbles: true })); } }); window.addEventListener("hashchange", route); route();