' +
cards
.map((c, i) =>
cardFace(c, i, selectable, selectable && exchange.includes(i)),
)
.join("") +
"
"
);
}
function choices() {
const v = data.view,
acts = data.actions;
if (v.winner !== null)
return (
"" +
(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 (
'Ваш ход
' +
btn("mode", "Розыгрыш", mode === "move" ? "selected" : "", "move") +
btn("mode", "Обмен", mode === "exchange" ? "selected" : "", "exchange") +
"
" +
(mode === "exchange"
? 'Выберите 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 =
'";
}
function report(v, timeline) {
const rows = v.colors.map(() => ({
flights: 0,
ex: 0,
ret: 0,
tail: 0,
"31L": 0,
"31R": 0,
}));
for (const ev of timeline) {
const d = ev.data,
r = rows[d.seat];
if (!r) continue;
if (ev.kind === "move" && d.to === "F") {
r.flights++;
r[d.origin.split(":")[1]]++;
}
if (ev.kind === "move" && d.to === "H") r.ret++;
if (ev.kind === "rotate") r.tail++;
if (ev.kind === "play" && d.action === "exchange") r.ex++;
}
return (
'"
);
}
function replay() {
const v = rep.view,
t = rep.timeline,
ev = t[rep.seq - 1],
d = ev.data;
const available = t.slice(0, rep.seq);
const list = available.filter(
(e) =>
(!ff || e.kind === ff) &&
(!pf || e.data.plane === pf || e.data.order?.includes(pf)) &&
(!cf || e.data.seat === +cf),
);
app.innerHTML =
'Ход ' +
ev.turn +
" · Событие " +
rep.seq +
" из " +
rep.last +
'
' +
[
["first", "Начало"],
["backturn", "− ход"],
["prev", "− событие"],
["next", "+ событие"],
["nextturn", "+ ход"],
["last", "Конец"],
]
.map(([a, t]) => btn(a, t))
.join("") +
'
' +
esc(textEvent(ev, v)) +
"" +
(d.observed_seq
? btn("before", "Позиция перед решением", "", d.observed_seq)
: "") +
(d.alternatives?.length
? "" +
d.alternatives
.map(
(o) =>
"- " +
esc(cname(o.command)) +
" · " +
o.score +
" · " +
esc(o.reason) +
"
",
)
.join("") +
"
"
: "") +
'' +
board(v) +
'
Карты в этот момент
' +
(v.hands
? v.hands
.map((h, i) => "" + dot(v.colors[i]) + "
" + hand(h))
.join("") +
"Колода сверху вниз · " +
v.deck.length +
"
" +
hand(v.deck) +
" "
: "" +
dot(v.colors[v.seat]) +
"
" +
hand(v.hand) +
'В колоде ' +
v.deck_count +
" карт.
" +
"Открыто полученные карты на руках
" +
v.known
.map(
(known, i) =>
"" +
names[v.colors[i]] +
" · " +
(Object.entries(known)
.map(([c, n]) => cardCaption(c) + " × " + n)
.join(", ") || "нет известных") +
"
",
)
.join("") +
" ") +
'События до выбранного момента
' +
list
.slice()
.reverse()
.map((e) =>
btn("goto", "#" + e.seq + " · " + esc(textEvent(e, v)), "", e.seq),
)
.join("") +
"
" +
(rep.finished && rep.seq === rep.last ? report(v, t) : "");
}
async function readReplay() {
const mark = ++epoch;
const r = await api(
(gid === "reference" ? "reference" : "games/" + gid) +
"/replay?seq=" +
step +
"&perspective=" +
eye,
);
if (mark !== epoch) return;
rep = r;
step = r.seq;
replay();
}
async function refresh(force = false) {
const mark = epoch;
const game = await api("games/" + gid);
if (mark !== epoch) return;
if (force || liveRev !== game.version) {
data = game;
liveRev = game.version;
exchange = [];
selected = "";
cmdIndex = 0;
mode = "move";
live();
}
}
async function poll(mark) {
if (mark !== epoch) return;
try {
if (!busy) await refresh();
} catch (e) {
notify("Связь потеряна. Повторяю запрос.");
}
if (mark === epoch && data?.view.winner == null)
timer = setTimeout(() => poll(mark), fast ? 180 : 800);
}
async function localPlay(options = {}) {
const local = await import("./demo-client.js");
data = await local.play(options);
selected = ""; exchange = []; mode = "move"; cmdIndex = 0;
live();
}
async function route() {
clearTimeout(timer);
const mark = ++epoch;
const [page, id] = (location.hash.slice(1) || "home").split("/");
app.setAttribute("aria-busy", "true");
try {
if (demo) {
cat ??= await (await fetch("/catalog.json", {credentials:"omit"})).json();
const local = await import("./demo-client.js");
if (await local.current()) await localPlay();
else home();
return;
}
cat ??= await api("catalog");
if (mark !== epoch) return;
if (page === "cards") {
app.innerHTML =
'Карты колоды
' +
Object.keys(cat.cards).length +
" типов · " +
Object.values(cat.cards as Record).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 as Element).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 as HTMLInputElement;
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: KeyboardEvent) => {
const slot = (e.target as Element).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();