1060 lines
34 KiB
TypeScript
1060 lines
34 KiB
TypeScript
const demo = document.documentElement.hasAttribute("data-demo");
|
||
import { airfield } from "./airfield.js";
|
||
import { cardFace, cardLabel, cardCaption } from "./cards.js";
|
||
type GameId = string;
|
||
type Plane = { pos: string; size: number; owner: number; since: number };
|
||
type Command = { kind: string; plane?: string; to?: string; cards?: string[] };
|
||
const $ = (id: string) => 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: GameId = "",
|
||
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: any) =>
|
||
String(s ?? "").replace(
|
||
/[&<>"']/g,
|
||
(c) =>
|
||
({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[
|
||
c
|
||
],
|
||
);
|
||
const dot = (c) => '<svg class="dot" aria-hidden="true" viewBox="0 0 10 10"><circle cx="5" cy="5" r="5" fill="' + css[c] + '"/></svg>' + 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]) =>
|
||
'<option value="' +
|
||
esc(k) +
|
||
'" ' +
|
||
(String(k) === String(cur) ? "selected" : "") +
|
||
">" +
|
||
esc(v) +
|
||
"</option>",
|
||
)
|
||
.join("");
|
||
const btn = (act, label, cls = "", val: string | number = "") =>
|
||
'<button class="' +
|
||
cls +
|
||
'" data-act="' +
|
||
act +
|
||
'" data-val="' +
|
||
esc(val) +
|
||
'">' +
|
||
label +
|
||
"</button>";
|
||
const link = (hash, label) =>
|
||
'<a class="btn" href="#' + hash + '">' + label + "</a>";
|
||
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: Command) {
|
||
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<string>();
|
||
function listGames(list, manage=false) {
|
||
return list.length
|
||
? '<div class="ledger">' +
|
||
list
|
||
.map(
|
||
(g) =>
|
||
'<div class="entry"><div><b>' +
|
||
dot(g.colors[0]) +
|
||
" · " +
|
||
(g.colors.length - 1) +
|
||
(g.colors.length === 6 ? " ботов" : " бота") +
|
||
"</b><small>" +
|
||
date(g.created) +
|
||
" · Ход " +
|
||
g.turn +
|
||
(g.winner !== null
|
||
? " · " +
|
||
Math.max(
|
||
0,
|
||
Math.round(
|
||
(Date.parse(g.updated) - Date.parse(g.created)) / 60000,
|
||
),
|
||
) +
|
||
" мин · Победа: " +
|
||
names[g.colors[g.winner]]
|
||
: " · В процессе") +
|
||
"</small><details class='sub'><summary>Состав и версии</summary>" +
|
||
g.colors.map((c) => names[c]).join(", ") +
|
||
" · Правила " +
|
||
g.rules.slice(0, 12) +
|
||
" · Стратегия " +
|
||
g.strategy +
|
||
"</details></div><div class='chips'>" +
|
||
(manage && g.winner!==null ? '<label><input type="checkbox" data-mark="'+g.id+'" '+(markedGames.has(g.id)?"checked":"")+'> Выбрать</label>' : "") +
|
||
(manage ? btn("dropOne","Удалить","danger",g.id) : "") +
|
||
link(
|
||
(g.winner === null ? "game/" : "replay/") + g.id,
|
||
g.winner === null ? "Продолжить" : "Разобрать",
|
||
) +
|
||
"</div></div>",
|
||
)
|
||
.join("") +
|
||
"</div>"
|
||
: '<p class="muted">Партий пока нет.</p>';
|
||
}
|
||
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 =
|
||
'<div class="homegrid"><section class="hero"><div class="eyebrow">Аэродром / диспетчерская</div><h1>Взлёт<br>разрешён!</h1><p>Выведите свой флот из ангара, проведите его к полосе и первым отправьте в небо последний борт.</p><div class="home-field" aria-hidden="true">' +
|
||
map +
|
||
'</div></section><section class="panel"><div class="eyebrow">Полётное задание</div><h2>Новая партия</h2><fieldset><legend>Компьютерные соперники</legend><div class="chips">' +
|
||
[3, 4, 5]
|
||
.map((n) =>
|
||
btn(
|
||
"bots",
|
||
n + (n === 5 ? " ботов" : " бота"),
|
||
bots === n ? "selected" : "",
|
||
n,
|
||
),
|
||
)
|
||
.join("") +
|
||
'</div></fieldset><label class="caption" for="color">Ваша авиакомпания</label><select id="color">' +
|
||
opts([["", "Случайная компания"], ...Object.entries(names)], color) +
|
||
'</select><p class="sub space">' +
|
||
(fleet
|
||
? fleet.length +
|
||
" бортов · " +
|
||
[1, 2, 3]
|
||
.map((n) => size[n] + ": " + fleet.filter((x) => x === n).length)
|
||
.join(" / ")
|
||
: "У каждой компании свой флот. Цвета соперников определит жеребьёвка.") +
|
||
"</p>" +
|
||
btn("start", "Начать партию", "primary wide") +
|
||
'</section></div>' + (demo ? '' : '<section class="section"><div class="toolbar"><h2>Последние партии</h2><a href="#archive">Весь архив</a></div>' +
|
||
listGames(games.slice(0, 3)) + "</section>");
|
||
}
|
||
function archiveRows() {
|
||
return games.filter(
|
||
(g) =>
|
||
(!ag || g.colors.length - 1 === +ag) &&
|
||
(!ar ||
|
||
(ar === "active"
|
||
? g.winner === null
|
||
: ar === "won"
|
||
? g.winner === 0
|
||
: g.winner !== null && g.winner !== 0)) &&
|
||
(!ad || new Date(g.created).toLocaleDateString("sv-SE") === ad),
|
||
);
|
||
}
|
||
function archive() {
|
||
const rows = archiveRows();
|
||
const eligible=rows.filter(g=>g.winner!==null);
|
||
const count=eligible.filter(g=>markedGames.has(g.id)).length;
|
||
app.innerHTML =
|
||
'<div class="toolbar"><h1>Архив партий</h1>' +
|
||
link("home", "Новая партия") +
|
||
'</div><div class="controls"><select aria-label="Соперники" id="ag">' +
|
||
opts(
|
||
[
|
||
["", "Любой состав"],
|
||
[3, "3 бота"],
|
||
[4, "4 бота"],
|
||
[5, "5 ботов"],
|
||
],
|
||
ag,
|
||
) +
|
||
'</select><select aria-label="Статус" id="ar">' +
|
||
opts(
|
||
[
|
||
["", "Любой результат"],
|
||
["active", "В процессе"],
|
||
["won", "Моя победа"],
|
||
["lost", "Победа бота"],
|
||
],
|
||
ar,
|
||
) +
|
||
'</select><input type="date" aria-label="Дата партии" id="ad" value="' +
|
||
ad +
|
||
'"></div>' +
|
||
'<div class="controls archive-tools">' +
|
||
(eligible.length?btn("markAll",count===eligible.length?"Снять выбор":"Выбрать завершённые по фильтру"):"") +
|
||
(count?btn("dropMarked","Удалить выбранные ("+count+")","danger"):"") +
|
||
(games.some(g=>g.winner!==null)?btn("dropFinished","Очистить все завершённые","danger"):"") +
|
||
'</div>'+listGames(rows,true) +
|
||
'<div class="section">' +
|
||
link("replay/reference", "Разобрать эталонную партию") +
|
||
"</div>";
|
||
}
|
||
async function removeArchive(action:string,id:string){
|
||
const rows=action==="dropOne"?games.filter(g=>g.id===id):
|
||
action==="dropFinished"?games.filter(g=>g.winner!==null):
|
||
archiveRows().filter(g=>g.winner!==null && markedGames.has(g.id));
|
||
if(!rows.length)return;
|
||
const active=action==="dropOne" && rows[0].winner===null;
|
||
const message=active?"Прервать и удалить текущую партию? Продолжить её будет невозможно.":
|
||
action==="dropFinished"?"Удалить все ваши завершённые партии, включая скрытые фильтром ("+rows.length+")?":
|
||
"Удалить выбранные партии ("+rows.length+")?";
|
||
if(!window.confirm(message+" Журнал ходов и повторы будут удалены."))return;
|
||
busy=true;
|
||
try{
|
||
const result=await api("archive/remove",{ids:rows.map(g=>g.id),allow_active:active});
|
||
const updated=await api("games");
|
||
if(location.hash==="#archive"){games=updated;markedGames.clear();archive()}
|
||
notify("Удалено партий: "+result.removed);
|
||
}finally{busy=false}
|
||
}
|
||
let mapZoom = false;
|
||
function hangar(v) {
|
||
const seat = v.seat ?? 0;
|
||
const planes = Object.entries(v.planes as Record<string, Plane>).filter(([, p]) => p.owner === seat);
|
||
const parked = planes.filter(([, p]) => p.pos === "H");
|
||
return '<section class="hangar"><div class="toolbar"><h3>Ангар · ' + names[v.colors[seat]] +
|
||
'</h3><strong>' + parked.length + ' из ' + planes.length + '</strong></div>' +
|
||
(parked.length ? '<ul>' + parked.map(([id, p]) => '<li><svg aria-hidden="true" viewBox="-26 -26 52 52" fill="' +
|
||
css[v.colors[seat]] + '"><use href="#jet' + p.size + '"/></svg><span>' + pn(id) + ' · ' + size[p.size] + '</span></li>').join('') +
|
||
'</ul>' : '<p>Ангар пуст</p>') + '</section>';
|
||
}
|
||
function board(v, active = false) {
|
||
const markers = Object.fromEntries(
|
||
Object.entries(v.planes as Record<string, Plane>)
|
||
.filter(([, p]) => p.pos !== "H" && p.pos !== "F")
|
||
.map(([key, p]) => [
|
||
p.pos,
|
||
{
|
||
key,
|
||
caption: pn(key),
|
||
size: p.size,
|
||
color: css[v.colors[p.owner]],
|
||
name:
|
||
names[v.colors[p.owner]] +
|
||
" · " +
|
||
pn(key) +
|
||
" · " +
|
||
size[p.size] +
|
||
" · " +
|
||
loc(p.pos),
|
||
},
|
||
]),
|
||
);
|
||
const acts: Command[] =
|
||
active && !v.pending && mode === "move" ? data.actions : [];
|
||
const destinations = new Set(
|
||
acts.filter((c) => c.plane === selected && c.to).map((c) => c.to),
|
||
);
|
||
const field = airfield({
|
||
geometry: cat.board,
|
||
markers,
|
||
pickable: new Set(acts.map((c) => c.plane).filter(Boolean)),
|
||
destinations,
|
||
selected: active ? selected : "",
|
||
weather: v.weather,
|
||
piles: {
|
||
deck: v.deck_count,
|
||
discard: v.discard.at(-1) || "—",
|
||
weather: v.weather || "—",
|
||
},
|
||
});
|
||
const last = v.discard.at(-1);
|
||
return (
|
||
'<section class="map-panel"><div class="map-heading"><h2>Схема аэродрома</h2>' +
|
||
btn("zoom", mapZoom ? "Вписать поле" : "Увеличить поле", "map-zoom") +
|
||
'</div><div class="map-window ' +
|
||
(mapZoom ? "zoomed" : "") +
|
||
'" tabindex="0">' +
|
||
field +
|
||
'</div><div class="map-legend"><span><small>Погода</small><b>' +
|
||
(v.weather ? cardCaption(v.weather) : "Ясно") +
|
||
"</b></span><span><small>Колода</small><b>" +
|
||
v.deck_count +
|
||
"</b></span><span><small>Верх сброса</small><b>" +
|
||
(last ? cardCaption(last) : "Пусто") +
|
||
"</b></span></div>" + hangar(v) + "</section>"
|
||
);
|
||
}
|
||
function fleet(v) {
|
||
return (
|
||
'<div class="scroll"><table><thead><tr><th>Компания</th><th>Ангар</th><th>Поле</th><th>Вылетели</th></tr></thead><tbody>' +
|
||
v.colors
|
||
.map((c, i) => {
|
||
const ps = Object.values(v.planes as Record<string, Plane>).filter(
|
||
(p) => p.owner === i,
|
||
);
|
||
const h = ps.filter((p) => p.pos === "H").length,
|
||
f = ps.filter((p) => p.pos === "F").length;
|
||
return (
|
||
"<tr><td>" +
|
||
dot(c) +
|
||
(i === 0 ? " · вы" : "") +
|
||
"</td><td>" +
|
||
h +
|
||
"</td><td>" +
|
||
(ps.length - h - f) +
|
||
"</td><td>" +
|
||
f +
|
||
" / " +
|
||
ps.length +
|
||
"</td></tr>"
|
||
);
|
||
})
|
||
.join("") +
|
||
"</tbody></table></div>"
|
||
);
|
||
}
|
||
function hand(cards: string[], selectable = false) {
|
||
return (
|
||
'<div class="hand flight-hand">' +
|
||
cards
|
||
.map((c, i) =>
|
||
cardFace(c, i, selectable, selectable && exchange.includes(i)),
|
||
)
|
||
.join("") +
|
||
"</div>"
|
||
);
|
||
}
|
||
function choices() {
|
||
const v = data.view,
|
||
acts = data.actions;
|
||
if (v.winner !== null)
|
||
return (
|
||
"<h2>Победа: " +
|
||
names[v.colors[v.winner]] +
|
||
"</h2>" +
|
||
(demo ? "" : link("replay/" + gid, "Разобрать партию"))
|
||
);
|
||
if (!acts.length)
|
||
return (
|
||
"<h2>Ходит бот</h2><p>" +
|
||
dot(v.colors[v.pending?.seat ?? v.active]) +
|
||
"</p><h3>Ваша рука</h3>" +
|
||
hand(v.hand)
|
||
);
|
||
if (v.pending) {
|
||
return (
|
||
"<h2>" +
|
||
(v.pending.type === "runway" ? "Выберите ВПП" : "Выберите борт") +
|
||
"</h2><p>" +
|
||
(v.pending.type === "runway"
|
||
? "VIP-борт готов войти в очередь."
|
||
: "Вы сидите слева. Цели неприятности равноценны. Продолжит обмен компания «" +
|
||
names[v.colors[v.active]] +
|
||
"».") +
|
||
"</p>" +
|
||
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<string>(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 (
|
||
'<h2>Ваш ход</h2><div class="chips">' +
|
||
btn("mode", "Розыгрыш", mode === "move" ? "selected" : "", "move") +
|
||
btn("mode", "Обмен", mode === "exchange" ? "selected" : "", "exchange") +
|
||
"</div>" +
|
||
(mode === "exchange"
|
||
? '<p class="sub">Выберите 1–4 карты для открытого обмена.</p><button class="primary wide" data-act="exchange" ' +
|
||
(!exchange.length ? "disabled" : "") +
|
||
">Обменять (" +
|
||
exchange.length +
|
||
")</button>"
|
||
: group.length
|
||
? '<div class="selector space"><label for="plane">Борт или погода</label><select id="plane">' +
|
||
opts(
|
||
targets.map((k) => [
|
||
k,
|
||
k === "weather"
|
||
? "Изменить погоду"
|
||
: pn(k) +
|
||
" · " +
|
||
size[v.planes[k].size] +
|
||
" · " +
|
||
loc(v.planes[k].pos),
|
||
]),
|
||
selected,
|
||
) +
|
||
'</select><label for="action">Маршрут и оплата</label><select id="action">' +
|
||
opts(
|
||
group.map(([c, i]) => [i, cname(c)]),
|
||
cmdIndex,
|
||
) +
|
||
"</select></div>" +
|
||
btn("send", "Подтвердить ход", "primary wide", cmdIndex)
|
||
: "<p>Доступен обмен карт.</p>") +
|
||
'<p class="caption space">Карты на руке · ' +
|
||
v.hand.length +
|
||
"</p>" +
|
||
hand(v.hand, mode === "exchange")
|
||
);
|
||
}
|
||
function live() {
|
||
const v = data.view;
|
||
const actionPanel = choices();
|
||
app.innerHTML =
|
||
'<div class="toolbar"><div><span class="eyebrow">Партия / ' +
|
||
(demo ? "Демо" : gid.slice(0, 6)) +
|
||
"</span><h1>Ход " +
|
||
v.turn +
|
||
"</h1></div><div>" +
|
||
(demo ? btn("setup", "Новая партия", "") : link("replay/" + gid, "Журнал партии")) +
|
||
'</div></div><div class="tablegrid">' +
|
||
board(v, true) +
|
||
'<section class="panel">' +
|
||
actionPanel +
|
||
'</section><section class="panel"><h2>Флоты</h2>' +
|
||
fleet(v) +
|
||
'</section><section class="panel"><div class="toolbar"><h2>Радиообмен</h2><span class="tag">Колода ' +
|
||
v.deck_count +
|
||
'</span></div><ul class="log">' +
|
||
data.recent
|
||
.slice(-5)
|
||
.map((ev) => "<li>" + esc(textEvent(ev, v)) + "</li>")
|
||
.join("") +
|
||
'</ul>' + (demo ? '' : '<label><input id="fast" type="checkbox" ' +
|
||
(fast ? "checked" : "") +
|
||
"> Быстрое обновление</label>") + "</section></div>";
|
||
}
|
||
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 (
|
||
'<section class="panel section"><h2>Итоги партии</h2><div class="scroll"><table><thead><tr>' +
|
||
[
|
||
"Компания",
|
||
"Вылеты",
|
||
"Обмены",
|
||
"Возвраты в ангар",
|
||
"Уходы в хвост",
|
||
"31L",
|
||
"31R",
|
||
]
|
||
.map((t) => "<th>" + t + "</th>")
|
||
.join("") +
|
||
"</tr></thead><tbody>" +
|
||
rows
|
||
.map(
|
||
(r, i) =>
|
||
"<tr><td>" +
|
||
dot(v.colors[i]) +
|
||
"</td>" +
|
||
["flights", "ex", "ret", "tail", "31L", "31R"]
|
||
.map((k) => "<td>" + r[k] + "</td>")
|
||
.join("") +
|
||
"</tr>",
|
||
)
|
||
.join("") +
|
||
"</tbody></table></div></section>"
|
||
);
|
||
}
|
||
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 =
|
||
'<div class="toolbar"><div><span class="eyebrow">Архив / ' +
|
||
gid.slice(0, 6) +
|
||
'</span><h1>Разбор партии</h1></div><div class="chips">' +
|
||
(rep.finished
|
||
? '<a class="btn" href="/api/' +
|
||
(gid === "reference" ? "reference" : "games/" + gid) +
|
||
'/export">Скачать JSON</a>'
|
||
: link("game/" + gid, "К игре")) +
|
||
'</div></div><section class="panel"><div class="toolbar"><b>Ход ' +
|
||
ev.turn +
|
||
" · Событие " +
|
||
rep.seq +
|
||
" из " +
|
||
rep.last +
|
||
'</b><select aria-label="Перспектива" id="eye">' +
|
||
opts(
|
||
rep.finished
|
||
? [
|
||
["full", "Полный разбор"],
|
||
...v.colors.map((c, i) => [i, "Глазами: " + names[c]]),
|
||
]
|
||
: [[0, "Моя перспектива"]],
|
||
eye,
|
||
) +
|
||
'</select></div><input class="range" aria-label="Событие" id="step" type="range" min="1" max="' +
|
||
rep.last +
|
||
'" value="' +
|
||
rep.seq +
|
||
'"><div class="controls">' +
|
||
[
|
||
["first", "Начало"],
|
||
["backturn", "− ход"],
|
||
["prev", "− событие"],
|
||
["next", "+ событие"],
|
||
["nextturn", "+ ход"],
|
||
["last", "Конец"],
|
||
]
|
||
.map(([a, t]) => btn(a, t))
|
||
.join("") +
|
||
'<label>К ходу <input type="number" id="jump" min="1" max="' +
|
||
t.at(-1).turn +
|
||
'" value="' +
|
||
ev.turn +
|
||
'" class="replay-step"></label></div><b>' +
|
||
esc(textEvent(ev, v)) +
|
||
"</b>" +
|
||
(d.observed_seq
|
||
? btn("before", "Позиция перед решением", "", d.observed_seq)
|
||
: "") +
|
||
(d.alternatives?.length
|
||
? "<ol>" +
|
||
d.alternatives
|
||
.map(
|
||
(o) =>
|
||
"<li>" +
|
||
esc(cname(o.command)) +
|
||
" · " +
|
||
o.score +
|
||
" · " +
|
||
esc(o.reason) +
|
||
"</li>",
|
||
)
|
||
.join("") +
|
||
"</ol>"
|
||
: "") +
|
||
'</section><div class="tablegrid section">' +
|
||
board(v) +
|
||
'<section class="panel"><h2>Карты в этот момент</h2>' +
|
||
(v.hands
|
||
? v.hands
|
||
.map((h, i) => "<h3>" + dot(v.colors[i]) + "</h3>" + hand(h))
|
||
.join("") +
|
||
"<details><summary>Колода сверху вниз · " +
|
||
v.deck.length +
|
||
"</summary>" +
|
||
hand(v.deck) +
|
||
"</details>"
|
||
: "<h3>" +
|
||
dot(v.colors[v.seat]) +
|
||
"</h3>" +
|
||
hand(v.hand) +
|
||
'<p class="sub space">В колоде ' +
|
||
v.deck_count +
|
||
" карт.</p>" +
|
||
"<details><summary>Открыто полученные карты на руках</summary>" +
|
||
v.known
|
||
.map(
|
||
(known, i) =>
|
||
"<p>" +
|
||
names[v.colors[i]] +
|
||
" · " +
|
||
(Object.entries(known)
|
||
.map(([c, n]) => cardCaption(c) + " × " + n)
|
||
.join(", ") || "нет известных") +
|
||
"</p>",
|
||
)
|
||
.join("") +
|
||
"</details>") +
|
||
'</section></div><section class="panel section"><h2>События до выбранного момента</h2><div class="controls"><select aria-label="Тип" id="ff">' +
|
||
opts([["", "Все события"], ...Object.entries(types)], ff) +
|
||
'</select><select aria-label="Борт" id="pf">' +
|
||
opts(
|
||
[["", "Все борта"], ...Object.keys(v.planes).map((k) => [k, pn(k)])],
|
||
pf,
|
||
) +
|
||
'</select><select aria-label="Компания" id="cf">' +
|
||
opts([["", "Все компании"], ...v.colors.map((c, i) => [i, names[c]])], cf) +
|
||
'</select></div><div class="choices">' +
|
||
list
|
||
.slice()
|
||
.reverse()
|
||
.map((e) =>
|
||
btn("goto", "#" + e.seq + " · " + esc(textEvent(e, v)), "", e.seq),
|
||
)
|
||
.join("") +
|
||
"</div></section>" +
|
||
(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 =
|
||
'<div class="toolbar"><h1>Карты колоды</h1></div><p class="muted">' +
|
||
Object.keys(cat.cards).length +
|
||
" типов · " +
|
||
Object.values(cat.cards as Record<string, number>).reduce(
|
||
(sum, n) => sum + n,
|
||
0,
|
||
) +
|
||
" карт в комплекте</p>" +
|
||
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<HTMLButtonElement>("[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<SVGElement>(".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();
|