Initial
This commit is contained in:
commit
2ca7a264b3
53 files changed
+7113
No files matched your search
@@ -0,0 +1,6 @@
|
|||||||
|
*
|
||||||
|
!requirements.txt
|
||||||
|
!game
|
||||||
|
!game/**
|
||||||
|
**/__pycache__
|
||||||
|
**/*.pyc
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
BIND_ADDRESS=127.0.0.1
|
||||||
|
HTTP_PORT=8080
|
||||||
|
COOKIE_SECURE=0
|
||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
FROM python:3.12-slim-bookworm@sha256:935c3c5b12357a7e10caa9c1e6ca5692344d97cf229832ef584be2cec9fc03df AS python
|
||||||
|
FROM python AS dependencies
|
||||||
|
COPY requirements.txt /requirements.txt
|
||||||
|
RUN pip install --disable-pip-version-check --no-cache-dir --no-compile --require-hashes --only-binary=:all: --target=/opt/packages -r /requirements.txt
|
||||||
|
|
||||||
|
FROM python AS base
|
||||||
|
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 PYTHONPATH=/opt/packages
|
||||||
|
WORKDIR /app
|
||||||
|
COPY --from=dependencies /opt/packages /opt/packages
|
||||||
|
RUN install -d -o 10001 -g 10001 -m 0750 /data
|
||||||
|
USER 10001:10001
|
||||||
|
|
||||||
|
FROM base AS worker
|
||||||
|
COPY game/__init__.py game/worker.py game/strategy.py ./game/
|
||||||
|
CMD ["python","-m","uvicorn","game.worker:app","--host","0.0.0.0","--port","8081","--no-server-header","--no-access-log","--limit-concurrency","64"]
|
||||||
|
|
||||||
|
FROM base AS web
|
||||||
|
COPY game ./game
|
||||||
|
CMD ["python","-m","uvicorn","game.api:app","--host","0.0.0.0","--port","8080","--no-server-header","--no-access-log","--limit-concurrency","64"]
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
FROM python:3.12-slim-bookworm@sha256:935c3c5b12357a7e10caa9c1e6ca5692344d97cf229832ef584be2cec9fc03df AS assets
|
||||||
|
WORKDIR /src
|
||||||
|
COPY game/static game/static
|
||||||
|
COPY game/catalog.json game/engine.py game/strategy.py game/
|
||||||
|
COPY demo demo
|
||||||
|
RUN cd demo/vendor && sha256sum -c ../SHA256SUMS
|
||||||
|
RUN python demo/prepare.py /out
|
||||||
|
|
||||||
|
FROM golang:1.26-alpine@sha256:ecb67f987aa1a57794c91d19ade7ae0209f2f0f5496aaef9e6ae85ddf92d02ab AS build
|
||||||
|
WORKDIR /src
|
||||||
|
COPY demo/server.go .
|
||||||
|
COPY --from=assets /out ./public
|
||||||
|
RUN CGO_ENABLED=0 GOPROXY=off go build -trimpath -ldflags="-s -w -buildid=" -o /server server.go
|
||||||
|
|
||||||
|
FROM scratch
|
||||||
|
COPY --from=build /server /server
|
||||||
|
USER 10001:10001
|
||||||
|
ENTRYPOINT ["/server"]
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
*
|
||||||
|
!game/
|
||||||
|
!game/static/
|
||||||
|
!game/static/*.js
|
||||||
|
!game/static/style.css
|
||||||
|
!game/static/index.html
|
||||||
|
!game/engine.py
|
||||||
|
!game/strategy.py
|
||||||
|
!game/catalog.json
|
||||||
|
!demo/
|
||||||
|
!demo/*.go
|
||||||
|
!demo/*.py
|
||||||
|
!demo/*.js
|
||||||
|
!demo/LICENSE-*
|
||||||
|
!demo/SHA256SUMS
|
||||||
|
!demo/vendor/
|
||||||
|
!demo/vendor/*
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
# Взлёт разрешён! 0.1.4
|
||||||
|
|
||||||
|
Самостоятельно размещаемая браузерная игра по буклету 00475. В обычном режиме один человек управляет авиакомпанией, за одним столом с ним играют три, четыре или пять серверных ботов. Побеждает компания, первой отправившая в небо весь свой флот. Сервер сохраняет каждое решение и каждый результат добора. Интерфейс, правила и история работают внутри развёрнутого приложения без внешнего API, CDN и ключей моделей.
|
||||||
|
|
||||||
|
## Адаптивное игровое поле в 0.1.4
|
||||||
|
|
||||||
|
При ширине окна от 960 CSS-пикселей поле с ангаром располагается слева, а действия и карты игрока справа. В повторе справа показаны карты на выбранном шаге. На узком экране эти панели идут друг под другом. Кнопка увеличения позволяет прокручивать схему внутри её панели.
|
||||||
|
|
||||||
|
## Режим развёртывания в 0.1.3
|
||||||
|
|
||||||
|
В игре под схемой аэродрома видны позывные и силуэты бортов, которые сейчас в ангаре. Счётчик показывает остаток и полный размер флота. В повторе ангар соответствует выбранной перспективе и событию.
|
||||||
|
|
||||||
|
| Режим | Команда из корня проекта | Хранение |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Обычный | `docker compose up -d --build --wait` | SQLite в прежнем томе, меню и архив партий |
|
||||||
|
| Публичное демо | `docker compose -f compose.demo.yaml up -d --build --wait` | Одна текущая партия в cookie браузера, без меню и архива |
|
||||||
|
|
||||||
|
Используйте compose.demo.yaml самостоятельно. Для одновременной работы двух режимов задайте другой порт, например `HTTP_PORT=8082 docker compose -f compose.demo.yaml up -d --build --wait`. Для публикации выделите демо отдельное доменное имя с HTTPS и проксируйте корень сайта на 127.0.0.1 и выбранный порт. На той же машине для теста подходит http://localhost:8080. Префикс URL не поддерживается. Публичный HTTP по IP не даёт браузеру запустить service worker.
|
||||||
|
|
||||||
|
Демо запускает один статический HTTP-сервер. Правила Python и алгоритм ботов работают в браузерном worker через Pyodide 0.28.3. При первом старте браузер загружает около 12 МиБ файлов среды с вашего сайта. Настройки, руки, порядок карт и позиции находятся в одной локальной cookie со сроком 30 дней с последнего сохранения. Страница восстанавливает игру при повторном открытии. Кнопка «Новая партия» позволяет заменить позицию. Очистка cookie удаляет сохранение. Для игры нужны разрешённые cookie, Service Worker, Web Locks и WebAssembly. При отключённом хранилище UI сообщает об ошибке.
|
||||||
|
|
||||||
|
Для доступа к cookie приложение создаёт скрытый документ под отдельным путём. Service worker отвечает на его запрос в самом браузере. У игровых ресурсов и страницы другой путь, поэтому при штатной игре браузер загружает их без cookie позиции. Демо не использует серверный API и не накапливает историю. Алгоритм бота получает только видимую ему позицию и разрешённые действия. Владелец браузера технически может прочитать или изменить своё сохранение.
|
||||||
|
|
||||||
|
Демо-образ на базе scratch содержит один статический бинарник с ресурсами. В контейнере нет оболочки, интерпретатора ОС, томов и драйверов БД. Сервис работает под UID/GID 10001 с read-only rootfs, пустым набором capabilities, no-new-privileges, ограничениями памяти, CPU, процессов и файловых дескрипторов. HTTP-сервер обслуживает GET/HEAD и healthcheck, применяет тайм-ауты, CSP и запрет встраивания страницы другим сайтом. Запросы не попадают в access log приложения. Логи и лимиты внешнего HTTPS-прокси регулируются на прокси.
|
||||||
|
|
||||||
|
Базовые образы зафиксированы по digest, Python-пакеты и локальные файлы Pyodide проверяются по SHA-256. Для обновления зависимостей требуется обновить фиксации и повторить проверки. В обычном режиме ограничения контейнеров применены к web и bot. Рабочие данные SQLite записываются в /data. Для длительного резервного копирования используйте каталог с достаточным местом, учитывая лимит /tmp.
|
||||||
|
|
||||||
|
## Что изменилось в MVP2
|
||||||
|
|
||||||
|
Аэродром нарисован в SVG по схеме из буклета 00475. Векторный оригинал реализован в airfield.ts. Пустое поле для просмотра в браузере или редактирования в Inkscape находится в art/aerodrome.svg. Обе ВПП, очереди D, стоянки A/B и A/C, отдельные ветки VIP и терминал видны на одном поле. Цвет, позывной и силуэт обозначают компанию, конкретный борт и его размер. В руке и в архиве у каждой карты есть название на русском и английском, категория, рисунок и описание действия. Раздел «Карты» показывает все 16 типов из исходного комплекта.
|
||||||
|
|
||||||
|
В свой ход выберите борт на поле или в списке. Доступные места обведены пунктиром. Нажмите на место, проверьте оплату и нажмите «Подтвердить ход». Доступные позиции также выбираются клавишами Tab и Enter. На телефоне кнопка «Увеличить поле» включает прокрутку внутри схемы. В архиве используется та же карта аэродрома с расстановкой на выбранное событие.
|
||||||
|
|
||||||
|
## Архив и SQLite в 0.1.2
|
||||||
|
|
||||||
|
По умолчанию Compose запускает web и bot. Файл SQLite расположен в /data/dispatch.sqlite3 в постоянном томе sqlite_data, доступном только web. Воркер получает только сведения, доступные его месту за столом по внутренней сети. SQLite использует WAL и транзакции записи с ожиданием блокировки. Такой режим рассчитан на один экземпляр web и локальный диск Docker-хоста.
|
||||||
|
|
||||||
|
В «Архиве партий» можно удалить отдельную партию, выбрать завершённые по фильтру или очистить все свои завершённые партии. Перед удалением интерфейс показывает подтверждение. Удаление текущей партии доступно по одной строке, с отдельным предупреждением. Очистка удаляет партию, журнал, снимки и квитанции команд. Другие владельцы и эталонный повтор сохраняют свои данные. SQLite повторно использует освободившиеся страницы при следующих записях; размер файла сразу после очистки может остаться прежним.
|
||||||
|
|
||||||
|
### Переход с PostgreSQL из 0.1.0 или 0.1.1
|
||||||
|
|
||||||
|
Сохраните прежние .env, имя проекта Compose и адрес сайта. Разверните файлы текущего релиза поверх исходников. Если есть нужные партии, выполните перенос **до первого запуска новой игры на SQLite**. Источник на время копирования должен быть свободен от записи. Команды выполняются из корня проекта:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose -f compose.postgres.yaml stop web
|
||||||
|
docker compose -f compose.postgres.yaml up -d --wait db
|
||||||
|
docker compose -f compose.postgres.yaml exec -T db sh -ec 'exec pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Fc' > vzlet-before-sqlite.dump
|
||||||
|
docker compose -f compose.postgres.yaml run --rm --build migrate
|
||||||
|
docker compose -f compose.postgres.yaml stop db
|
||||||
|
docker compose up -d --build
|
||||||
|
```
|
||||||
|
|
||||||
|
Продолжайте после успешного завершения каждой команды. Утилита переносит четыре таблицы из согласованного снимка PostgreSQL в одной транзакции SQLite, сверяет число строк и проверяет целостность. Она откажется записывать поверх непустого архива. Прежние тома PostgreSQL и пароль сохраняются. После перехода проверьте свой архив в прежнем браузере. Для продолжения работы на PostgreSQL вместо перехода используйте `docker compose -f compose.postgres.yaml up -d --build`. Партии, созданные после переключения, принадлежат выбранной базе; обратной синхронизации нет.
|
||||||
|
|
||||||
|
Номер сборки виден рядом с названием игры на всех экранах. Для нового релиза измените значение в элементе build-version файла game/static/index.html перед сборкой образа web.
|
||||||
|
|
||||||
|
## Запуск в Docker
|
||||||
|
|
||||||
|
Нужны Docker Engine и Docker Compose v2. Из корня распакованного проекта:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose up -d --build
|
||||||
|
docker compose ps
|
||||||
|
curl -fsS http://127.0.0.1:8080/health
|
||||||
|
```
|
||||||
|
|
||||||
|
Откройте [диспетчерскую](http://127.0.0.1:8080). При первом запуске загружаются базовые образы и Python-зависимости. Статический интерфейс уже собран. Готовность web и bot контролируется healthcheck.
|
||||||
|
|
||||||
|
Для доступа с другой машины скопируйте .env.example в .env, установите BIND_ADDRESS в адрес интерфейса сервера и при необходимости измените HTTP_PORT. Повторите docker compose up -d. При работе за Nginx можно оставить привязку к 127.0.0.1. Проксируйте весь корневой путь на этот порт, включая /api/. Для внешнего HTTPS задайте COOKIE_SECURE=1. Внутри HTTP-стенда используется значение 0. Воркер доступен только во внутренней сети.
|
||||||
|
|
||||||
|
## Первая партия
|
||||||
|
|
||||||
|
1. Выберите количество ботов и цвет. По выбору цвета интерфейс покажет состав флота. Сервер назначит первого участника случайно.
|
||||||
|
2. В свой ход выберите борт, маршрут и оплату либо погоду. При наличии капитанов список включает доступные комбинации. Для обмена включите вкладку «Обмен», отметьте до четырёх карт и подтвердите. Поле показывает обе полосы в порядке от старта к хвосту, букву компании, номер борта и его размер.
|
||||||
|
3. Внеочередной запрос появляется, когда нужно выбрать цель неприятности соседа или полосу VIP-борта. Игру можно закрыть даже в этой фазе. Откройте тот же сайт в том же профиле браузера и выберите «Продолжить».
|
||||||
|
4. В архиве можно отобрать партии по дате, числу ботов и результату. Откройте «Разобрать»; переход «Конец» покажет итоговый отчёт по компаниям и полосам. Кнопка «Разобрать эталонную партию» сразу открывает запись реального прогона, где тестовый клиент управлял местом человека.
|
||||||
|
5. В повторе меняйте ход, событие и перспективу. У решения бота видны его оценки и переход к позиции непосредственно перед выбором. Полный режим показывает колоду сверху вниз. JSON-экспорт доступен владельцу завершённой партии. Для доступа к своим играм браузер хранит HttpOnly cookie. Удаление cookie или другой профиль браузера создают отдельную историю владельца.
|
||||||
|
|
||||||
|
## Игровой движок и трактовки
|
||||||
|
|
||||||
|
Правила, сканы и сверка комплекта описаны в [заметках о каталоге](catalog-notes.md). Игровые данные находятся в game/catalog.json; они включают флот, состав колоды и связность слотов. Буклету 00475 соответствуют 34 борта и 146 карт. При открытом обмене погода или неприятность действует сразу. При закрытом доборе такая же карта остаётся в руке. Первоначальная погода не занимает физическую карту.
|
||||||
|
|
||||||
|
Для редакции 00475 боковой ветер ограничивает малые борта. Готовность для неприятности сравнивается сначала по положению на поле, затем по размеру; при равенстве выбирает сосед слева. На замороженной полосе можно добавлять борта в хвост без обгона. Промежутки после поломки закрываются после снятия запрета. Капитан оплачивает любую единицу движения A/B/C/D, в том числе дополнительную стоимость при снеге. Позиции на полосу после VIP выбирает владелец, если доступны два направления.
|
||||||
|
|
||||||
|
## Архитектура и видимость
|
||||||
|
|
||||||
|
FastAPI валидирует команды и рассчитывает правила на сервере. TypeScript-интерфейс показывает персональную проекцию и доступные действия. Каждое событие сохраняется с номером хода, временем UTC, причиной и сжатым снимком состояния. Снимки позволяют переходить к середине хода и воспроизводить старый результат независимо от текущей стратегии. Цена такого подхода — размер БД растёт с числом событий. Полные выгрузки содержат закрытую информацию всех мест.
|
||||||
|
|
||||||
|
Бот получает только наблюдение конкретного места, разрешённые варианты и историю с применёнными ограничениями видимости. Воркер не хранит состояние между запросами. У него отдельный образ и внутренняя сеть без доступа к сети базы и её тому. Сведения о фактических остатках колоды, перестановках и закрытых доборах соперников не входят в протокол. При равенстве оценок используется стабильный порядок вариантов. При сетевой ошибке сервер повторяет запрос, затем применяет резервное действие с записью причины.
|
||||||
|
|
||||||
|
Команда содержит UUID и ожидаемую версию партии. Повтор запроса возвращает прежнюю квитанцию. Параллельная команда с устаревшей версией получает HTTP 409. Команда, её события, следующее ожидаемое место и состояние фиксируются одной транзакцией. По незавершённым партиям сервер восстанавливает очередь ботов после старта. Сеанс пользователя привязан к хешу случайного токена владельца. Экспорт и запросы к партиям проверяют принадлежность сеанса.
|
||||||
|
|
||||||
|
## Технические проверки
|
||||||
|
|
||||||
|
Python 3.12. Чистые тесты механики используют стандартную библиотеку. Для полного набора тестов, включая HTTP-контракт и конкурирующие запросы:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 -m venv .venv
|
||||||
|
.venv/bin/python -m pip install --require-hashes --only-binary=:all: -r requirements.txt
|
||||||
|
.venv/bin/python -m pip install -r requirements-test.txt
|
||||||
|
.venv/bin/python -m unittest discover -s tests -v
|
||||||
|
.venv/bin/python verify_replay.py game/fixtures/reference.json.gz
|
||||||
|
```
|
||||||
|
|
||||||
|
Просмотр полного состояния события 40 и проверка скачанного JSON:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 verify_replay.py game/fixtures/reference.json.gz --step 40
|
||||||
|
python3 verify_replay.py dispatch-export.json
|
||||||
|
```
|
||||||
|
|
||||||
|
Второй команде передайте имя фактически скачанного файла. Верификатор проверяет нумерацию событий, переходы между ходами, неизменность флота, баланс карт на каждом шаге и конечную победу. В JSON внутренний массив deck хранится от дна к вершине; верхняя карта последняя. Интерфейс полного разбора разворачивает его для чтения.
|
||||||
|
|
||||||
|
Для локальной разработки без Docker запустите в отдельных терминалах из корня проекта:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
.venv/bin/uvicorn game.worker:app --host 127.0.0.1 --port 8081
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
.venv/bin/uvicorn game.api:app --host 127.0.0.1 --port 8080
|
||||||
|
```
|
||||||
|
|
||||||
|
В этом режиме используется файл dispatch.sqlite3. SQLITE_PATH меняет его расположение. DATABASE_URL переключает приложение на PostgreSQL. BOT_URL задаёт внутренний адрес воркера. Для повторной сборки браузерного кода после изменения app.ts:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx --yes --package typescript@5.8.3 tsc --target ES2022 --module es2022 --outDir game/static app.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
## Резервная копия SQLite и восстановление
|
||||||
|
|
||||||
|
Создать согласованную копию работающей базы на хосте:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose exec -T web python -m game.sqlite_backup > vzlet.sqlite3
|
||||||
|
```
|
||||||
|
|
||||||
|
Для восстановления в отдельный пустой проект используйте новый том и свободный порт. Команда импорта откажется заменить существующую базу. Сохраните cookie владельца и открывайте восстановленную игру с тем же именем хоста.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export COMPOSE_PROJECT_NAME=vzlet-restore
|
||||||
|
export HTTP_PORT=18080
|
||||||
|
docker compose run --rm --build --no-deps -T web python -m game.sqlite_backup --restore < vzlet.sqlite3
|
||||||
|
docker compose up -d --build
|
||||||
|
```
|
||||||
|
|
||||||
|
Обычный перезапуск сохраняет том SQLite. При обновлении сначала сделайте копию. Опция `docker compose down -v` удаляет тома.
|
||||||
+255
@@ -0,0 +1,255 @@
|
|||||||
|
/** Vector airfield for edition 00475. Positions share the engine's slot IDs. */
|
||||||
|
type Point = { x: number; y: number; angle: number; label: string };
|
||||||
|
type Geometry = {
|
||||||
|
ab_stands: number;
|
||||||
|
b_stands: number;
|
||||||
|
ac_stands: number;
|
||||||
|
queue_capacity: number;
|
||||||
|
runways: string[];
|
||||||
|
};
|
||||||
|
type Marker = {
|
||||||
|
key: string;
|
||||||
|
caption: string;
|
||||||
|
color: string;
|
||||||
|
size: number;
|
||||||
|
name: string;
|
||||||
|
};
|
||||||
|
type MapView = {
|
||||||
|
geometry: Geometry;
|
||||||
|
markers: Record<string, Marker>;
|
||||||
|
pickable: Set<string>;
|
||||||
|
destinations: Set<string>;
|
||||||
|
selected: string;
|
||||||
|
weather: string | null;
|
||||||
|
piles?: { deck: number; discard: string; weather: string };
|
||||||
|
};
|
||||||
|
const width = 1080,
|
||||||
|
height = 548;
|
||||||
|
const laneY = (lane: string) => (lane === "31R" ? 57 : 491);
|
||||||
|
const queueY = (lane: string) => (lane === "31R" ? 129 : 419);
|
||||||
|
const spread = (i: number, n: number, from: number, to: number) =>
|
||||||
|
n <= 1 ? (from + to) / 2 : from + ((to - from) * i) / (n - 1);
|
||||||
|
|
||||||
|
function geometry(b: Geometry) {
|
||||||
|
const points: Record<string, Point> = {};
|
||||||
|
const add = (
|
||||||
|
id: string,
|
||||||
|
x: number,
|
||||||
|
y: number,
|
||||||
|
angle: number,
|
||||||
|
label: string,
|
||||||
|
) => (points[id] = { x, y, angle, label });
|
||||||
|
for (const lane of b.runways) {
|
||||||
|
const sy = laneY(lane),
|
||||||
|
qy = queueY(lane);
|
||||||
|
add("D:" + lane + ":0", 987, sy, -90, "D");
|
||||||
|
for (let n = 1; n < b.queue_capacity; n++)
|
||||||
|
add(
|
||||||
|
"D:" + lane + ":" + n,
|
||||||
|
spread(n - 1, b.queue_capacity - 1, 949, 670),
|
||||||
|
qy,
|
||||||
|
90,
|
||||||
|
"D" + n,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for (let n = 0; n < b.ab_stands; n++) {
|
||||||
|
const upper = n < Math.ceil(b.ab_stands / 2),
|
||||||
|
count = upper ? Math.ceil(b.ab_stands / 2) : Math.floor(b.ab_stands / 2);
|
||||||
|
add(
|
||||||
|
"A:B" + (n + 1),
|
||||||
|
spread(upper ? n : n - Math.ceil(b.ab_stands / 2), count, 440, 600),
|
||||||
|
upper ? 215 : 332,
|
||||||
|
upper ? 180 : 0,
|
||||||
|
"A" + (n + 1),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for (let n = 0; n < b.b_stands; n++)
|
||||||
|
add(
|
||||||
|
"B:B" + (n + 1),
|
||||||
|
spread(n, b.b_stands, 410, 638),
|
||||||
|
n % 2 ? 371 : 176,
|
||||||
|
90,
|
||||||
|
"B" + (n + 1),
|
||||||
|
);
|
||||||
|
for (let n = 0; n < b.ac_stands; n++) {
|
||||||
|
const x = spread(n, b.ac_stands, 116, 258);
|
||||||
|
add("A:C" + (n + 1), x, 260, 0, "A" + (n + 1));
|
||||||
|
add("C:C" + (n + 1), x, 311, 180, "C" + (n + 1));
|
||||||
|
}
|
||||||
|
for (const lane of b.runways) {
|
||||||
|
const upper = lane === "31R";
|
||||||
|
add("V1:" + lane, 834, upper ? 231 : 317, 90, "VIP1");
|
||||||
|
add("V2:" + lane, 914, upper ? 231 : 317, 90, "VIP2");
|
||||||
|
}
|
||||||
|
return points;
|
||||||
|
}
|
||||||
|
|
||||||
|
function runway(lane: string, weather: string | null) {
|
||||||
|
const y = laneY(lane);
|
||||||
|
const bars = Array.from(
|
||||||
|
{ length: 6 },
|
||||||
|
(_, i) =>
|
||||||
|
'<path d="M54 ' +
|
||||||
|
(y - 13 + i * 5) +
|
||||||
|
"h31 M1026 " +
|
||||||
|
(y - 13 + i * 5) +
|
||||||
|
'h-30"/>',
|
||||||
|
).join("");
|
||||||
|
const lights = Array.from(
|
||||||
|
{ length: 24 },
|
||||||
|
(_, i) => '<path d="M' + (44 + i * 43) + " " + (y - 22) + 'v2 m0 40v2"/>',
|
||||||
|
).join("");
|
||||||
|
return `<g><rect x="28" y="${y - 25}" width="1024" height="50" rx="5" fill="#687773" stroke="#92a492" stroke-width="5"/>
|
||||||
|
<rect x="34" y="${y - 19}" width="1012" height="38" fill="url(#asphalt)" stroke="#c5cdc0" stroke-width="1.4"/>
|
||||||
|
<g stroke="#ecebdd" stroke-width="2.6">${bars}<path d="M171 ${y}H920" stroke-dasharray="20 16"/></g>
|
||||||
|
<path d="M225 ${y - 10}h35 m0 20h-35 M785 ${y - 10}h35 m0 20h-35" stroke="#d1d7cb" stroke-width="4"/>
|
||||||
|
<g stroke="#e5dfad" stroke-width="3">${lights}</g>
|
||||||
|
<text x="106" y="${y + 8}" class="rw-number">${lane}</text>
|
||||||
|
${weather === lane || weather === "FG" ? '<path d="M930 ' + (y - 12) + 'l23 24m0 -24l-23 24" stroke="#ff9c64" stroke-width="5"/>' : ""}</g>`;
|
||||||
|
}
|
||||||
|
const fieldDefs = `<defs>
|
||||||
|
<pattern id="grass" width="21" height="17" patternUnits="userSpaceOnUse"><rect width="21" height="17" fill="#9aa780"/><path d="M2 3h4m8 7h3m-8 4h3" stroke="#718765" stroke-width=".9" opacity=".38"/></pattern>
|
||||||
|
<pattern id="roof" width="8" height="8" patternUnits="userSpaceOnUse"><rect width="8" height="8" fill="#c5d3cb"/><path d="M1 0v8" stroke="#a3b8ad"/></pattern>
|
||||||
|
<pattern id="asphalt" width="23" height="16" patternUnits="userSpaceOnUse"><rect width="23" height="16" fill="#515e60"/><path d="M0 0h23m-17 0v16" stroke="#657073" stroke-width=".7"/></pattern>
|
||||||
|
<pattern id="apron" width="30" height="28" patternUnits="userSpaceOnUse"><rect width="30" height="28" fill="#bdc4ae"/><path d="M0 28V0h30" fill="none" stroke="#9ca896" stroke-width="1.4"/></pattern>
|
||||||
|
<g id="tree"><path d="M-6 4l1-8 4-5 6 2 4 6-3 7-7 1z" fill="#546f54"/><path d="M-6 1l1-7 5-4 5 3 1 6-5 5z" fill="#71885e"/><path d="M-4-4l4-4 3 3" fill="#889967"/></g>
|
||||||
|
<g id="vent"><rect width="12" height="9" rx="1" fill="#82988d"/><circle cx="6" cy="4.5" r="3" fill="#a5b5a9" stroke="#506a62"/><path d="M3 4.5h6m-3-3v6" stroke="#657d72"/></g>
|
||||||
|
<g id="jet1"><path d="M0-15Q3-13 2-2L14 1v3L2 3l-1 8 5 3v2l-6-2-6 2v-2l5-3-1-8-12 1V1l12-3Q-3-13 0-15Z"/></g>
|
||||||
|
<g id="jet2"><path d="M0-19Q3-18 3-6L19 4v4L3 3l-1 10 6 4v2l-8-3-8 3v-2l6-4-1-10-16 5V4L-3-6Q-3-18 0-19Z"/><path d="M-9-2v7m18-7v7" stroke-width="3"/></g>
|
||||||
|
<g id="jet3"><path d="M0-22Q4-20 3.8-7L23 4v5L4 4l-2 11 8 5v3l-10-4-10 4v-3l8-5-2-11-19 5V4L-3.8-7Q-4-20 0-22Z"/><path d="M-15 0v7m7-10v8m16-8v8m7-5v7" stroke-width="3.6"/></g>
|
||||||
|
</defs>`;
|
||||||
|
function building(x: number, y: number, w: number, h: number) {
|
||||||
|
const vents = Array.from(
|
||||||
|
{ length: Math.max(1, Math.floor(w / 44)) },
|
||||||
|
(_, i) => `<use href="#vent" x="${x + 8 + 35 * i}" y="${y + 5}"/>`,
|
||||||
|
).join("");
|
||||||
|
return `<g><rect x="${x + 4}" y="${y + 5}" width="${w}" height="${h}" rx="3" fill="#54685c" opacity=".5"/>
|
||||||
|
<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="3" fill="url(#roof)" stroke="#667d72" stroke-width="2"/>
|
||||||
|
<path d="M${x + 4} ${y + h - 3}h${w - 8}" stroke="#73979a" stroke-width="4" stroke-dasharray="8 3"/>${vents}</g>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function apronEquipment() {
|
||||||
|
const carts = (
|
||||||
|
x: number,
|
||||||
|
y: number,
|
||||||
|
angle: number,
|
||||||
|
) => `<g transform="translate(${x} ${y}) rotate(${angle})"><path d="M0 0h28" stroke="#58675b" stroke-width="2"/>
|
||||||
|
<rect x="-3" y="-3" width="8" height="6" rx="1" fill="#bc7643" stroke="#687168"/><path d="M1-2v4" stroke="#cbdfe0"/>
|
||||||
|
${[9, 18, 27].map((x) => `<rect x="${x}" y="-2.6" width="6" height="5" rx=".7" fill="#d6d4bb" stroke="#677269" stroke-width=".8"/>`).join("")}</g>`;
|
||||||
|
const hatches = Array.from(
|
||||||
|
{ length: 9 },
|
||||||
|
(_, i) => `<path d="M${383 + i * 7} 294l6-8 M${591 + i * 7} 248l6-8"/>`,
|
||||||
|
).join("");
|
||||||
|
return `<g fill="none" stroke="#f7f3d5" stroke-width="1.1">${hatches}
|
||||||
|
<path d="M374 239h33v26h-33z M662 249h22v59h-22z" stroke-dasharray="4 3"/>
|
||||||
|
<path d="M95 240h183 M95 329h183" stroke="#c9a651" stroke-width="2"/></g>
|
||||||
|
${carts(374, 317, 0)}${carts(626, 288, 90)}${carts(786, 299, -90)}
|
||||||
|
<g transform="translate(701 289)"><ellipse cx="6" cy="10" rx="10" ry="3" fill="#899980"/>
|
||||||
|
<path d="M0 9v-25" stroke="#53675b" stroke-width="2"/><path d="M0-17l18 3-2 4-16-1z" fill="#ce693d" stroke="#765f47"/><path d="M5-16v5m6-4v4" stroke="#fff3d5" stroke-width="2.5"/></g>
|
||||||
|
<g transform="translate(287 348)"><path d="M-4 13l2-22h5l3 22z" fill="#d4ddd1" stroke="#6d8278"/><path d="M-7-12h15l-2 6h-11z" fill="#76959a" stroke="#4a6360"/><path d="M-8-12l3-3h11l3 3z" fill="#c5cfc2"/></g>`;
|
||||||
|
}
|
||||||
|
function terrain(points: Record<string, Point>) {
|
||||||
|
let seed = 49075;
|
||||||
|
function rand() {
|
||||||
|
seed = (1664525 * seed + 1013904223) >>> 0;
|
||||||
|
return seed / 4294967296;
|
||||||
|
}
|
||||||
|
const trees = [
|
||||||
|
[45, 172, 34, 202],
|
||||||
|
[65, 91, 265, 22],
|
||||||
|
[69, 447, 270, 18],
|
||||||
|
[383, 96, 200, 15],
|
||||||
|
[361, 442, 214, 12],
|
||||||
|
[1012, 187, 31, 161],
|
||||||
|
]
|
||||||
|
.map(([x, y, w, h]) =>
|
||||||
|
Array.from(
|
||||||
|
{ length: Math.ceil((w * h) / 180) },
|
||||||
|
() =>
|
||||||
|
`<use href="#tree" transform="translate(${Math.round(x + rand() * w)} ${Math.round(y + rand() * h)}) scale(${(0.48 + rand() * 0.48).toFixed(2)})"/>`,
|
||||||
|
).join(""),
|
||||||
|
)
|
||||||
|
.join("");
|
||||||
|
const routes: string[] = [
|
||||||
|
"M91 129H938Q987 129 987 90V57",
|
||||||
|
"M91 419H938Q987 419 987 458V491",
|
||||||
|
"M91 129Q72 129 72 151V397Q72 419 91 419",
|
||||||
|
"M350 129V419",
|
||||||
|
"M350 176H680Q722 176 752 129",
|
||||||
|
"M350 371H680Q722 371 752 419",
|
||||||
|
"M776 129Q758 170 758 202V342Q758 374 776 419",
|
||||||
|
"M758 231H914Q955 231 955 265V283Q955 317 914 317H758",
|
||||||
|
];
|
||||||
|
for (const [id, p] of Object.entries(points)) {
|
||||||
|
if (id.startsWith("A:B"))
|
||||||
|
routes.push(`M${p.x} ${p.y}V${p.y < 274 ? 176 : 371}`);
|
||||||
|
if (id.startsWith("A:C")) routes.push(`M${p.x} 129V419`);
|
||||||
|
}
|
||||||
|
const line = routes.map((d) => `<path d="${d}"/>`).join("");
|
||||||
|
const apron =
|
||||||
|
'<path d="M89 156H302L320 177V365L298 389H89Z M364 162H670L710 196V350L676 382H364Z M778 192H926L969 221V321L935 351H778Z" fill="url(#apron)" stroke="#a2ac95" stroke-width="3"/>';
|
||||||
|
const fingers = Object.entries(points)
|
||||||
|
.filter(([k]) => k.startsWith("A:B"))
|
||||||
|
.map(([, p]) => {
|
||||||
|
const top = p.y < 274,
|
||||||
|
y = top ? 235 : 296;
|
||||||
|
return `<g><path d="M${p.x + 10} ${top ? 252 : 296}v${top ? -13 : 12}l-9 ${top ? -7 : 7}" stroke="#667e75" stroke-width="8" fill="none"/><rect x="${p.x - 5}" y="${top ? y - 8 : y + 12}" width="10" height="9" fill="#e1e4d4" stroke="#748777"/></g>`;
|
||||||
|
})
|
||||||
|
.join("");
|
||||||
|
return `<rect width="${width}" height="${height}" fill="url(#grass)"/><path d="M-30 125L370 0H615L-10 187ZM483 548L1080 342V399L671 548Z" fill="#b1b58a" opacity=".38"/>
|
||||||
|
${trees}${apron}<g fill="none" stroke-linecap="round" stroke-linejoin="round"><g stroke="#798879" stroke-width="23">${line}</g><g stroke="#a9b1a2" stroke-width="19">${line}</g><g stroke="#e4cd7e" stroke-width="1.7">${line}</g></g>
|
||||||
|
${apronEquipment()}${fingers}${building(399, 251, 259, 45)}${building(441, 244, 114, 16)}
|
||||||
|
<text x="533" y="281" class="roof-title" text-anchor="middle">ТЕРМИНАЛ</text>
|
||||||
|
${building(805, 259, 99, 36)}<text x="857" y="285" text-anchor="middle" class="roof-title">VIP</text>
|
||||||
|
${building(239, 179, 45, 27)}${building(286, 312, 28, 55)}${building(350, 254, 23, 41)}
|
||||||
|
<path d="M98 226h177m-177 114h177" stroke="#e4dfba" stroke-width="2" stroke-dasharray="4 5"/>
|
||||||
|
<text x="180" y="209" text-anchor="middle" class="ground-title">ПЕРРОН A / C</text>
|
||||||
|
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function cardBays(v: MapView) {
|
||||||
|
const items = [
|
||||||
|
["ПОГОДА", v.piles?.weather ?? "—"],
|
||||||
|
["КОЛОДА", String(v.piles?.deck ?? "—")],
|
||||||
|
["СБРОС", v.piles?.discard ?? "—"],
|
||||||
|
];
|
||||||
|
return items
|
||||||
|
.map(
|
||||||
|
(
|
||||||
|
[label, value],
|
||||||
|
i,
|
||||||
|
) => `<g transform="translate(${107 + 132 * i} 91)"><rect x="2" y="2" width="119" height="24" rx="3" fill="#4f6554"/>
|
||||||
|
<rect width="119" height="24" rx="3" fill="#d9dfc9" stroke="#657860"/>
|
||||||
|
<path d="M6 5h12v14H6zm2-2h12v14" fill="none" stroke="#6c806a"/>
|
||||||
|
<text x="24" y="16" class="bay-name">${label}</text><text x="111" y="16" text-anchor="end" class="bay-value">${value}</text></g>`,
|
||||||
|
)
|
||||||
|
.join("");
|
||||||
|
}
|
||||||
|
export function airfield(v: MapView) {
|
||||||
|
const pts = geometry(v.geometry);
|
||||||
|
const markers = Object.entries(pts)
|
||||||
|
.map(([id, p]) => {
|
||||||
|
const m = v.markers[id],
|
||||||
|
dest = v.destinations.has(id),
|
||||||
|
canPick = m && v.pickable.has(m.key);
|
||||||
|
const picked = !!m && m.key === v.selected;
|
||||||
|
const title = m ? m.name + " · " + p.label : p.label + " · " + id;
|
||||||
|
const action = canPick ? "pick" : dest ? "mapdest" : "";
|
||||||
|
const attr = action
|
||||||
|
? `role="button" tabindex="0" data-act="${action}" data-val="${canPick ? m.key : id}"`
|
||||||
|
: "";
|
||||||
|
const label = p.label === "D" ? "СТАРТ" : p.label;
|
||||||
|
return `<g transform="translate(${p.x} ${p.y})" data-position="${id}" class="map-slot ${dest ? "legal" : ""} ${picked ? "picked" : ""}" ${attr} aria-label="${title}"><title>${title}</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="${m ? 18 : 14}" fill="${id.startsWith("D") ? "#f1d977" : "#e7e8d6"}" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
${dest || picked ? '<circle class="focus-ring" r="21" fill="none" stroke="' + (picked ? "#fff" : "#075842") + '" stroke-width="3" stroke-dasharray="5 3"/>' : ""}
|
||||||
|
${
|
||||||
|
m
|
||||||
|
? `<use href="#jet${m.size}" transform="rotate(${p.angle})" fill="${m.color}" stroke="#26382e" stroke-linejoin="round" stroke-width="1.2"/>
|
||||||
|
<rect x="-20" y="18" width="40" height="15" rx="4" fill="#233d33"/><text y="29" class="jet-id">${m.caption}</text>`
|
||||||
|
: `<text y="4" class="spot-label">${label}</text>`
|
||||||
|
}</g>`;
|
||||||
|
})
|
||||||
|
.join("");
|
||||||
|
return `<svg class="airfield" viewBox="0 0 ${width} ${height}" xmlns="http://www.w3.org/2000/svg" role="group" aria-label="Аэродром, полосы 31R и 31L, терминал и стоянки">${fieldDefs}${terrain(pts)}${v.geometry.runways.map((l) => runway(l, v.weather)).join("")}${markers}${cardBays(v)}</svg>`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
<svg class="airfield" viewBox="0 0 1080 548" xmlns="http://www.w3.org/2000/svg" role="group" aria-label="Аэродром, полосы 31R и 31L, терминал и стоянки"><defs><style>.airfield text {
|
||||||
|
font-family: Consolas, "Liberation Mono", monospace;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
.rw-number {
|
||||||
|
font-size: 26px;
|
||||||
|
font-weight: bold;
|
||||||
|
fill: #f3f2e5;
|
||||||
|
letter-spacing: 1px;
|
||||||
|
}
|
||||||
|
.ground-title {
|
||||||
|
font-size: 10px;
|
||||||
|
letter-spacing: 2px;
|
||||||
|
font-weight: bold;
|
||||||
|
fill: #3e5744;
|
||||||
|
}
|
||||||
|
.roof-title {
|
||||||
|
font-size: 12px;
|
||||||
|
letter-spacing: 2px;
|
||||||
|
font-weight: bold;
|
||||||
|
fill: #3b514b;
|
||||||
|
}
|
||||||
|
.spot-label,
|
||||||
|
.jet-id {
|
||||||
|
font-weight: 700;
|
||||||
|
text-anchor: middle;
|
||||||
|
fill: #2a372d;
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
.jet-id {
|
||||||
|
fill: white;
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
.bay-name {
|
||||||
|
font-size: 11px;
|
||||||
|
letter-spacing: 0.6px;
|
||||||
|
fill: #405744;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
.bay-value {
|
||||||
|
font-size: 12px;
|
||||||
|
fill: #193e31;
|
||||||
|
font-weight: bold;
|
||||||
|
}</style>
|
||||||
|
<pattern id="grass" width="21" height="17" patternUnits="userSpaceOnUse"><rect width="21" height="17" fill="#9aa780"/><path d="M2 3h4m8 7h3m-8 4h3" stroke="#718765" stroke-width=".9" opacity=".38"/></pattern>
|
||||||
|
<pattern id="roof" width="8" height="8" patternUnits="userSpaceOnUse"><rect width="8" height="8" fill="#c5d3cb"/><path d="M1 0v8" stroke="#a3b8ad"/></pattern>
|
||||||
|
<pattern id="asphalt" width="23" height="16" patternUnits="userSpaceOnUse"><rect width="23" height="16" fill="#515e60"/><path d="M0 0h23m-17 0v16" stroke="#657073" stroke-width=".7"/></pattern>
|
||||||
|
<pattern id="apron" width="30" height="28" patternUnits="userSpaceOnUse"><rect width="30" height="28" fill="#bdc4ae"/><path d="M0 28V0h30" fill="none" stroke="#9ca896" stroke-width="1.4"/></pattern>
|
||||||
|
<g id="tree"><path d="M-6 4l1-8 4-5 6 2 4 6-3 7-7 1z" fill="#546f54"/><path d="M-6 1l1-7 5-4 5 3 1 6-5 5z" fill="#71885e"/><path d="M-4-4l4-4 3 3" fill="#889967"/></g>
|
||||||
|
<g id="vent"><rect width="12" height="9" rx="1" fill="#82988d"/><circle cx="6" cy="4.5" r="3" fill="#a5b5a9" stroke="#506a62"/><path d="M3 4.5h6m-3-3v6" stroke="#657d72"/></g>
|
||||||
|
<g id="jet1"><path d="M0-15Q3-13 2-2L14 1v3L2 3l-1 8 5 3v2l-6-2-6 2v-2l5-3-1-8-12 1V1l12-3Q-3-13 0-15Z"/></g>
|
||||||
|
<g id="jet2"><path d="M0-19Q3-18 3-6L19 4v4L3 3l-1 10 6 4v2l-8-3-8 3v-2l6-4-1-10-16 5V4L-3-6Q-3-18 0-19Z"/><path d="M-9-2v7m18-7v7" stroke-width="3"/></g>
|
||||||
|
<g id="jet3"><path d="M0-22Q4-20 3.8-7L23 4v5L4 4l-2 11 8 5v3l-10-4-10 4v-3l8-5-2-11-19 5V4L-3.8-7Q-4-20 0-22Z"/><path d="M-15 0v7m7-10v8m16-8v8m7-5v7" stroke-width="3.6"/></g>
|
||||||
|
</defs><rect width="1080" height="548" fill="url(#grass)"/><path d="M-30 125L370 0H615L-10 187ZM483 548L1080 342V399L671 548Z" fill="#b1b58a" opacity=".38"/>
|
||||||
|
<use href="#tree" transform="translate(54 286) scale(0.90)"/><use href="#tree" transform="translate(53 216) scale(0.74)"/><use href="#tree" transform="translate(62 343) scale(0.82)"/><use href="#tree" transform="translate(74 249) scale(0.91)"/><use href="#tree" transform="translate(48 240) scale(0.55)"/><use href="#tree" transform="translate(50 324) scale(0.61)"/><use href="#tree" transform="translate(59 255) scale(0.78)"/><use href="#tree" transform="translate(57 186) scale(0.67)"/><use href="#tree" transform="translate(55 201) scale(0.94)"/><use href="#tree" transform="translate(73 372) scale(0.83)"/><use href="#tree" transform="translate(79 303) scale(0.93)"/><use href="#tree" transform="translate(48 196) scale(0.74)"/><use href="#tree" transform="translate(78 352) scale(0.60)"/><use href="#tree" transform="translate(76 320) scale(0.77)"/><use href="#tree" transform="translate(52 258) scale(0.50)"/><use href="#tree" transform="translate(59 242) scale(0.71)"/><use href="#tree" transform="translate(48 243) scale(0.60)"/><use href="#tree" transform="translate(49 216) scale(0.62)"/><use href="#tree" transform="translate(75 289) scale(0.57)"/><use href="#tree" transform="translate(47 330) scale(0.61)"/><use href="#tree" transform="translate(70 324) scale(0.80)"/><use href="#tree" transform="translate(73 238) scale(0.87)"/><use href="#tree" transform="translate(77 339) scale(0.77)"/><use href="#tree" transform="translate(69 242) scale(0.91)"/><use href="#tree" transform="translate(48 186) scale(0.90)"/><use href="#tree" transform="translate(64 337) scale(0.85)"/><use href="#tree" transform="translate(50 211) scale(0.61)"/><use href="#tree" transform="translate(51 273) scale(0.71)"/><use href="#tree" transform="translate(64 322) scale(0.49)"/><use href="#tree" transform="translate(67 323) scale(0.69)"/><use href="#tree" transform="translate(63 236) scale(0.51)"/><use href="#tree" transform="translate(72 195) scale(0.71)"/><use href="#tree" transform="translate(78 317) scale(0.87)"/><use href="#tree" transform="translate(52 263) scale(0.51)"/><use href="#tree" transform="translate(61 188) scale(0.65)"/><use href="#tree" transform="translate(71 372) scale(0.62)"/><use href="#tree" transform="translate(51 371) scale(0.59)"/><use href="#tree" transform="translate(79 299) scale(0.86)"/><use href="#tree" transform="translate(63 262) scale(0.70)"/><use href="#tree" transform="translate(324 109) scale(0.90)"/><use href="#tree" transform="translate(246 92) scale(0.95)"/><use href="#tree" transform="translate(92 101) scale(0.91)"/><use href="#tree" transform="translate(285 103) scale(0.73)"/><use href="#tree" transform="translate(181 103) scale(0.50)"/><use href="#tree" transform="translate(152 112) scale(0.94)"/><use href="#tree" transform="translate(129 111) scale(0.59)"/><use href="#tree" transform="translate(66 98) scale(0.88)"/><use href="#tree" transform="translate(85 98) scale(0.76)"/><use href="#tree" transform="translate(258 111) scale(0.51)"/><use href="#tree" transform="translate(134 96) scale(0.56)"/><use href="#tree" transform="translate(77 91) scale(0.68)"/><use href="#tree" transform="translate(275 107) scale(0.71)"/><use href="#tree" transform="translate(179 103) scale(0.65)"/><use href="#tree" transform="translate(82 112) scale(0.59)"/><use href="#tree" transform="translate(124 111) scale(0.72)"/><use href="#tree" transform="translate(112 105) scale(0.80)"/><use href="#tree" transform="translate(255 96) scale(0.57)"/><use href="#tree" transform="translate(107 103) scale(0.69)"/><use href="#tree" transform="translate(131 107) scale(0.64)"/><use href="#tree" transform="translate(285 94) scale(0.69)"/><use href="#tree" transform="translate(216 99) scale(0.55)"/><use href="#tree" transform="translate(173 93) scale(0.85)"/><use href="#tree" transform="translate(123 93) scale(0.64)"/><use href="#tree" transform="translate(209 97) scale(0.95)"/><use href="#tree" transform="translate(150 91) scale(0.65)"/><use href="#tree" transform="translate(272 106) scale(0.74)"/><use href="#tree" transform="translate(67 95) scale(0.74)"/><use href="#tree" transform="translate(246 106) scale(0.52)"/><use href="#tree" transform="translate(291 110) scale(0.93)"/><use href="#tree" transform="translate(98 100) scale(0.75)"/><use href="#tree" transform="translate(99 107) scale(0.82)"/><use href="#tree" transform="translate(201 93) scale(0.89)"/><use href="#tree" transform="translate(209 449) scale(0.83)"/><use href="#tree" transform="translate(147 458) scale(0.55)"/><use href="#tree" transform="translate(159 453) scale(0.95)"/><use href="#tree" transform="translate(153 460) scale(0.84)"/><use href="#tree" transform="translate(79 459) scale(0.51)"/><use href="#tree" transform="translate(102 461) scale(0.75)"/><use href="#tree" transform="translate(158 449) scale(0.69)"/><use href="#tree" transform="translate(206 454) scale(0.77)"/><use href="#tree" transform="translate(99 460) scale(0.83)"/><use href="#tree" transform="translate(Line truncated
|
||||||
|
<g fill="none" stroke="#f7f3d5" stroke-width="1.1"><path d="M383 294l6-8 M591 248l6-8"/><path d="M390 294l6-8 M598 248l6-8"/><path d="M397 294l6-8 M605 248l6-8"/><path d="M404 294l6-8 M612 248l6-8"/><path d="M411 294l6-8 M619 248l6-8"/><path d="M418 294l6-8 M626 248l6-8"/><path d="M425 294l6-8 M633 248l6-8"/><path d="M432 294l6-8 M640 248l6-8"/><path d="M439 294l6-8 M647 248l6-8"/>
|
||||||
|
<path d="M374 239h33v26h-33z M662 249h22v59h-22z" stroke-dasharray="4 3"/>
|
||||||
|
<path d="M95 240h183 M95 329h183" stroke="#c9a651" stroke-width="2"/></g>
|
||||||
|
<g transform="translate(374 317) rotate(0)"><path d="M0 0h28" stroke="#58675b" stroke-width="2"/>
|
||||||
|
<rect x="-3" y="-3" width="8" height="6" rx="1" fill="#bc7643" stroke="#687168"/><path d="M1-2v4" stroke="#cbdfe0"/>
|
||||||
|
<rect x="9" y="-2.6" width="6" height="5" rx=".7" fill="#d6d4bb" stroke="#677269" stroke-width=".8"/><rect x="18" y="-2.6" width="6" height="5" rx=".7" fill="#d6d4bb" stroke="#677269" stroke-width=".8"/><rect x="27" y="-2.6" width="6" height="5" rx=".7" fill="#d6d4bb" stroke="#677269" stroke-width=".8"/></g><g transform="translate(626 288) rotate(90)"><path d="M0 0h28" stroke="#58675b" stroke-width="2"/>
|
||||||
|
<rect x="-3" y="-3" width="8" height="6" rx="1" fill="#bc7643" stroke="#687168"/><path d="M1-2v4" stroke="#cbdfe0"/>
|
||||||
|
<rect x="9" y="-2.6" width="6" height="5" rx=".7" fill="#d6d4bb" stroke="#677269" stroke-width=".8"/><rect x="18" y="-2.6" width="6" height="5" rx=".7" fill="#d6d4bb" stroke="#677269" stroke-width=".8"/><rect x="27" y="-2.6" width="6" height="5" rx=".7" fill="#d6d4bb" stroke="#677269" stroke-width=".8"/></g><g transform="translate(786 299) rotate(-90)"><path d="M0 0h28" stroke="#58675b" stroke-width="2"/>
|
||||||
|
<rect x="-3" y="-3" width="8" height="6" rx="1" fill="#bc7643" stroke="#687168"/><path d="M1-2v4" stroke="#cbdfe0"/>
|
||||||
|
<rect x="9" y="-2.6" width="6" height="5" rx=".7" fill="#d6d4bb" stroke="#677269" stroke-width=".8"/><rect x="18" y="-2.6" width="6" height="5" rx=".7" fill="#d6d4bb" stroke="#677269" stroke-width=".8"/><rect x="27" y="-2.6" width="6" height="5" rx=".7" fill="#d6d4bb" stroke="#677269" stroke-width=".8"/></g>
|
||||||
|
<g transform="translate(701 289)"><ellipse cx="6" cy="10" rx="10" ry="3" fill="#899980"/>
|
||||||
|
<path d="M0 9v-25" stroke="#53675b" stroke-width="2"/><path d="M0-17l18 3-2 4-16-1z" fill="#ce693d" stroke="#765f47"/><path d="M5-16v5m6-4v4" stroke="#fff3d5" stroke-width="2.5"/></g>
|
||||||
|
<g transform="translate(287 348)"><path d="M-4 13l2-22h5l3 22z" fill="#d4ddd1" stroke="#6d8278"/><path d="M-7-12h15l-2 6h-11z" fill="#76959a" stroke="#4a6360"/><path d="M-8-12l3-3h11l3 3z" fill="#c5cfc2"/></g><g><path d="M450 252v-13l-9 -7" stroke="#667e75" stroke-width="8" fill="none"/><rect x="435" y="227" width="10" height="9" fill="#e1e4d4" stroke="#748777"/></g><g><path d="M530 252v-13l-9 -7" stroke="#667e75" stroke-width="8" fill="none"/><rect x="515" y="227" width="10" height="9" fill="#e1e4d4" stroke="#748777"/></g><g><path d="M610 252v-13l-9 -7" stroke="#667e75" stroke-width="8" fill="none"/><rect x="595" y="227" width="10" height="9" fill="#e1e4d4" stroke="#748777"/></g><g><path d="M450 296v12l-9 7" stroke="#667e75" stroke-width="8" fill="none"/><rect x="435" y="308" width="10" height="9" fill="#e1e4d4" stroke="#748777"/></g><g><path d="M530 296v12l-9 7" stroke="#667e75" stroke-width="8" fill="none"/><rect x="515" y="308" width="10" height="9" fill="#e1e4d4" stroke="#748777"/></g><g><path d="M610 296v12l-9 7" stroke="#667e75" stroke-width="8" fill="none"/><rect x="595" y="308" width="10" height="9" fill="#e1e4d4" stroke="#748777"/></g><g><rect x="403" y="256" width="259" height="45" rx="3" fill="#54685c" opacity=".5"/>
|
||||||
|
<rect x="399" y="251" width="259" height="45" rx="3" fill="url(#roof)" stroke="#667d72" stroke-width="2"/>
|
||||||
|
<path d="M403 293h251" stroke="#73979a" stroke-width="4" stroke-dasharray="8 3"/><use href="#vent" x="407" y="256"/><use href="#vent" x="442" y="256"/><use href="#vent" x="477" y="256"/><use href="#vent" x="512" y="256"/><use href="#vent" x="547" y="256"/></g><g><rect x="445" y="249" width="114" height="16" rx="3" fill="#54685c" opacity=".5"/>
|
||||||
|
<rect x="441" y="244" width="114" height="16" rx="3" fill="url(#roof)" stroke="#667d72" stroke-width="2"/>
|
||||||
|
<path d="M445 257h106" stroke="#73979a" stroke-width="4" stroke-dasharray="8 3"/><use href="#vent" x="449" y="249"/><use href="#vent" x="484" y="249"/></g>
|
||||||
|
<text x="533" y="281" class="roof-title" text-anchor="middle">ТЕРМИНАЛ</text>
|
||||||
|
<g><rect x="809" y="264" width="99" height="36" rx="3" fill="#54685c" opacity=".5"/>
|
||||||
|
<rect x="805" y="259" width="99" height="36" rx="3" fill="url(#roof)" stroke="#667d72" stroke-width="2"/>
|
||||||
|
<path d="M809 292h91" stroke="#73979a" stroke-width="4" stroke-dasharray="8 3"/><use href="#vent" x="813" y="264"/><use href="#vent" x="848" y="264"/></g><text x="857" y="285" text-anchor="middle" class="roof-title">VIP</text>
|
||||||
|
<g><rect x="243" y="184" width="45" height="27" rx="3" fill="#54685c" opacity=".5"/>
|
||||||
|
<rect x="239" y="179" width="45" height="27" rx="3" fill="url(#roof)" stroke="#667d72" stroke-width="2"/>
|
||||||
|
<path d="M243 203h37" stroke="#73979a" stroke-width="4" stroke-dasharray="8 3"/><use href="#vent" x="247" y="184"/></g><g><rect x="290" y="317" width="28" height="55" rx="3" fill="#54685c" opacity=".5"/>
|
||||||
|
<rect x="286" y="312" width="28" height="55" rx="3" fill="url(#roof)" stroke="#667d72" stroke-width="2"/>
|
||||||
|
<path d="M290 364h20" stroke="#73979a" stroke-width="4" stroke-dasharray="8 3"/><use href="#vent" x="294" y="317"/></g><g><rect x="354" y="259" width="23" height="41" rx="3" fill="#54685c" opacity=".5"/>
|
||||||
|
<rect x="350" y="254" width="23" height="41" rx="3" fill="url(#roof)" stroke="#667d72" stroke-width="2"/>
|
||||||
|
<path d="M354 292h15" stroke="#73979a" stroke-width="4" stroke-dasharray="8 3"/><use href="#vent" x="358" y="259"/></g>
|
||||||
|
<path d="M98 226h177m-177 114h177" stroke="#e4dfba" stroke-width="2" stroke-dasharray="4 5"/>
|
||||||
|
<text x="180" y="209" text-anchor="middle" class="ground-title">ПЕРРОН A / C</text>
|
||||||
|
|
||||||
|
<g><rect x="28" y="466" width="1024" height="50" rx="5" fill="#687773" stroke="#92a492" stroke-width="5"/>
|
||||||
|
<rect x="34" y="472" width="1012" height="38" fill="url(#asphalt)" stroke="#c5cdc0" stroke-width="1.4"/>
|
||||||
|
<g stroke="#ecebdd" stroke-width="2.6"><path d="M54 478h31 M1026 478h-30"/><path d="M54 483h31 M1026 483h-30"/><path d="M54 488h31 M1026 488h-30"/><path d="M54 493h31 M1026 493h-30"/><path d="M54 498h31 M1026 498h-30"/><path d="M54 503h31 M1026 503h-30"/><path d="M171 491H920" stroke-dasharray="20 16"/></g>
|
||||||
|
<path d="M225 481h35 m0 20h-35 M785 481h35 m0 20h-35" stroke="#d1d7cb" stroke-width="4"/>
|
||||||
|
<g stroke="#e5dfad" stroke-width="3"><path d="M44 469v2 m0 40v2"/><path d="M87 469v2 m0 40v2"/><path d="M130 469v2 m0 40v2"/><path d="M173 469v2 m0 40v2"/><path d="M216 469v2 m0 40v2"/><path d="M259 469v2 m0 40v2"/><path d="M302 469v2 m0 40v2"/><path d="M345 469v2 m0 40v2"/><path d="M388 469v2 m0 40v2"/><path d="M431 469v2 m0 40v2"/><path d="M474 469v2 m0 40v2"/><path d="M517 469v2 m0 40v2"/><path d="M560 469v2 m0 40v2"/><path d="M603 469v2 m0 40v2"/><path d="M646 469v2 m0 40v2"/><path d="M689 469v2 m0 40v2"/><path d="M732 469v2 m0 40v2"/><path d="M775 469v2 m0 40v2"/><path d="M818 469v2 m0 40v2"/><path d="M861 469v2 m0 40v2"/><path d="M904 469v2 m0 40v2"/><path d="M947 469v2 m0 40v2"/><path d="M990 469v2 m0 40v2"/><path d="M1033 469v2 m0 40v2"/></g>
|
||||||
|
<text x="106" y="499" class="rw-number">31L</text>
|
||||||
|
</g><g><rect x="28" y="32" width="1024" height="50" rx="5" fill="#687773" stroke="#92a492" stroke-width="5"/>
|
||||||
|
<rect x="34" y="38" width="1012" height="38" fill="url(#asphalt)" stroke="#c5cdc0" stroke-width="1.4"/>
|
||||||
|
<g stroke="#ecebdd" stroke-width="2.6"><path d="M54 44h31 M1026 44h-30"/><path d="M54 49h31 M1026 49h-30"/><path d="M54 54h31 M1026 54h-30"/><path d="M54 59h31 M1026 59h-30"/><path d="M54 64h31 M1026 64h-30"/><path d="M54 69h31 M1026 69h-30"/><path d="M171 57H920" stroke-dasharray="20 16"/></g>
|
||||||
|
<path d="M225 47h35 m0 20h-35 M785 47h35 m0 20h-35" stroke="#d1d7cb" stroke-width="4"/>
|
||||||
|
<g stroke="#e5dfad" stroke-width="3"><path d="M44 35v2 m0 40v2"/><path d="M87 35v2 m0 40v2"/><path d="M130 35v2 m0 40v2"/><path d="M173 35v2 m0 40v2"/><path d="M216 35v2 m0 40v2"/><path d="M259 35v2 m0 40v2"/><path d="M302 35v2 m0 40v2"/><path d="M345 35v2 m0 40v2"/><path d="M388 35v2 m0 40v2"/><path d="M431 35v2 m0 40v2"/><path d="M474 35v2 m0 40v2"/><path d="M517 35v2 m0 40v2"/><path d="M560 35v2 m0 40v2"/><path d="M603 35v2 m0 40v2"/><path d="M646 35v2 m0 40v2"/><path d="M689 35v2 m0 40v2"/><path d="M732 35v2 m0 40v2"/><path d="M775 35v2 m0 40v2"/><path d="M818 35v2 m0 40v2"/><path d="M861 35v2 m0 40v2"/><path d="M904 35v2 m0 40v2"/><path d="M947 35v2 m0 40v2"/><path d="M990 35v2 m0 40v2"/><path d="M1033 35v2 m0 40v2"/></g>
|
||||||
|
<text x="106" y="65" class="rw-number">31R</text>
|
||||||
|
</g><g transform="translate(987 491)" data-position="D:31L:0" class="map-slot " aria-label="D · D:31L:0"><title>D · D:31L:0</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#f1d977" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">СТАРТ</text></g><g transform="translate(949 419)" data-position="D:31L:1" class="map-slot " aria-label="D1 · D:31L:1"><title>D1 · D:31L:1</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#f1d977" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">D1</text></g><g transform="translate(879.25 419)" data-position="D:31L:2" class="map-slot " aria-label="D2 · D:31L:2"><title>D2 · D:31L:2</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#f1d977" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">D2</text></g><g transform="translate(809.5 419)" data-position="D:31L:3" class="map-slot " aria-label="D3 · D:31L:3"><title>D3 · D:31L:3</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#f1d977" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">D3</text></g><g transform="translate(739.75 419)" data-position="D:31L:4" class="map-slot " aria-label="D4 · D:31L:4"><title>D4 · D:31L:4</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#f1d977" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">D4</text></g><g transform="translate(670 419)" data-position="D:31L:5" class="map-slot " aria-label="D5 · D:31L:5"><title>D5 · D:31L:5</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#f1d977" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">D5</text></g><g transform="translate(987 57)" data-position="D:31R:0" class="map-slot " aria-label="D · D:31R:0"><title>D · D:31R:0</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#f1d977" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">СТАРТ</text></g><g transform="translate(949 129)" data-position="D:31R:1" class="map-slot " aria-label="D1 · D:31R:1"><title>D1 · D:31R:1</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#f1d977" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">D1</text></g><g transform="translate(879.25 129)" data-position="D:31R:2" class="map-slot " aria-label="D2 · D:31R:2"><title>D2 · D:31R:2</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#f1d977" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">D2</text></g><g transform="translate(809.5 129)" data-position="D:31R:3" class="map-slot " aria-label="D3 · D:31R:3"><title>D3 · D:31R:3</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#f1d977" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">D3</text></g><g transform="translate(739.75 129)" data-position="D:31R:4" class="map-slot " aria-label="D4 · D:31R:4"><title>D4 · D:31R:4</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#f1d977" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">D4</text></g><g transform="translate(670 129)" data-position="D:31R:5" class="map-slot " aria-label="D5 · D:31R:5"><title>D5 · D:31R:5</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#f1d977" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">D5</text></g><g transform="translate(440 215)" data-position="A:B1" class="map-slot " aria-label="A1 · A:B1"><title>A1 · A:B1</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#e7e8d6" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">A1</text></g><g transform="translate(520 215)" data-position="A:B2" class="map-slot " aria-label="A2 · A:B2"><title>A2 · A:B2</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#e7e8d6" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">A2</text></g><g transform="translate(600 215)" data-position="A:B3" class="map-slot " aria-label="A3 · A:B3"><title>A3 · A:B3</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#e7e8d6" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">A3</text></g><g transform="translate(440 332)" data-position="A:B4" class="map-slot " aria-label="A4 · A:B4"><title>A4 · A:B4</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#e7e8d6" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">A4</text></g><g transform="translate(520 332)" data-position="A:B5" class="map-slot " aria-label="A5 · A:B5"><title>A5 · A:B5</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#e7e8d6" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">A5</text></g><g transform="translate(600 332)" data-position="A:B6" class="map-slot " aria-label="A6 · A:B6"><title>A6 · A:B6</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#e7e8d6" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">A6</text></g><g transform="translate(410 176)" data-position="B:B1" class="map-slot " aria-label="B1 · B:B1"><title>B1 · B:B1</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#e7e8d6" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">B1</text></g><g transform="translate(524 371)" data-position="B:B2" class="map-slot " aria-label="B2 · B:B2"><title>B2 · B:B2</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#e7e8d6" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">B2</text></g><g transform="translate(638 176)" data-position="B:B3" class="map-slot " aria-label="B3 · B:B3"><title>B3 · B:B3</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#e7e8d6" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">B3</text></g><g transform="translate(116 260)" data-position="A:C1" class="map-slot " aria-label="A1 · A:C1"><title>A1 · A:C1</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#e7e8d6" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">A1</text></g><g transform="translate(116 311)" data-position="C:C1" class="map-slot " aria-label="C1 · C:C1"><title>C1 · C:C1</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#e7e8d6" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">C1</text></g><g transform="translate(187 260)" data-position="A:C2" class="map-slot " aria-label="A2 · A:C2"><title>A2 · A:C2</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#e7e8d6" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">A2</text></g><g transform="translate(187 311)" data-position="C:C2" class="map-slot " aria-label="C2 · C:C2"><title>C2 · C:C2</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#e7e8d6" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">C2</text></g><g transform="translate(258 260)" data-position="A:C3" class="map-slot " aria-label="A3 · A:C3"><title>A3 · A:C3</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#e7e8d6" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">A3</text></g><g transform="translate(258 311)" data-position="C:C3" class="map-slot " aria-label="C3 · C:C3"><title>C3 · C:C3</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#e7e8d6" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">C3</text></g><g transform="translate(834 317)" data-position="V1:31L" class="map-slot " aria-label="VIP1 · V1:31L"><title>VIP1 · V1:31L</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#e7e8d6" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">VIP1</text></g><g transform="translate(914 317)" data-position="V2:31L" class="map-slot " aria-label="VIP2 · V2:31L"><title>VIP2 · V2:31L</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#e7e8d6" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">VIP2</text></g><g transform="translate(834 231)" data-position="V1:31R" class="map-slot " aria-label="VIP1 · V1:31R"><title>VIP1 · V1:31R</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#e7e8d6" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">VIP1</text></g><g transform="translate(914 231)" data-position="V2:31R" class="map-slot " aria-label="VIP2 · V2:31R"><title>VIP2 · V2:31R</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="14" fill="#e7e8d6" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
|
||||||
|
<text y="4" class="spot-label">VIP2</text></g><g transform="translate(107 91)"><rect x="2" y="2" width="119" height="24" rx="3" fill="#4f6554"/>
|
||||||
|
<rect width="119" height="24" rx="3" fill="#d9dfc9" stroke="#657860"/>
|
||||||
|
<path d="M6 5h12v14H6zm2-2h12v14" fill="none" stroke="#6c806a"/>
|
||||||
|
<text x="24" y="16" class="bay-name">ПОГОДА</text><text x="111" y="16" text-anchor="end" class="bay-value">—</text></g><g transform="translate(239 91)"><rect x="2" y="2" width="119" height="24" rx="3" fill="#4f6554"/>
|
||||||
|
<rect width="119" height="24" rx="3" fill="#d9dfc9" stroke="#657860"/>
|
||||||
|
<path d="M6 5h12v14H6zm2-2h12v14" fill="none" stroke="#6c806a"/>
|
||||||
|
<text x="24" y="16" class="bay-name">КОЛОДА</text><text x="111" y="16" text-anchor="end" class="bay-value">—</text></g><g transform="translate(371 91)"><rect x="2" y="2" width="119" height="24" rx="3" fill="#4f6554"/>
|
||||||
|
<rect width="119" height="24" rx="3" fill="#d9dfc9" stroke="#657860"/>
|
||||||
|
<path d="M6 5h12v14H6zm2-2h12v14" fill="none" stroke="#6c806a"/>
|
||||||
|
<text x="24" y="16" class="bay-name">СБРОС</text><text x="111" y="16" text-anchor="end" class="bay-value">—</text></g></svg>
|
||||||
|
After Width: | Height: | Size: 34 KiB |
@@ -0,0 +1,193 @@
|
|||||||
|
/** Display metadata only. The engine remains authoritative for costs and targets. */
|
||||||
|
type Family = "movement" | "weather" | "incident" | "special";
|
||||||
|
type Face = [string, string, Family, string];
|
||||||
|
const faces: Record<string, Face> = {
|
||||||
|
A: [
|
||||||
|
"Подготовка к вылету",
|
||||||
|
"Boarding",
|
||||||
|
"movement",
|
||||||
|
"Выведите борт из ангара на свободную стоянку A.",
|
||||||
|
],
|
||||||
|
B: [
|
||||||
|
"Буксировка и запуск",
|
||||||
|
"Push and Start",
|
||||||
|
"movement",
|
||||||
|
"Переведите борт с обычной стоянки A на свободную позицию B.",
|
||||||
|
],
|
||||||
|
C: [
|
||||||
|
"Запуск двигателей",
|
||||||
|
"Start Up",
|
||||||
|
"movement",
|
||||||
|
"На стоянке A/C переведите борт с позиции A на C.",
|
||||||
|
],
|
||||||
|
D: [
|
||||||
|
"Отправление на полосу",
|
||||||
|
"Departure",
|
||||||
|
"movement",
|
||||||
|
"Переведите борт с B или C в очередь выбранной ВПП.",
|
||||||
|
],
|
||||||
|
LC: [
|
||||||
|
"Счастливый капитан",
|
||||||
|
"Lucky Captain",
|
||||||
|
"special",
|
||||||
|
"Заменяет одну карту A, B, C или D при оплате движения.",
|
||||||
|
],
|
||||||
|
VIP: [
|
||||||
|
"Обслуживание VIP",
|
||||||
|
"VIP",
|
||||||
|
"special",
|
||||||
|
"Направьте один борт из ангара или с A, B, C на свободную ветку VIP.",
|
||||||
|
],
|
||||||
|
AI: [
|
||||||
|
"Противообледенительная обработка",
|
||||||
|
"Anti-Icing",
|
||||||
|
"special",
|
||||||
|
"При обледенении обработайте борт на старте. Нужно 1–3 карты по размеру.",
|
||||||
|
],
|
||||||
|
FLR: [
|
||||||
|
"Техническая неисправность",
|
||||||
|
"Failure",
|
||||||
|
"incident",
|
||||||
|
"Верните борт соперника с поля в ангар. При открытом доборе действует на свой борт.",
|
||||||
|
],
|
||||||
|
DLY: [
|
||||||
|
"Задержка рейса",
|
||||||
|
"Delay",
|
||||||
|
"incident",
|
||||||
|
"Возврат с A, B, C или VIP в ангар. При розыгрыше цель чужая, при обмене — своя.",
|
||||||
|
],
|
||||||
|
SC: [
|
||||||
|
"Чистое небо",
|
||||||
|
"Sky Clear",
|
||||||
|
"weather",
|
||||||
|
"Вылет разрешён всем типам самолётов с обеих полос.",
|
||||||
|
],
|
||||||
|
FG: [
|
||||||
|
"Туман",
|
||||||
|
"Fog",
|
||||||
|
"weather",
|
||||||
|
"Вылеты и продвижение очередей на обеих полосах приостановлены.",
|
||||||
|
],
|
||||||
|
SN: [
|
||||||
|
"Снег",
|
||||||
|
"Snow",
|
||||||
|
"weather",
|
||||||
|
"Движение стоит на карту больше. Широкофюзеляжные борта не взлетают.",
|
||||||
|
],
|
||||||
|
CW: [
|
||||||
|
"Боковой ветер",
|
||||||
|
"Crosswind",
|
||||||
|
"weather",
|
||||||
|
"Малым самолётам вылет запрещён. При очереди борт уступает старт.",
|
||||||
|
],
|
||||||
|
ICE: [
|
||||||
|
"Обледенение",
|
||||||
|
"Ice",
|
||||||
|
"weather",
|
||||||
|
"Для вылета требуется противообледенительная обработка.",
|
||||||
|
],
|
||||||
|
"31L": [
|
||||||
|
"Левая полоса закрыта",
|
||||||
|
"31L Closed",
|
||||||
|
"weather",
|
||||||
|
"Вылет и продвижение очереди на ВПП 31L приостановлены.",
|
||||||
|
],
|
||||||
|
"31R": [
|
||||||
|
"Правая полоса закрыта",
|
||||||
|
"31R Closed",
|
||||||
|
"weather",
|
||||||
|
"Вылет и продвижение очереди на ВПП 31R приостановлены.",
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const families = {
|
||||||
|
movement: "Движение",
|
||||||
|
weather: "Погода",
|
||||||
|
incident: "Неприятность",
|
||||||
|
special: "Специальная",
|
||||||
|
};
|
||||||
|
const line = (d: string) => '<path d="' + d + '"/>';
|
||||||
|
const cloud =
|
||||||
|
'<path d="M28 31h32a7 7 0 0 0 0-14 12 12 0 0 0-22-2 8 8 0 1 0-10 16Z"/>';
|
||||||
|
const snowflake = line(
|
||||||
|
"M44 7v33m-14-25 28 17m0-17L30 32m10-22 4 4 4-4m0 27-4-4-4 4m-9-17 6-1-1-6m20 15-6 1 1 6m-20-7 6 1-1 6m20-15-6-1 1-6",
|
||||||
|
);
|
||||||
|
const nose = line(
|
||||||
|
"M20 28l31-5 16-9q7-2 3 4L57 31l-32 3-10-8 5-2z M43 24l-6-11 5-2 12 12",
|
||||||
|
);
|
||||||
|
const icons: Record<string, string> = {
|
||||||
|
A:
|
||||||
|
line(
|
||||||
|
"M13 36h21l20-22h12v-5H51L29 31H13z M31 29h7m-2-7h8m-3-6h8 M19 32v-6",
|
||||||
|
) + '<circle cx="24" cy="39" r="3"/><circle cx="48" cy="34" r="3"/>',
|
||||||
|
B:
|
||||||
|
line("M15 31v-9h10l4-8h12l4 11h9v7H15zm13-8h12l-3-6h-6z M55 28h11l8-11") +
|
||||||
|
'<circle cx="23" cy="33" r="4"/><circle cx="45" cy="33" r="4"/>',
|
||||||
|
C:
|
||||||
|
'<circle cx="44" cy="24" r="17"/><circle cx="44" cy="24" r="4"/>' +
|
||||||
|
Array.from(
|
||||||
|
{ length: 8 },
|
||||||
|
(_, i) =>
|
||||||
|
`<path d="M45 20q8-4 6-9" transform="rotate(${45 * i} 44 24)"/>`,
|
||||||
|
).join(""),
|
||||||
|
D: nose + line("M12 40h58m-49-4 8-1m3-1 7-1"),
|
||||||
|
LC:
|
||||||
|
line(
|
||||||
|
"M17 18l27-9 27 9-11 7-16-4-16 4z M29 26v5q13 10 30 0v-5 M36 24l8 3 8-3",
|
||||||
|
) + '<circle cx="44" cy="17" r="3"/>',
|
||||||
|
VIP:
|
||||||
|
line("M20 14l12 7 12-12 12 12 12-7-5 20H25z M26 39h37") +
|
||||||
|
'<circle cx="44" cy="27" r="2"/>',
|
||||||
|
AI:
|
||||||
|
line(
|
||||||
|
"M15 33h35v-8H35l-3-9H21v11h-6z M38 24l12-16 12 4-2 4-8-2-7 11 M65 16l7 3m-9 0 7 5m-10-3 5 7",
|
||||||
|
) + '<circle cx="23" cy="35" r="4"/><circle cx="43" cy="35" r="4"/>',
|
||||||
|
FLR: line(
|
||||||
|
"M26 37l17-16a12 12 0 0 1 15-14l-8 9 6 5 9-8a12 12 0 0 1-17 14L31 42Z",
|
||||||
|
),
|
||||||
|
DLY:
|
||||||
|
'<circle cx="44" cy="25" r="16"/>' +
|
||||||
|
line("M44 14v12l8 4m-12-25h8m-4 0v3 M22 17h-8m7 8H9m15 8H13"),
|
||||||
|
SC:
|
||||||
|
'<circle cx="44" cy="24" r="9"/>' +
|
||||||
|
line(
|
||||||
|
"M44 4v6m0 28v6M24 24h6m28 0h6M30 10l4 4m20 20 4 4m0-28-4 4m-20 20-4 4",
|
||||||
|
),
|
||||||
|
FG: cloud + line("M15 33h34m6 0h18m-52 5h44m-38 5h18m6 0h13"),
|
||||||
|
SN:
|
||||||
|
cloud +
|
||||||
|
line(
|
||||||
|
"M33 35v7m-3-5 6 3m0-3-6 3m15-5v6m-3-4 6 2m0-2-6 2m15-6v7m-3-5 6 3m0-3-6 3",
|
||||||
|
),
|
||||||
|
CW: line(
|
||||||
|
"M27 40V8m0 4 37 5-4 11-33-6z M39 14l-2 10m12-9-2 11m12-10-2 11 M14 15h7m-10 7h10m47 0h10",
|
||||||
|
),
|
||||||
|
ICE: snowflake,
|
||||||
|
};
|
||||||
|
for (const code of ["31L", "31R"])
|
||||||
|
icons[code] =
|
||||||
|
line("M20 10h46v28H20z M25 13v22m36-22v22m-24-19 14 16m0-16L37 32") +
|
||||||
|
`<text x="73" y="36" fill="currentColor" stroke="none" font-size="12">${code.slice(-1)}</text>`;
|
||||||
|
|
||||||
|
export function cardLabel(code: string) {
|
||||||
|
return faces[code]?.[0] || code;
|
||||||
|
}
|
||||||
|
export function cardCaption(code: string) {
|
||||||
|
return code + " · " + cardLabel(code);
|
||||||
|
}
|
||||||
|
export function cardFace(
|
||||||
|
code: string,
|
||||||
|
index: number,
|
||||||
|
selectable: boolean,
|
||||||
|
selected: boolean,
|
||||||
|
) {
|
||||||
|
const [title, english, family, effect] = faces[code];
|
||||||
|
const tag = selectable ? "button" : "div";
|
||||||
|
const action = selectable
|
||||||
|
? `type="button" data-act="card" data-val="${index}" aria-pressed="${selected}"`
|
||||||
|
: "";
|
||||||
|
return `<${tag} class="flight-card fc-${family}${selected ? " chosen" : ""}" ${action} data-code="${code}">
|
||||||
|
<span class="fc-head"><b>${code}</b><span>${families[family]}</span></span>
|
||||||
|
<svg viewBox="0 0 88 48" aria-hidden="true" class="fc-art"><g stroke="currentColor" stroke-width="2" fill="none" stroke-linejoin="round" stroke-linecap="round">${icons[code]}</g></svg>
|
||||||
|
<span class="fc-title">${title}</span><span class="fc-en" lang="en">${english}</span>
|
||||||
|
<span class="fc-effect">${effect}</span></${tag}>`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
# Сверка комплекта и решений по правилам
|
||||||
|
|
||||||
|
Каталог основан на буклете издания 00475. При сверке использованы подписи на самих картах, силуэты фишек и увеличенная схема поля. Номера страниц ниже напечатаны в нижней части исходного буклета. [Буклет 00475](https://tesera.ru/images/items/893919/00475.pdf). [Копия для сверки иллюстраций](https://hobbygames.ru/download/rules/Vzlyot_Razreshen_Rules.pdf).
|
||||||
|
|
||||||
|
| Компания | Малые | Средние | Широкофюзеляжные |
|
||||||
|
|---|---:|---:|---:|
|
||||||
|
| Фиолетовая | 0 | 0 | 4 |
|
||||||
|
| Красная | 0 | 3 | 2 |
|
||||||
|
| Зелёная | 0 | 6 | 0 |
|
||||||
|
| Синяя | 4 | 0 | 2 |
|
||||||
|
| Голубая | 2 | 3 | 1 |
|
||||||
|
| Жёлтая | 7 | 0 | 0 |
|
||||||
|
|
||||||
|
На стр. 1 видны три разных силуэта. У малого самолёта прямое крыло, у среднего стреловидное, у широкофюзеляжного по два двигателя на каждом крыле. Суммарно в комплекте 34 борта. Для погоды иллюстрация на той же странице даёт 4 ICE, 2 CROSSWIND, 2 SKY CLEAR и 3 FOG. Вместе с остальной погодой в колоде 19 погодных карт. Общий размер колоды 146.
|
||||||
|
|
||||||
|
На стр. 2, 5 и 6 можно пересчитать шесть позиций A у терминала, три B, три стоянки A/C и две пары VIP. У каждой полосы пять D ожидания и отдельно D на исполнительном старте, общая вместимость шесть. Сведения из чернового ТЗ о размерах поля и составе погодных карт исправлены по иллюстрациям. Для разработки новой разметки и тестов следует брать значения из каталога.
|
||||||
|
|
||||||
|
На стр. 6 занятый C и перечёркнутая стрелка из ангара показывают, что на A этой же стоянки вход закрыт. Обычные стоянки A/B подключены к общей дорожке. В цифровой версии при переходе с обычной A допускается выбор любой свободной B. Следующий участок дорожки общий для обеих VIP-веток и обоих направлений на ВПП. Если разрешены обе ВПП, направление выбирает владелец борта.
|
||||||
|
|
||||||
|
В буклете на стр. 7 при боковом ветре головной борт, которому запрещён взлёт, уступает место ожидающим. Рисунок на стр. 9 показывает такой манёвр для малого самолёта. Средний самолёт этим примером не разобран. В настольной игре существуют отличающиеся редакции: в другой русской инструкции запрет бокового ветра прямо распространён на малые и средние борта. Для совместимости повтора трактовка привязывается к версии правил конкретной партии. [Другая русская редакция, стр. 8](https://na100lki.com/wp-content/uploads/2023/09/Lucky-Captain-Rules.pdf).
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
name: vzlet-demo
|
||||||
|
services:
|
||||||
|
demo:
|
||||||
|
build: {context: ., dockerfile: Dockerfile.demo}
|
||||||
|
restart: unless-stopped
|
||||||
|
user: "10001:10001"
|
||||||
|
read_only: true
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
environment: {GOMEMLIMIT: 80MiB, GOMAXPROCS: "1"}
|
||||||
|
pids_limit: 48
|
||||||
|
mem_limit: 128m
|
||||||
|
cpus: 1
|
||||||
|
ulimits:
|
||||||
|
nofile: {soft: 512, hard: 512}
|
||||||
|
ports: ["${BIND_ADDRESS:-127.0.0.1}:${HTTP_PORT:-8080}:8080"]
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD","/server","-health"]
|
||||||
|
interval: 20s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 3
|
||||||
|
logging:
|
||||||
|
driver: json-file
|
||||||
|
options: {max-size: "2m", max-file: "2"}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
name: vzlet
|
||||||
|
x-db-settings: &db-settings
|
||||||
|
POSTGRES_USER: dispatch
|
||||||
|
POSTGRES_DB: dispatch
|
||||||
|
x-app-security: &app-security
|
||||||
|
user: "10001:10001"
|
||||||
|
read_only: true
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
pids_limit: 96
|
||||||
|
mem_limit: 384m
|
||||||
|
cpus: 1
|
||||||
|
tmpfs: ["/tmp:rw,noexec,nosuid,nodev,size=32m,mode=1777"]
|
||||||
|
logging:
|
||||||
|
driver: json-file
|
||||||
|
options: {max-size: "5m", max-file: "2"}
|
||||||
|
services:
|
||||||
|
migrate:
|
||||||
|
<<: *app-security
|
||||||
|
profiles: [migration]
|
||||||
|
build: {context: ., target: web}
|
||||||
|
command: ["python", "-m", "game.migrate"]
|
||||||
|
volumes: [db_auth:/auth:ro, sqlite_data:/data]
|
||||||
|
environment:
|
||||||
|
<<: *db-settings
|
||||||
|
DB_PASSWORD_FILE: /auth/db-password
|
||||||
|
SQLITE_PATH: /data/dispatch.sqlite3
|
||||||
|
networks: [storage]
|
||||||
|
depends_on:
|
||||||
|
db: {condition: service_healthy}
|
||||||
|
init-secret:
|
||||||
|
image: postgres:16-alpine@sha256:f2f98726820d0342055351c6e9d36e705f5bfffb3dd53ff556325114b08afb6d
|
||||||
|
entrypoint: ["/bin/sh", "-ec"]
|
||||||
|
command:
|
||||||
|
- |
|
||||||
|
if [ ! -s /auth/db-password ]; then
|
||||||
|
umask 077
|
||||||
|
head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n' > /auth/new-password
|
||||||
|
chmod 0444 /auth/new-password
|
||||||
|
mv /auth/new-password /auth/db-password
|
||||||
|
fi
|
||||||
|
volumes: [db_auth:/auth]
|
||||||
|
network_mode: none
|
||||||
|
db:
|
||||||
|
image: postgres:16-alpine@sha256:f2f98726820d0342055351c6e9d36e705f5bfffb3dd53ff556325114b08afb6d
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
<<: *db-settings
|
||||||
|
POSTGRES_PASSWORD_FILE: /auth/db-password
|
||||||
|
volumes: [db_data:/var/lib/postgresql/data, db_auth:/auth:ro]
|
||||||
|
networks: [storage]
|
||||||
|
depends_on:
|
||||||
|
init-secret: {condition: service_completed_successfully}
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", 'pg_isready -U "$${POSTGRES_USER}" -d "$${POSTGRES_DB}"']
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 20
|
||||||
|
bot:
|
||||||
|
<<: *app-security
|
||||||
|
build: {context: ., target: worker}
|
||||||
|
restart: unless-stopped
|
||||||
|
networks: [decisions]
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD","python","-c","import urllib.request; urllib.request.urlopen('http://127.0.0.1:8081/health', timeout=2)"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 8
|
||||||
|
web:
|
||||||
|
<<: *app-security
|
||||||
|
build: {context: ., target: web}
|
||||||
|
restart: unless-stopped
|
||||||
|
ports: ["${BIND_ADDRESS:-127.0.0.1}:${HTTP_PORT:-8080}:8080"]
|
||||||
|
volumes: [db_auth:/auth:ro]
|
||||||
|
environment:
|
||||||
|
<<: *db-settings
|
||||||
|
DB_PASSWORD_FILE: /auth/db-password
|
||||||
|
BOT_URL: http://bot:8081
|
||||||
|
COOKIE_SECURE: ${COOKIE_SECURE:-0}
|
||||||
|
networks: [ingress, storage, decisions]
|
||||||
|
depends_on:
|
||||||
|
db: {condition: service_healthy}
|
||||||
|
bot: {condition: service_healthy}
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD","python","-c","import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health', timeout=2)"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 8
|
||||||
|
networks:
|
||||||
|
ingress: {}
|
||||||
|
storage: {internal: true}
|
||||||
|
decisions: {internal: true}
|
||||||
|
volumes:
|
||||||
|
sqlite_data: {}
|
||||||
|
db_auth: {}
|
||||||
|
db_data: {}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
name: vzlet
|
||||||
|
x-app-security: &app-security
|
||||||
|
user: "10001:10001"
|
||||||
|
read_only: true
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
pids_limit: 96
|
||||||
|
mem_limit: 384m
|
||||||
|
cpus: 1
|
||||||
|
tmpfs: ["/tmp:rw,noexec,nosuid,nodev,size=32m,mode=1777"]
|
||||||
|
logging:
|
||||||
|
driver: json-file
|
||||||
|
options: {max-size: "5m", max-file: "2"}
|
||||||
|
services:
|
||||||
|
bot:
|
||||||
|
<<: *app-security
|
||||||
|
build: {context: ., target: worker}
|
||||||
|
restart: unless-stopped
|
||||||
|
networks: [decisions]
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD","python","-c","import urllib.request; urllib.request.urlopen('http://127.0.0.1:8081/health', timeout=2)"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 8
|
||||||
|
web:
|
||||||
|
<<: *app-security
|
||||||
|
build: {context: ., target: web}
|
||||||
|
restart: unless-stopped
|
||||||
|
ports: ["${BIND_ADDRESS:-127.0.0.1}:${HTTP_PORT:-8080}:8080"]
|
||||||
|
volumes: [sqlite_data:/data]
|
||||||
|
environment:
|
||||||
|
SQLITE_PATH: /data/dispatch.sqlite3
|
||||||
|
BOT_URL: http://bot:8081
|
||||||
|
COOKIE_SECURE: ${COOKIE_SECURE:-0}
|
||||||
|
networks: [ingress, decisions]
|
||||||
|
depends_on:
|
||||||
|
bot: {condition: service_healthy}
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD","python","-c","import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health', timeout=2)"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 8
|
||||||
|
networks:
|
||||||
|
ingress: {}
|
||||||
|
decisions: {internal: true}
|
||||||
|
volumes:
|
||||||
|
sqlite_data: {}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
const cookieName="vzlet_demo_v1";
|
||||||
|
let bridge:Promise<HTMLIFrameElement>;
|
||||||
|
async function createBridge():Promise<HTMLIFrameElement>{
|
||||||
|
if(!navigator.serviceWorker)throw Error("Откройте демо по HTTPS или через localhost.");
|
||||||
|
await navigator.serviceWorker.register("/cookie-worker.js");
|
||||||
|
await navigator.serviceWorker.ready;
|
||||||
|
if(!navigator.serviceWorker.controller)await new Promise<void>(resolve=>
|
||||||
|
navigator.serviceWorker.addEventListener("controllerchange",()=>resolve(),{once:true}));
|
||||||
|
return new Promise(resolve=>{
|
||||||
|
const frame=document.createElement("iframe");
|
||||||
|
frame.hidden=true;frame.title="Локальное сохранение";frame.onload=()=>resolve(frame);
|
||||||
|
frame.src="/__local_game__/";document.body.append(frame);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async function cookie(next:string|null=null):Promise<string>{
|
||||||
|
const frame=await (bridge??=createBridge());
|
||||||
|
return new Promise((resolve,reject)=>{
|
||||||
|
const channel=new MessageChannel();
|
||||||
|
const timeout=setTimeout(()=>{channel.port1.close();reject(Error("Браузер заблокировал локальное сохранение"));},5000);
|
||||||
|
channel.port1.onmessage=({data})=>{
|
||||||
|
clearTimeout(timeout);channel.port1.close();data.error?reject(Error(data.error)):resolve(data.value);
|
||||||
|
};
|
||||||
|
frame.contentWindow.postMessage(next,location.origin,[channel.port2]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let worker:Worker,version="";
|
||||||
|
function run(input):Promise<any>{
|
||||||
|
if(!worker)worker=new Worker("/worker.js");
|
||||||
|
return new Promise((resolve,reject)=>{
|
||||||
|
worker.onmessage=({data})=>data.error?reject(Error(data.error)):resolve(data.result);
|
||||||
|
worker.onerror=()=>{worker.terminate();worker=null;reject(Error("Не удалось загрузить локальный движок"))};
|
||||||
|
worker.postMessage(input);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
export function current(){return cookie()}
|
||||||
|
export async function play(opts:{bots?:number,color?:string,command?:any,reset?:boolean}={}){
|
||||||
|
if(!navigator.locks)throw Error("Для локальной игры откройте сайт по HTTPS или через localhost.");
|
||||||
|
return navigator.locks.request(cookieName,async()=>{
|
||||||
|
const saved=await cookie();
|
||||||
|
if(opts.command && saved!==version)throw Error("Партия изменилась в другой вкладке. Обновите страницу.");
|
||||||
|
const result=await run({token:opts.reset?"":saved,bots:opts.bots||3,color:opts.color||null,command:opts.command??null});
|
||||||
|
await cookie(result.token);version=result.token;
|
||||||
|
return result;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,373 @@
|
|||||||
|
Mozilla Public License Version 2.0
|
||||||
|
==================================
|
||||||
|
|
||||||
|
1. Definitions
|
||||||
|
--------------
|
||||||
|
|
||||||
|
1.1. "Contributor"
|
||||||
|
means each individual or legal entity that creates, contributes to
|
||||||
|
the creation of, or owns Covered Software.
|
||||||
|
|
||||||
|
1.2. "Contributor Version"
|
||||||
|
means the combination of the Contributions of others (if any) used
|
||||||
|
by a Contributor and that particular Contributor's Contribution.
|
||||||
|
|
||||||
|
1.3. "Contribution"
|
||||||
|
means Covered Software of a particular Contributor.
|
||||||
|
|
||||||
|
1.4. "Covered Software"
|
||||||
|
means Source Code Form to which the initial Contributor has attached
|
||||||
|
the notice in Exhibit A, the Executable Form of such Source Code
|
||||||
|
Form, and Modifications of such Source Code Form, in each case
|
||||||
|
including portions thereof.
|
||||||
|
|
||||||
|
1.5. "Incompatible With Secondary Licenses"
|
||||||
|
means
|
||||||
|
|
||||||
|
(a) that the initial Contributor has attached the notice described
|
||||||
|
in Exhibit B to the Covered Software; or
|
||||||
|
|
||||||
|
(b) that the Covered Software was made available under the terms of
|
||||||
|
version 1.1 or earlier of the License, but not also under the
|
||||||
|
terms of a Secondary License.
|
||||||
|
|
||||||
|
1.6. "Executable Form"
|
||||||
|
means any form of the work other than Source Code Form.
|
||||||
|
|
||||||
|
1.7. "Larger Work"
|
||||||
|
means a work that combines Covered Software with other material, in
|
||||||
|
a separate file or files, that is not Covered Software.
|
||||||
|
|
||||||
|
1.8. "License"
|
||||||
|
means this document.
|
||||||
|
|
||||||
|
1.9. "Licensable"
|
||||||
|
means having the right to grant, to the maximum extent possible,
|
||||||
|
whether at the time of the initial grant or subsequently, any and
|
||||||
|
all of the rights conveyed by this License.
|
||||||
|
|
||||||
|
1.10. "Modifications"
|
||||||
|
means any of the following:
|
||||||
|
|
||||||
|
(a) any file in Source Code Form that results from an addition to,
|
||||||
|
deletion from, or modification of the contents of Covered
|
||||||
|
Software; or
|
||||||
|
|
||||||
|
(b) any new file in Source Code Form that contains any Covered
|
||||||
|
Software.
|
||||||
|
|
||||||
|
1.11. "Patent Claims" of a Contributor
|
||||||
|
means any patent claim(s), including without limitation, method,
|
||||||
|
process, and apparatus claims, in any patent Licensable by such
|
||||||
|
Contributor that would be infringed, but for the grant of the
|
||||||
|
License, by the making, using, selling, offering for sale, having
|
||||||
|
made, import, or transfer of either its Contributions or its
|
||||||
|
Contributor Version.
|
||||||
|
|
||||||
|
1.12. "Secondary License"
|
||||||
|
means either the GNU General Public License, Version 2.0, the GNU
|
||||||
|
Lesser General Public License, Version 2.1, the GNU Affero General
|
||||||
|
Public License, Version 3.0, or any later versions of those
|
||||||
|
licenses.
|
||||||
|
|
||||||
|
1.13. "Source Code Form"
|
||||||
|
means the form of the work preferred for making modifications.
|
||||||
|
|
||||||
|
1.14. "You" (or "Your")
|
||||||
|
means an individual or a legal entity exercising rights under this
|
||||||
|
License. For legal entities, "You" includes any entity that
|
||||||
|
controls, is controlled by, or is under common control with You. For
|
||||||
|
purposes of this definition, "control" means (a) the power, direct
|
||||||
|
or indirect, to cause the direction or management of such entity,
|
||||||
|
whether by contract or otherwise, or (b) ownership of more than
|
||||||
|
fifty percent (50%) of the outstanding shares or beneficial
|
||||||
|
ownership of such entity.
|
||||||
|
|
||||||
|
2. License Grants and Conditions
|
||||||
|
--------------------------------
|
||||||
|
|
||||||
|
2.1. Grants
|
||||||
|
|
||||||
|
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||||
|
non-exclusive license:
|
||||||
|
|
||||||
|
(a) under intellectual property rights (other than patent or trademark)
|
||||||
|
Licensable by such Contributor to use, reproduce, make available,
|
||||||
|
modify, display, perform, distribute, and otherwise exploit its
|
||||||
|
Contributions, either on an unmodified basis, with Modifications, or
|
||||||
|
as part of a Larger Work; and
|
||||||
|
|
||||||
|
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
||||||
|
for sale, have made, import, and otherwise transfer either its
|
||||||
|
Contributions or its Contributor Version.
|
||||||
|
|
||||||
|
2.2. Effective Date
|
||||||
|
|
||||||
|
The licenses granted in Section 2.1 with respect to any Contribution
|
||||||
|
become effective for each Contribution on the date the Contributor first
|
||||||
|
distributes such Contribution.
|
||||||
|
|
||||||
|
2.3. Limitations on Grant Scope
|
||||||
|
|
||||||
|
The licenses granted in this Section 2 are the only rights granted under
|
||||||
|
this License. No additional rights or licenses will be implied from the
|
||||||
|
distribution or licensing of Covered Software under this License.
|
||||||
|
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
||||||
|
Contributor:
|
||||||
|
|
||||||
|
(a) for any code that a Contributor has removed from Covered Software;
|
||||||
|
or
|
||||||
|
|
||||||
|
(b) for infringements caused by: (i) Your and any other third party's
|
||||||
|
modifications of Covered Software, or (ii) the combination of its
|
||||||
|
Contributions with other software (except as part of its Contributor
|
||||||
|
Version); or
|
||||||
|
|
||||||
|
(c) under Patent Claims infringed by Covered Software in the absence of
|
||||||
|
its Contributions.
|
||||||
|
|
||||||
|
This License does not grant any rights in the trademarks, service marks,
|
||||||
|
or logos of any Contributor (except as may be necessary to comply with
|
||||||
|
the notice requirements in Section 3.4).
|
||||||
|
|
||||||
|
2.4. Subsequent Licenses
|
||||||
|
|
||||||
|
No Contributor makes additional grants as a result of Your choice to
|
||||||
|
distribute the Covered Software under a subsequent version of this
|
||||||
|
License (see Section 10.2) or under the terms of a Secondary License (if
|
||||||
|
permitted under the terms of Section 3.3).
|
||||||
|
|
||||||
|
2.5. Representation
|
||||||
|
|
||||||
|
Each Contributor represents that the Contributor believes its
|
||||||
|
Contributions are its original creation(s) or it has sufficient rights
|
||||||
|
to grant the rights to its Contributions conveyed by this License.
|
||||||
|
|
||||||
|
2.6. Fair Use
|
||||||
|
|
||||||
|
This License is not intended to limit any rights You have under
|
||||||
|
applicable copyright doctrines of fair use, fair dealing, or other
|
||||||
|
equivalents.
|
||||||
|
|
||||||
|
2.7. Conditions
|
||||||
|
|
||||||
|
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
||||||
|
in Section 2.1.
|
||||||
|
|
||||||
|
3. Responsibilities
|
||||||
|
-------------------
|
||||||
|
|
||||||
|
3.1. Distribution of Source Form
|
||||||
|
|
||||||
|
All distribution of Covered Software in Source Code Form, including any
|
||||||
|
Modifications that You create or to which You contribute, must be under
|
||||||
|
the terms of this License. You must inform recipients that the Source
|
||||||
|
Code Form of the Covered Software is governed by the terms of this
|
||||||
|
License, and how they can obtain a copy of this License. You may not
|
||||||
|
attempt to alter or restrict the recipients' rights in the Source Code
|
||||||
|
Form.
|
||||||
|
|
||||||
|
3.2. Distribution of Executable Form
|
||||||
|
|
||||||
|
If You distribute Covered Software in Executable Form then:
|
||||||
|
|
||||||
|
(a) such Covered Software must also be made available in Source Code
|
||||||
|
Form, as described in Section 3.1, and You must inform recipients of
|
||||||
|
the Executable Form how they can obtain a copy of such Source Code
|
||||||
|
Form by reasonable means in a timely manner, at a charge no more
|
||||||
|
than the cost of distribution to the recipient; and
|
||||||
|
|
||||||
|
(b) You may distribute such Executable Form under the terms of this
|
||||||
|
License, or sublicense it under different terms, provided that the
|
||||||
|
license for the Executable Form does not attempt to limit or alter
|
||||||
|
the recipients' rights in the Source Code Form under this License.
|
||||||
|
|
||||||
|
3.3. Distribution of a Larger Work
|
||||||
|
|
||||||
|
You may create and distribute a Larger Work under terms of Your choice,
|
||||||
|
provided that You also comply with the requirements of this License for
|
||||||
|
the Covered Software. If the Larger Work is a combination of Covered
|
||||||
|
Software with a work governed by one or more Secondary Licenses, and the
|
||||||
|
Covered Software is not Incompatible With Secondary Licenses, this
|
||||||
|
License permits You to additionally distribute such Covered Software
|
||||||
|
under the terms of such Secondary License(s), so that the recipient of
|
||||||
|
the Larger Work may, at their option, further distribute the Covered
|
||||||
|
Software under the terms of either this License or such Secondary
|
||||||
|
License(s).
|
||||||
|
|
||||||
|
3.4. Notices
|
||||||
|
|
||||||
|
You may not remove or alter the substance of any license notices
|
||||||
|
(including copyright notices, patent notices, disclaimers of warranty,
|
||||||
|
or limitations of liability) contained within the Source Code Form of
|
||||||
|
the Covered Software, except that You may alter any license notices to
|
||||||
|
the extent required to remedy known factual inaccuracies.
|
||||||
|
|
||||||
|
3.5. Application of Additional Terms
|
||||||
|
|
||||||
|
You may choose to offer, and to charge a fee for, warranty, support,
|
||||||
|
indemnity or liability obligations to one or more recipients of Covered
|
||||||
|
Software. However, You may do so only on Your own behalf, and not on
|
||||||
|
behalf of any Contributor. You must make it absolutely clear that any
|
||||||
|
such warranty, support, indemnity, or liability obligation is offered by
|
||||||
|
You alone, and You hereby agree to indemnify every Contributor for any
|
||||||
|
liability incurred by such Contributor as a result of warranty, support,
|
||||||
|
indemnity or liability terms You offer. You may include additional
|
||||||
|
disclaimers of warranty and limitations of liability specific to any
|
||||||
|
jurisdiction.
|
||||||
|
|
||||||
|
4. Inability to Comply Due to Statute or Regulation
|
||||||
|
---------------------------------------------------
|
||||||
|
|
||||||
|
If it is impossible for You to comply with any of the terms of this
|
||||||
|
License with respect to some or all of the Covered Software due to
|
||||||
|
statute, judicial order, or regulation then You must: (a) comply with
|
||||||
|
the terms of this License to the maximum extent possible; and (b)
|
||||||
|
describe the limitations and the code they affect. Such description must
|
||||||
|
be placed in a text file included with all distributions of the Covered
|
||||||
|
Software under this License. Except to the extent prohibited by statute
|
||||||
|
or regulation, such description must be sufficiently detailed for a
|
||||||
|
recipient of ordinary skill to be able to understand it.
|
||||||
|
|
||||||
|
5. Termination
|
||||||
|
--------------
|
||||||
|
|
||||||
|
5.1. The rights granted under this License will terminate automatically
|
||||||
|
if You fail to comply with any of its terms. However, if You become
|
||||||
|
compliant, then the rights granted under this License from a particular
|
||||||
|
Contributor are reinstated (a) provisionally, unless and until such
|
||||||
|
Contributor explicitly and finally terminates Your grants, and (b) on an
|
||||||
|
ongoing basis, if such Contributor fails to notify You of the
|
||||||
|
non-compliance by some reasonable means prior to 60 days after You have
|
||||||
|
come back into compliance. Moreover, Your grants from a particular
|
||||||
|
Contributor are reinstated on an ongoing basis if such Contributor
|
||||||
|
notifies You of the non-compliance by some reasonable means, this is the
|
||||||
|
first time You have received notice of non-compliance with this License
|
||||||
|
from such Contributor, and You become compliant prior to 30 days after
|
||||||
|
Your receipt of the notice.
|
||||||
|
|
||||||
|
5.2. If You initiate litigation against any entity by asserting a patent
|
||||||
|
infringement claim (excluding declaratory judgment actions,
|
||||||
|
counter-claims, and cross-claims) alleging that a Contributor Version
|
||||||
|
directly or indirectly infringes any patent, then the rights granted to
|
||||||
|
You by any and all Contributors for the Covered Software under Section
|
||||||
|
2.1 of this License shall terminate.
|
||||||
|
|
||||||
|
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
||||||
|
end user license agreements (excluding distributors and resellers) which
|
||||||
|
have been validly granted by You or Your distributors under this License
|
||||||
|
prior to termination shall survive termination.
|
||||||
|
|
||||||
|
************************************************************************
|
||||||
|
* *
|
||||||
|
* 6. Disclaimer of Warranty *
|
||||||
|
* ------------------------- *
|
||||||
|
* *
|
||||||
|
* Covered Software is provided under this License on an "as is" *
|
||||||
|
* basis, without warranty of any kind, either expressed, implied, or *
|
||||||
|
* statutory, including, without limitation, warranties that the *
|
||||||
|
* Covered Software is free of defects, merchantable, fit for a *
|
||||||
|
* particular purpose or non-infringing. The entire risk as to the *
|
||||||
|
* quality and performance of the Covered Software is with You. *
|
||||||
|
* Should any Covered Software prove defective in any respect, You *
|
||||||
|
* (not any Contributor) assume the cost of any necessary servicing, *
|
||||||
|
* repair, or correction. This disclaimer of warranty constitutes an *
|
||||||
|
* essential part of this License. No use of any Covered Software is *
|
||||||
|
* authorized under this License except under this disclaimer. *
|
||||||
|
* *
|
||||||
|
************************************************************************
|
||||||
|
|
||||||
|
************************************************************************
|
||||||
|
* *
|
||||||
|
* 7. Limitation of Liability *
|
||||||
|
* -------------------------- *
|
||||||
|
* *
|
||||||
|
* Under no circumstances and under no legal theory, whether tort *
|
||||||
|
* (including negligence), contract, or otherwise, shall any *
|
||||||
|
* Contributor, or anyone who distributes Covered Software as *
|
||||||
|
* permitted above, be liable to You for any direct, indirect, *
|
||||||
|
* special, incidental, or consequential damages of any character *
|
||||||
|
* including, without limitation, damages for lost profits, loss of *
|
||||||
|
* goodwill, work stoppage, computer failure or malfunction, or any *
|
||||||
|
* and all other commercial damages or losses, even if such party *
|
||||||
|
* shall have been informed of the possibility of such damages. This *
|
||||||
|
* limitation of liability shall not apply to liability for death or *
|
||||||
|
* personal injury resulting from such party's negligence to the *
|
||||||
|
* extent applicable law prohibits such limitation. Some *
|
||||||
|
* jurisdictions do not allow the exclusion or limitation of *
|
||||||
|
* incidental or consequential damages, so this exclusion and *
|
||||||
|
* limitation may not apply to You. *
|
||||||
|
* *
|
||||||
|
************************************************************************
|
||||||
|
|
||||||
|
8. Litigation
|
||||||
|
-------------
|
||||||
|
|
||||||
|
Any litigation relating to this License may be brought only in the
|
||||||
|
courts of a jurisdiction where the defendant maintains its principal
|
||||||
|
place of business and such litigation shall be governed by laws of that
|
||||||
|
jurisdiction, without reference to its conflict-of-law provisions.
|
||||||
|
Nothing in this Section shall prevent a party's ability to bring
|
||||||
|
cross-claims or counter-claims.
|
||||||
|
|
||||||
|
9. Miscellaneous
|
||||||
|
----------------
|
||||||
|
|
||||||
|
This License represents the complete agreement concerning the subject
|
||||||
|
matter hereof. If any provision of this License is held to be
|
||||||
|
unenforceable, such provision shall be reformed only to the extent
|
||||||
|
necessary to make it enforceable. Any law or regulation which provides
|
||||||
|
that the language of a contract shall be construed against the drafter
|
||||||
|
shall not be used to construe this License against a Contributor.
|
||||||
|
|
||||||
|
10. Versions of the License
|
||||||
|
---------------------------
|
||||||
|
|
||||||
|
10.1. New Versions
|
||||||
|
|
||||||
|
Mozilla Foundation is the license steward. Except as provided in Section
|
||||||
|
10.3, no one other than the license steward has the right to modify or
|
||||||
|
publish new versions of this License. Each version will be given a
|
||||||
|
distinguishing version number.
|
||||||
|
|
||||||
|
10.2. Effect of New Versions
|
||||||
|
|
||||||
|
You may distribute the Covered Software under the terms of the version
|
||||||
|
of the License under which You originally received the Covered Software,
|
||||||
|
or under the terms of any subsequent version published by the license
|
||||||
|
steward.
|
||||||
|
|
||||||
|
10.3. Modified Versions
|
||||||
|
|
||||||
|
If you create software not governed by this License, and you want to
|
||||||
|
create a new license for such software, you may create and use a
|
||||||
|
modified version of this License if you rename the license and remove
|
||||||
|
any references to the name of the license steward (except to note that
|
||||||
|
such modified license differs from this License).
|
||||||
|
|
||||||
|
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
||||||
|
Licenses
|
||||||
|
|
||||||
|
If You choose to distribute Source Code Form that is Incompatible With
|
||||||
|
Secondary Licenses under the terms of this version of the License, the
|
||||||
|
notice described in Exhibit B of this License must be attached.
|
||||||
|
|
||||||
|
Exhibit A - Source Code Form License Notice
|
||||||
|
-------------------------------------------
|
||||||
|
|
||||||
|
This Source Code Form is subject to the terms of the Mozilla Public
|
||||||
|
License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||||
|
file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
If it is not possible or desirable to put the notice in a particular
|
||||||
|
file, then You may include the notice in a location (such as a LICENSE
|
||||||
|
file in a relevant directory) where a recipient would be likely to look
|
||||||
|
for such a notice.
|
||||||
|
|
||||||
|
You may add additional accurate notices of copyright ownership.
|
||||||
|
|
||||||
|
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
||||||
|
---------------------------------------------------------
|
||||||
|
|
||||||
|
This Source Code Form is "Incompatible With Secondary Licenses", as
|
||||||
|
defined by the Mozilla Public License, v. 2.0.
|
||||||
@@ -0,0 +1,277 @@
|
|||||||
|
A. HISTORY OF THE SOFTWARE
|
||||||
|
==========================
|
||||||
|
|
||||||
|
Python was created in the early 1990s by Guido van Rossum at Stichting
|
||||||
|
Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands
|
||||||
|
as a successor of a language called ABC. Guido remains Python's
|
||||||
|
principal author, although it includes many contributions from others.
|
||||||
|
|
||||||
|
In 1995, Guido continued his work on Python at the Corporation for
|
||||||
|
National Research Initiatives (CNRI, see https://www.cnri.reston.va.us)
|
||||||
|
in Reston, Virginia where he released several versions of the
|
||||||
|
software.
|
||||||
|
|
||||||
|
In May 2000, Guido and the Python core development team moved to
|
||||||
|
BeOpen.com to form the BeOpen PythonLabs team. In October of the same
|
||||||
|
year, the PythonLabs team moved to Digital Creations, which became
|
||||||
|
Zope Corporation. In 2001, the Python Software Foundation (PSF, see
|
||||||
|
https://www.python.org/psf/) was formed, a non-profit organization
|
||||||
|
created specifically to own Python-related Intellectual Property.
|
||||||
|
Zope Corporation was a sponsoring member of the PSF.
|
||||||
|
|
||||||
|
All Python releases are Open Source (see https://opensource.org for
|
||||||
|
the Open Source Definition). Historically, most, but not all, Python
|
||||||
|
releases have also been GPL-compatible; the table below summarizes
|
||||||
|
the various releases.
|
||||||
|
|
||||||
|
Release Derived Year Owner GPL-
|
||||||
|
from compatible? (1)
|
||||||
|
|
||||||
|
0.9.0 thru 1.2 1991-1995 CWI yes
|
||||||
|
1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
|
||||||
|
1.6 1.5.2 2000 CNRI no
|
||||||
|
2.0 1.6 2000 BeOpen.com no
|
||||||
|
1.6.1 1.6 2001 CNRI yes (2)
|
||||||
|
2.1 2.0+1.6.1 2001 PSF no
|
||||||
|
2.0.1 2.0+1.6.1 2001 PSF yes
|
||||||
|
2.1.1 2.1+2.0.1 2001 PSF yes
|
||||||
|
2.1.2 2.1.1 2002 PSF yes
|
||||||
|
2.1.3 2.1.2 2002 PSF yes
|
||||||
|
2.2 and above 2.1.1 2001-now PSF yes
|
||||||
|
|
||||||
|
Footnotes:
|
||||||
|
|
||||||
|
(1) GPL-compatible doesn't mean that we're distributing Python under
|
||||||
|
the GPL. All Python licenses, unlike the GPL, let you distribute
|
||||||
|
a modified version without making your changes open source. The
|
||||||
|
GPL-compatible licenses make it possible to combine Python with
|
||||||
|
other software that is released under the GPL; the others don't.
|
||||||
|
|
||||||
|
(2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
|
||||||
|
because its license has a choice of law clause. According to
|
||||||
|
CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
|
||||||
|
is "not incompatible" with the GPL.
|
||||||
|
|
||||||
|
Thanks to the many outside volunteers who have worked under Guido's
|
||||||
|
direction to make these releases possible.
|
||||||
|
|
||||||
|
|
||||||
|
B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
|
||||||
|
===============================================================
|
||||||
|
|
||||||
|
Python software and documentation are licensed under the
|
||||||
|
Python Software Foundation License Version 2.
|
||||||
|
|
||||||
|
Starting with Python 3.8.6, examples, recipes, and other code in
|
||||||
|
the documentation are dual licensed under the PSF License Version 2
|
||||||
|
and the Zero-Clause BSD license.
|
||||||
|
|
||||||
|
Some software incorporated into Python is under different licenses.
|
||||||
|
The licenses are listed with code falling under that license.
|
||||||
|
|
||||||
|
|
||||||
|
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
|
||||||
|
--------------------------------------------
|
||||||
|
|
||||||
|
1. This LICENSE AGREEMENT is between the Python Software Foundation
|
||||||
|
("PSF"), and the Individual or Organization ("Licensee") accessing and
|
||||||
|
otherwise using this software ("Python") in source or binary form and
|
||||||
|
its associated documentation.
|
||||||
|
|
||||||
|
2. Subject to the terms and conditions of this License Agreement, PSF hereby
|
||||||
|
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
|
||||||
|
analyze, test, perform and/or display publicly, prepare derivative works,
|
||||||
|
distribute, and otherwise use Python alone or in any derivative version,
|
||||||
|
provided, however, that PSF's License Agreement and PSF's notice of copyright,
|
||||||
|
i.e., "Copyright (c) 2001-2024 Python Software Foundation; All Rights Reserved"
|
||||||
|
are retained in Python alone or in any derivative version prepared by Licensee.
|
||||||
|
|
||||||
|
3. In the event Licensee prepares a derivative work that is based on
|
||||||
|
or incorporates Python or any part thereof, and wants to make
|
||||||
|
the derivative work available to others as provided herein, then
|
||||||
|
Licensee hereby agrees to include in any such work a brief summary of
|
||||||
|
the changes made to Python.
|
||||||
|
|
||||||
|
4. PSF is making Python available to Licensee on an "AS IS"
|
||||||
|
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
||||||
|
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
|
||||||
|
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
||||||
|
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
|
||||||
|
INFRINGE ANY THIRD PARTY RIGHTS.
|
||||||
|
|
||||||
|
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
|
||||||
|
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
|
||||||
|
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
|
||||||
|
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
||||||
|
|
||||||
|
6. This License Agreement will automatically terminate upon a material
|
||||||
|
breach of its terms and conditions.
|
||||||
|
|
||||||
|
7. Nothing in this License Agreement shall be deemed to create any
|
||||||
|
relationship of agency, partnership, or joint venture between PSF and
|
||||||
|
Licensee. This License Agreement does not grant permission to use PSF
|
||||||
|
trademarks or trade name in a trademark sense to endorse or promote
|
||||||
|
products or services of Licensee, or any third party.
|
||||||
|
|
||||||
|
8. By copying, installing or otherwise using Python, Licensee
|
||||||
|
agrees to be bound by the terms and conditions of this License
|
||||||
|
Agreement.
|
||||||
|
|
||||||
|
|
||||||
|
BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
|
||||||
|
-------------------------------------------
|
||||||
|
|
||||||
|
BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
|
||||||
|
|
||||||
|
1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
|
||||||
|
office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
|
||||||
|
Individual or Organization ("Licensee") accessing and otherwise using
|
||||||
|
this software in source or binary form and its associated
|
||||||
|
documentation ("the Software").
|
||||||
|
|
||||||
|
2. Subject to the terms and conditions of this BeOpen Python License
|
||||||
|
Agreement, BeOpen hereby grants Licensee a non-exclusive,
|
||||||
|
royalty-free, world-wide license to reproduce, analyze, test, perform
|
||||||
|
and/or display publicly, prepare derivative works, distribute, and
|
||||||
|
otherwise use the Software alone or in any derivative version,
|
||||||
|
provided, however, that the BeOpen Python License is retained in the
|
||||||
|
Software, alone or in any derivative version prepared by Licensee.
|
||||||
|
|
||||||
|
3. BeOpen is making the Software available to Licensee on an "AS IS"
|
||||||
|
basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
||||||
|
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
|
||||||
|
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
||||||
|
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
|
||||||
|
INFRINGE ANY THIRD PARTY RIGHTS.
|
||||||
|
|
||||||
|
4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
|
||||||
|
SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
|
||||||
|
AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
|
||||||
|
DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
||||||
|
|
||||||
|
5. This License Agreement will automatically terminate upon a material
|
||||||
|
breach of its terms and conditions.
|
||||||
|
|
||||||
|
6. This License Agreement shall be governed by and interpreted in all
|
||||||
|
respects by the law of the State of California, excluding conflict of
|
||||||
|
law provisions. Nothing in this License Agreement shall be deemed to
|
||||||
|
create any relationship of agency, partnership, or joint venture
|
||||||
|
between BeOpen and Licensee. This License Agreement does not grant
|
||||||
|
permission to use BeOpen trademarks or trade names in a trademark
|
||||||
|
sense to endorse or promote products or services of Licensee, or any
|
||||||
|
third party. As an exception, the "BeOpen Python" logos available at
|
||||||
|
http://www.pythonlabs.com/logos.html may be used according to the
|
||||||
|
permissions granted on that web page.
|
||||||
|
|
||||||
|
7. By copying, installing or otherwise using the software, Licensee
|
||||||
|
agrees to be bound by the terms and conditions of this License
|
||||||
|
Agreement.
|
||||||
|
|
||||||
|
|
||||||
|
CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
|
||||||
|
---------------------------------------
|
||||||
|
|
||||||
|
1. This LICENSE AGREEMENT is between the Corporation for National
|
||||||
|
Research Initiatives, having an office at 1895 Preston White Drive,
|
||||||
|
Reston, VA 20191 ("CNRI"), and the Individual or Organization
|
||||||
|
("Licensee") accessing and otherwise using Python 1.6.1 software in
|
||||||
|
source or binary form and its associated documentation.
|
||||||
|
|
||||||
|
2. Subject to the terms and conditions of this License Agreement, CNRI
|
||||||
|
hereby grants Licensee a nonexclusive, royalty-free, world-wide
|
||||||
|
license to reproduce, analyze, test, perform and/or display publicly,
|
||||||
|
prepare derivative works, distribute, and otherwise use Python 1.6.1
|
||||||
|
alone or in any derivative version, provided, however, that CNRI's
|
||||||
|
License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
|
||||||
|
1995-2001 Corporation for National Research Initiatives; All Rights
|
||||||
|
Reserved" are retained in Python 1.6.1 alone or in any derivative
|
||||||
|
version prepared by Licensee. Alternately, in lieu of CNRI's License
|
||||||
|
Agreement, Licensee may substitute the following text (omitting the
|
||||||
|
quotes): "Python 1.6.1 is made available subject to the terms and
|
||||||
|
conditions in CNRI's License Agreement. This Agreement together with
|
||||||
|
Python 1.6.1 may be located on the internet using the following
|
||||||
|
unique, persistent identifier (known as a handle): 1895.22/1013. This
|
||||||
|
Agreement may also be obtained from a proxy server on the internet
|
||||||
|
using the following URL: http://hdl.handle.net/1895.22/1013".
|
||||||
|
|
||||||
|
3. In the event Licensee prepares a derivative work that is based on
|
||||||
|
or incorporates Python 1.6.1 or any part thereof, and wants to make
|
||||||
|
the derivative work available to others as provided herein, then
|
||||||
|
Licensee hereby agrees to include in any such work a brief summary of
|
||||||
|
the changes made to Python 1.6.1.
|
||||||
|
|
||||||
|
4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
|
||||||
|
basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
||||||
|
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
|
||||||
|
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
||||||
|
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
|
||||||
|
INFRINGE ANY THIRD PARTY RIGHTS.
|
||||||
|
|
||||||
|
5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
|
||||||
|
1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
|
||||||
|
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
|
||||||
|
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
||||||
|
|
||||||
|
6. This License Agreement will automatically terminate upon a material
|
||||||
|
breach of its terms and conditions.
|
||||||
|
|
||||||
|
7. This License Agreement shall be governed by the federal
|
||||||
|
intellectual property law of the United States, including without
|
||||||
|
limitation the federal copyright law, and, to the extent such
|
||||||
|
U.S. federal law does not apply, by the law of the Commonwealth of
|
||||||
|
Virginia, excluding Virginia's conflict of law provisions.
|
||||||
|
Notwithstanding the foregoing, with regard to derivative works based
|
||||||
|
on Python 1.6.1 that incorporate non-separable material that was
|
||||||
|
previously distributed under the GNU General Public License (GPL), the
|
||||||
|
law of the Commonwealth of Virginia shall govern this License
|
||||||
|
Agreement only as to issues arising under or with respect to
|
||||||
|
Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
|
||||||
|
License Agreement shall be deemed to create any relationship of
|
||||||
|
agency, partnership, or joint venture between CNRI and Licensee. This
|
||||||
|
License Agreement does not grant permission to use CNRI trademarks or
|
||||||
|
trade name in a trademark sense to endorse or promote products or
|
||||||
|
services of Licensee, or any third party.
|
||||||
|
|
||||||
|
8. By clicking on the "ACCEPT" button where indicated, or by copying,
|
||||||
|
installing or otherwise using Python 1.6.1, Licensee agrees to be
|
||||||
|
bound by the terms and conditions of this License Agreement.
|
||||||
|
|
||||||
|
ACCEPT
|
||||||
|
|
||||||
|
|
||||||
|
CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
|
||||||
|
--------------------------------------------------
|
||||||
|
|
||||||
|
Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
|
||||||
|
The Netherlands. All rights reserved.
|
||||||
|
|
||||||
|
Permission to use, copy, modify, and distribute this software and its
|
||||||
|
documentation for any purpose and without fee is hereby granted,
|
||||||
|
provided that the above copyright notice appear in all copies and that
|
||||||
|
both that copyright notice and this permission notice appear in
|
||||||
|
supporting documentation, and that the name of Stichting Mathematisch
|
||||||
|
Centrum or CWI not be used in advertising or publicity pertaining to
|
||||||
|
distribution of the software without specific, written prior
|
||||||
|
permission.
|
||||||
|
|
||||||
|
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
|
||||||
|
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||||
|
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
|
||||||
|
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||||
|
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||||
|
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
|
||||||
|
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||||
|
|
||||||
|
ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION
|
||||||
|
----------------------------------------------------------------------
|
||||||
|
|
||||||
|
Permission to use, copy, modify, and/or distribute this software for any
|
||||||
|
purpose with or without fee is hereby granted.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||||
|
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||||
|
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||||
|
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||||
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||||
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||||
|
PERFORMANCE OF THIS SOFTWARE.
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
f6e6f42f451f42affbbcddb00e8c9a3278dcbf399f57aab9f3f568839a7ff4a6 pyodide-lock.json
|
||||||
|
b22e5831eade9ff10e6fe2c811c68688cd91f10154377b4f80debcf5bafa1e56 pyodide.asm.js
|
||||||
|
5effb6a1a6cc4a1a85bec4622701aa797c031e1de923cbbaf2ad47abdc4ab325 pyodide.asm.wasm
|
||||||
|
24a458425dcb4ea9836eb5ce26701d18cb769374e2b79247602ba605bf093278 pyodide.js
|
||||||
|
71fee17f88a6260ec8c9c7c063533ee59c021fdc88a1ce76247378d3c4a35f4c python_stdlib.zip
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
// This document exists only under the private cookie path.
|
||||||
|
addEventListener("message", event => {
|
||||||
|
if (event.origin !== location.origin || event.source !== parent || !event.ports[0]) return;
|
||||||
|
const name="vzlet_demo_v1", next=event.data, port=event.ports[0];
|
||||||
|
try {
|
||||||
|
if(next!==null){
|
||||||
|
if(typeof next!=="string" || !/^[a-zA-Z0-9_=-]{1,3500}$/.test(next)) throw Error("Некорректная позиция");
|
||||||
|
document.cookie=name+"="+next+"; Path="+location.pathname+"; SameSite=Strict; Max-Age=2592000"+(location.protocol==="https:"?"; Secure":"");
|
||||||
|
}
|
||||||
|
const value=document.cookie.split("; ").find(item=>item.startsWith(name+"="))?.slice(name.length+1)||"";
|
||||||
|
if(next!==null && value!==next)throw Error("Браузер заблокировал cookie");
|
||||||
|
port.postMessage({value});
|
||||||
|
} catch(err){port.postMessage({error:err.message});}
|
||||||
|
});
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
// The browser creates this same-origin document locally. No upstream fetch.
|
||||||
|
const path = "/__local_game__/";
|
||||||
|
self.addEventListener("install", event => event.waitUntil(self.skipWaiting()));
|
||||||
|
self.addEventListener("activate", event => event.waitUntil(self.clients.claim()));
|
||||||
|
self.addEventListener("fetch", event => {
|
||||||
|
const url = new URL(event.request.url);
|
||||||
|
if (url.origin === self.location.origin && url.pathname === path)
|
||||||
|
event.respondWith(new Response('<!doctype html><script src="/cookie-bridge.js"></script>', {
|
||||||
|
headers: {"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store",
|
||||||
|
"Content-Security-Policy":"default-src 'none'; script-src 'self'; frame-ancestors 'self'; base-uri 'none'"}
|
||||||
|
}));
|
||||||
|
});
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
"""Browser worker bridge. Only a compact, validated position goes into the cookie."""
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
from collections import Counter
|
||||||
|
|
||||||
|
import engine as e
|
||||||
|
from strategy import decide
|
||||||
|
|
||||||
|
CARDS = tuple(e.CAT["cards"])
|
||||||
|
COLORS = tuple(e.CAT["fleets"])
|
||||||
|
BOARD = e.CAT["board"]
|
||||||
|
POSITIONS = ["H", "F"] + [
|
||||||
|
f"{stage}:{branch}{n}" for stage, branch, count in
|
||||||
|
(("A","B",BOARD["ab_stands"]), ("A","C",BOARD["ac_stands"]),
|
||||||
|
("B","B",BOARD["b_stands"]), ("C","C",BOARD["ac_stands"]))
|
||||||
|
for n in range(1,count+1)
|
||||||
|
] + [pos for lane in e.LANES for pos in [*e.queue(lane),f"V1:{lane}",f"V2:{lane}"]]
|
||||||
|
|
||||||
|
|
||||||
|
def number(value, lo, hi):
|
||||||
|
if type(value) is not int or not lo <= value <= hi:
|
||||||
|
raise ValueError("Некорректное число в сохранении")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def unpack_cards(ids):
|
||||||
|
return [CARDS[number(i,0,len(CARDS)-1)] for i in ids]
|
||||||
|
|
||||||
|
|
||||||
|
def encode(s):
|
||||||
|
def cards(seq):
|
||||||
|
return [CARDS.index(c) for c in seq]
|
||||||
|
ids=list(s["planes"])
|
||||||
|
pending=s["pending"]
|
||||||
|
wait=None
|
||||||
|
if pending:
|
||||||
|
if pending.get("type")=="runway":
|
||||||
|
wait=["r",ids.index(pending["plane"]),[POSITIONS.index(p) for p in pending["targets"]]]
|
||||||
|
else:
|
||||||
|
wait=["c",CARDS.index(pending["card"]),[ids.index(p) for p in pending["targets"]]]
|
||||||
|
record=[1,[COLORS.index(c) for c in s["colors"]],cards(s["deck"]),cards(s["discard"]),
|
||||||
|
[cards(h) for h in s["hands"]],[cards(Counter(h).elements()) for h in s["known"]],
|
||||||
|
[POSITIONS.index(p["pos"]) for p in s["planes"].values()],
|
||||||
|
[int(p["since"]==s["turn"]) for p in s["planes"].values()],
|
||||||
|
cards([s["weather"]]) if s["weather"] else [],s["turn"],s["active"],s["winner"],s["owed"],wait]
|
||||||
|
return base64.urlsafe_b64encode(json.dumps(record,separators=(",",":")).encode()).decode()
|
||||||
|
|
||||||
|
|
||||||
|
def decode(token):
|
||||||
|
if not isinstance(token,str) or len(token)>3500:
|
||||||
|
raise ValueError("Размер сохранения")
|
||||||
|
version,colors,deck,discard,hands,known,pos,entered,weather,turn,seat,winner,owed,wait=json.loads(
|
||||||
|
base64.b64decode(token, altchars=b"-_", validate=True))
|
||||||
|
n=len(colors)
|
||||||
|
if version!=1 or not 4<=n<=6 or len(set(colors))!=n or len(hands)!=n or len(known)!=n:
|
||||||
|
raise ValueError("Состав стола")
|
||||||
|
colors=[COLORS[number(c,0,len(COLORS)-1)] for c in colors]
|
||||||
|
turn=number(turn,1,2**31-1)
|
||||||
|
planes={}
|
||||||
|
for i,col in enumerate(colors):
|
||||||
|
for j,size in enumerate(e.CAT["fleets"][col],1):
|
||||||
|
k=len(planes)
|
||||||
|
planes[f"{col}-{j}"]=dict(owner=i,size=size,pos=POSITIONS[number(pos[k],0,len(POSITIONS)-1)],
|
||||||
|
since=turn-1+number(entered[k],0,1))
|
||||||
|
if len(pos)!=len(planes) or len(entered)!=len(planes):
|
||||||
|
raise ValueError("Состав флота")
|
||||||
|
hands=[unpack_cards(h) for h in hands]
|
||||||
|
known=[dict(Counter(unpack_cards(h))) for h in known]
|
||||||
|
deck,discard,weather=map(unpack_cards,(deck,discard,weather))
|
||||||
|
if len(weather)>1 or set(weather)-e.WEATHER or any(len(h)>e.HAND for h in hands):
|
||||||
|
raise ValueError("Некорректная рука или погода")
|
||||||
|
if Counter(deck+discard+sum(hands,[])+weather)!=Counter(e.CAT["cards"]):
|
||||||
|
raise ValueError("Неверный баланс карт")
|
||||||
|
if any(Counter(k)-Counter(h) for k,h in zip(known,hands)):
|
||||||
|
raise ValueError("Неверные открытые карты")
|
||||||
|
seat=number(seat,0,n-1)
|
||||||
|
pending=None
|
||||||
|
if wait is not None:
|
||||||
|
typ,value,targets=wait
|
||||||
|
keys=list(planes)
|
||||||
|
if typ=="r":
|
||||||
|
pending=dict(type="runway",seat=seat,plane=keys[number(value,0,len(keys)-1)],
|
||||||
|
targets=[POSITIONS[number(t,0,len(POSITIONS)-1)] for t in targets])
|
||||||
|
elif typ=="c" and CARDS[number(value,0,len(CARDS)-1)] in e.TROUBLE:
|
||||||
|
pending=dict(seat=(seat+1)%n,card=CARDS[value],targets=[keys[number(t,0,len(keys)-1)] for t in targets])
|
||||||
|
else:
|
||||||
|
raise ValueError("Неверная фаза")
|
||||||
|
return dict(colors=colors,deck=deck,discard=discard,hands=hands,known=known,planes=planes,
|
||||||
|
weather=next(iter(weather),None),transit=None,turn=turn,active=seat,
|
||||||
|
winner=None if winner is None else number(winner,0,n-1),
|
||||||
|
pending=pending,owed=number(owed,0,4),catalog=e.DIGEST,strategy=e.STRATEGY)
|
||||||
|
|
||||||
|
|
||||||
|
def dispatch(raw):
|
||||||
|
req=json.loads(raw)
|
||||||
|
if req["token"]:
|
||||||
|
s=decode(req["token"])
|
||||||
|
else:
|
||||||
|
s=e.new_game(number(req["bots"],3,5),req.get("color"))
|
||||||
|
recent=[]
|
||||||
|
def emit(state,kind,data):
|
||||||
|
if kind=="draw" and data["seat"]!=0:
|
||||||
|
data={"seat":data["seat"]}
|
||||||
|
recent.append(dict(kind=kind,data=data))
|
||||||
|
if req.get("command") is not None:
|
||||||
|
if e.actor(s)!=0:
|
||||||
|
raise ValueError("Ход другого участника")
|
||||||
|
e.Turn(s,emit).apply(req["command"])
|
||||||
|
for _ in range(40):
|
||||||
|
if s["winner"] is not None or e.actor(s)==0:
|
||||||
|
break
|
||||||
|
choice=decide(dict(view=e.observation(s,e.actor(s)),actions=e.actions(s)))
|
||||||
|
e.Turn(s,emit).apply(choice["command"])
|
||||||
|
else:
|
||||||
|
raise ValueError("Не удалось завершить ходы соперников")
|
||||||
|
return json.dumps(dict(token=encode(s),view=e.observation(s,0),actions=e.actions(s),recent=recent[-8:]))
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
"""Build only the files served by the public demo."""
|
||||||
|
from pathlib import Path
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import sys
|
||||||
|
|
||||||
|
root = Path(__file__).resolve().parents[1]
|
||||||
|
out = Path(sys.argv[1])
|
||||||
|
out.mkdir(parents=True, exist_ok=True)
|
||||||
|
static = root / "game/static"
|
||||||
|
for name in ("app.js", "airfield.js", "cards.js", "demo-client.js", "style.css"):
|
||||||
|
shutil.copy(static / name, out)
|
||||||
|
index = (static / "index.html").read_text().replace('<html lang="ru">','<html lang="ru" data-demo>')
|
||||||
|
index = re.sub(r'<nav>.*?</nav>', '', index, flags=re.S)
|
||||||
|
index = re.sub(r'<a class="brand" href="#home"\s*>', '<span class="brand">', index)
|
||||||
|
index = re.sub(r'</small></a\s*>', '</small></span>', index)
|
||||||
|
(out / "index.html").write_text(index)
|
||||||
|
shutil.copy(root / "game/catalog.json", out)
|
||||||
|
for name in ("worker.js","cookie-worker.js","cookie-bridge.js"):
|
||||||
|
shutil.copy(root / "demo" / name, out)
|
||||||
|
shutil.copytree(root / "demo/vendor", out / "vendor", dirs_exist_ok=True)
|
||||||
|
for license_file in (root / "demo").glob("LICENSE-*"):
|
||||||
|
shutil.copy(license_file, out / (license_file.name + ".txt"))
|
||||||
|
files = {name:(root / "game" / name).read_text() for name in ("catalog.json","engine.py","strategy.py")}
|
||||||
|
files["local_game.py"] = (root / "demo/local_game.py").read_text()
|
||||||
|
(out / "rules.json").write_text(json.dumps(files, ensure_ascii=False))
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
// Static-only demo server. No storage, sessions, request logs or upstreams.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"embed"
|
||||||
|
"io"
|
||||||
|
"io/fs"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed public
|
||||||
|
var assets embed.FS
|
||||||
|
|
||||||
|
func serve(w http.ResponseWriter, r *http.Request) {
|
||||||
|
h := w.Header()
|
||||||
|
policy := "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; worker-src 'self'; frame-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'"
|
||||||
|
if r.URL.Path == "/worker.js" {
|
||||||
|
policy = "default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; connect-src 'self'"
|
||||||
|
}
|
||||||
|
h.Set("Content-Security-Policy", policy)
|
||||||
|
h.Set("X-Content-Type-Options", "nosniff")
|
||||||
|
h.Set("Referrer-Policy", "no-referrer")
|
||||||
|
h.Set("X-Frame-Options", "DENY")
|
||||||
|
h.Set("Cross-Origin-Resource-Policy", "same-origin")
|
||||||
|
h.Set("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=()")
|
||||||
|
if r.Method != "GET" && r.Method != "HEAD" {
|
||||||
|
h.Set("Allow", "GET, HEAD")
|
||||||
|
w.WriteHeader(405)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
name := strings.TrimPrefix(r.URL.Path, "/")
|
||||||
|
if name == "health" {
|
||||||
|
w.WriteHeader(204)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if name == "" {
|
||||||
|
name = "index.html"
|
||||||
|
}
|
||||||
|
if !fs.ValidPath(name) {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
typ := map[string]string{".txt": "text/plain; charset=utf-8", ".html": "text/html; charset=utf-8", ".js": "text/javascript", ".css": "text/css", ".json": "application/json", ".wasm": "application/wasm", ".zip": "application/zip"}[path.Ext(name)]
|
||||||
|
f, err := assets.Open("public/" + name)
|
||||||
|
if err != nil || typ == "" {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
info, err := f.Stat()
|
||||||
|
if err != nil || info.IsDir() {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.Set("Content-Type", typ)
|
||||||
|
h.Set("Cache-Control", "no-cache")
|
||||||
|
http.ServeContent(w, r, name, time.Time{}, f.(io.ReadSeeker))
|
||||||
|
}
|
||||||
|
func main() {
|
||||||
|
if len(os.Args) == 2 && os.Args[1] == "-health" {
|
||||||
|
c := http.Client{Timeout: 2 * time.Second}
|
||||||
|
r, e := c.Get("http://127.0.0.1:8080/health")
|
||||||
|
if e != nil || r.StatusCode != 204 {
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
r.Body.Close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
server := http.Server{Addr: ":8080", Handler: http.HandlerFunc(serve), ReadHeaderTimeout: 4 * time.Second, ReadTimeout: 8 * time.Second, WriteTimeout: 45 * time.Second, IdleTimeout: 20 * time.Second, MaxHeaderBytes: 8192}
|
||||||
|
log.Fatal(server.ListenAndServe())
|
||||||
|
}
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
{"info": {"abi_version": "2025_0", "arch": "wasm32", "platform": "emscripten_4_0_9", "python": "3.13.2", "version": "0.28.0.dev0"}, "packages": {"affine": {"depends": [], "file_name": "affine-2.4.0-py3-none-any.whl", "imports": ["affine"], "install_dir": "site", "name": "affine", "package_type": "package", "sha256": "1d4c8070a40853fc28819af0821ee25d42979718165e0d4255d3063d9b11d1d4", "unvendored_tests": true, "version": "2.4.0"}, "affine-tests": {"depends": ["affine"], "file_name": "affine-tests.tar", "imports": [], "install_dir": "site", "name": "affine-tests", "package_type": "package", "sha256": "aee4fc1688de2e658f4cf3a94caa1bc8d920b2ba4919f187d1fd425fad7b3c82", "unvendored_tests": false, "version": "2.4.0"}, "aiohappyeyeballs": {"depends": [], "file_name": "aiohappyeyeballs-2.6.1-py3-none-any.whl", "imports": ["aiohappyeyeballs"], "install_dir": "site", "name": "aiohappyeyeballs", "package_type": "package", "sha256": "9a03eb07a9f12b87fe9d00c2f28719120d1b0f397d2804ee827c8253b46afc64", "unvendored_tests": false, "version": "2.6.1"}, "aiohttp": {"depends": ["aiohappyeyeballs", "aiosignal", "async-timeout", "attrs", "charset-normalizer", "frozenlist", "multidict", "yarl"], "file_name": "aiohttp-3.11.13-cp313-cp313-pyodide_2025_0_wasm32.whl", "imports": ["aiohttp"], "install_dir": "site", "name": "aiohttp", "package_type": "package", "sha256": "d75a75f15665ce930fe07b52086f0afae5717b1e1ae6ce0f5a971abb64ceab86", "unvendored_tests": true, "version": "3.11.13"}, "aiohttp-tests": {"depends": ["aiohttp"], "file_name": "aiohttp-tests.tar", "imports": [], "install_dir": "site", "name": "aiohttp-tests", "package_type": "package", "sha256": "c7d5d7d8df2c2e4e2c824bc739f603257ede6fc5a0ab128cfe64b084195bfa45", "unvendored_tests": false, "version": "3.11.13"}, "aiosignal": {"depends": ["frozenlist"], "file_name": "aiosignal-1.3.2-py2.py3-none-any.whl", "imports": ["aiosignal"], "install_dir": "site", "name": "aiosignal", "package_type": "package", "sha256": "cb0d492148462bebaea8e915d9d7a9c284ef826365884c5d3bafe5bc52d5b09e", "unvendored_tests": false, "version": "1.3.2"}, "altair": {"depends": ["typing-extensions", "jinja2", "jsonschema", "packaging", "narwhals"], "file_name": "altair-5.5.0-py3-none-any.whl", "imports": ["altair"], "install_dir": "site", "name": "altair", "package_type": "package", "sha256": "a817c6699f1956f783540cefdb891c5dfa25f3c6f1ca09792a720231cbe9f154", "unvendored_tests": false, "version": "5.5.0"}, "annotated-types": {"depends": [], "file_name": "annotated_types-0.7.0-py3-none-any.whl", "imports": ["annotated_types"], "install_dir": "site", "name": "annotated-types", "package_type": "package", "sha256": "f2cffbe760f3c616b680279d54d4ae97185c69f6d68eb5b94675f73a834efb67", "unvendored_tests": true, "version": "0.7.0"}, "annotated-types-tests": {"depends": ["annotated-types"], "file_name": "annotated-types-tests.tar", "imports": [], "install_dir": "site", "name": "annotated-types-tests", "package_type": "package", "sha256": "583fd1bfaa07896c7a3a538cc489b2d1695cc840bd617f6e3a151094f7634337", "unvendored_tests": false, "version": "0.7.0"}, "anyio": {"depends": ["ssl", "sniffio", "typing-extensions"], "file_name": "anyio-4.9.0-py3-none-any.whl", "imports": ["anyio"], "install_dir": "site", "name": "anyio", "package_type": "package", "sha256": "72b5d6b66bffbc584350772be5959e4506cb3c9d4e830fc9f15d74186c9ee0c4", "unvendored_tests": false, "version": "4.9.0"}, "apsw": {"depends": [], "file_name": "apsw-3.49.1.0-cp313-cp313-pyodide_2025_0_wasm32.whl", "imports": ["apsw"], "install_dir": "site", "name": "apsw", "package_type": "package", "sha256": "b4fe5749b60338ee9fe522fd41a5cf0fd78466c8752e656c15009fe883311088", "unvendored_tests": false, "version": "3.49.1.0"}, "argon2-cffi": {"depends": ["argon2-cffi-bindings"], "file_name": "argon2_cffi-23.1.0-py3-none-any.whl", "imports": ["argon2"], "install_dir": "site", "name": "argon2-cffi", "package_type": "package", "sha256": "f1746991a04bfb572059eb72fc4791a2c5f83abcbcf3202edb3b95c55c546493", "unvendored_tests": false, "version": "23.1.0"}, "argon2-cffi-bindings": {"depends": ["cffi"], "file_name": "argon2_cffi_bindings-21.2.0-cp313-abi3-pyodide_2025_0_wasm32.whl", "imports": ["_argon2_cffi_bindings"], "install_dir": "site", "name": "argon2-cffi-bindings", "package_type": "package", "sha256": "20aaa40b82803c597a5c32f4e5e5e02588935014fb9ca79c0615b8e412bb4dd5", "unvendored_tests": false, "version": "21.2.0"}, "asciitree": {"depends": [], "file_name": "asciitree-0.3.3-py3-none-any.whl", "imports": ["asciitree"], "install_dir": "site", "name": "asciitree", "package_type": "package", "sha256": "4ff61ef1a58d6f2a0f639171b7cf95cbf6a69f1f79205b5ba8de98ccd87b9fea", "unvendored_tests": false, "version": "0.3.3"}, "astropy": {"depends": ["packaging", "numpy", "pyerfa", "pyyaml", "astropy_iers_data"], "file_name": "astropy-7.0.1-cp313-cp313-pyodide_2025_0_wasm32.whl", "imports": ["astropy"], "install_dir": "site", "name": "astropy", "package_type": "package", "sha256": "4708771a3Line truncated
|
||||||
Vendored
+15
@@ -0,0 +1,15 @@
|
|||||||
|
"use strict";
|
||||||
|
var _createPyodideModule = (() => {
|
||||||
|
var _scriptName = typeof document != 'undefined' ? document.currentScript?.src : undefined;
|
||||||
|
return (
|
||||||
|
async function(moduleArg = {}) {
|
||||||
|
var moduleRtn;
|
||||||
|
|
||||||
|
var Module=moduleArg;var readyPromiseResolve,readyPromiseReject;var readyPromise=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject});var ENVIRONMENT_IS_WEB=typeof window=="object";var ENVIRONMENT_IS_WORKER=typeof WorkerGlobalScope!="undefined";var ENVIRONMENT_IS_NODE=typeof process=="object"&&process.versions?.node&&process.type!="renderer";var ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;if(ENVIRONMENT_IS_NODE){}var arguments_=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};if(typeof __filename!="undefined"){_scriptName=__filename}else if(ENVIRONMENT_IS_WORKER){_scriptName=self.location.href}var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("fs");var nodePath=require("path");scriptDirectory=__dirname+"/";readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}arguments_=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_SHELL){readBinary=f=>{if(typeof readbuffer=="function"){return new Uint8Array(readbuffer(f))}let data=read(f,"binary");assert(typeof data=="object");return data};readAsync=async f=>readBinary(f);globalThis.clearTimeout??=id=>{};globalThis.setTimeout??=f=>f();arguments_=globalThis.arguments||globalThis.scriptArgs;if(typeof quit=="function"){quit_=(status,toThrow)=>{setTimeout(()=>{if(!(toThrow instanceof ExitStatus)){let toLog=toThrow;if(toThrow&&typeof toThrow=="object"&&toThrow.stack){toLog=[toThrow,toThrow.stack]}err(`exiting due to exception: ${toLog}`)}quit(status)});throw toThrow}}if(typeof print!="undefined"){globalThis.console??={};console.log=print;console.warn=console.error=globalThis.printErr??print}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var dynamicLibraries=[];var wasmBinary;var wasmMemory;var ABORT=false;var EXITSTATUS;function assert(condition,text){if(!condition){abort(text)}}var HEAP,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAP64,HEAPU64,HEAPF64;var runtimeInitialized=false;var runtimeExited=false;var isFileURI=filename=>filename.startsWith("file://");function updateMemoryViews(){var b=wasmMemory.buffer;Module["HEAP8"]=HEAP8=new Int8Array(b);Module["HEAP16"]=HEAP16=new Int16Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);Module["HEAPU16"]=HEAPU16=new Uint16Array(b);Module["HEAP32"]=HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b);Module["HEAPF32"]=HEAPF32=new Float32Array(b);Module["HEAPF64"]=HEAPF64=new Float64Array(b);Module["HEAP64"]=HEAP64=new BigInt64Array(b);Module["HEAPU64"]=HEAPU64=new BigUint64Array(b)}function initMemory(){if(Module["wasmMemory"]){wasmMemory=Module["wasmMemory"]}else{var INITIAL_MEMORY=Module["INITIAL_MEMORY"]||20971520;wasmMemory=new WebAssembly.Memory({initial:INITIAL_MEMORY/65536,maximum:65536})}updateMemoryViews()}var __RELOC_FUNCS__=[];function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;callRuntimeCallbacks(__RELOC_FUNCS__);callRuntimeCallbacks(onInits);if(!Module["noFSInit"]&&!FS.initialized)FS.init();TTY.init();SOCKFS.root=FS.mount(SOCKFS,{},null);PIPEFS.root=FS.mount(PIPEFS,{},null);wasmExports["__wasm_call_ctors"]();callRuntimeCallbacks(onPostCtors);FS.ignorePermissions=false}function preMain(){callRuntimeCallbacks(onMains)}function exitRuntime(){___funcs_on_exit();callRuntimeCallbacks(onExits);FS.quit();TTY.shutdown();IDBFS.quit();runtimeExited=true}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"]Line truncated
|
||||||
|
|
||||||
|
|
||||||
|
return moduleRtn;
|
||||||
|
}
|
||||||
|
);
|
||||||
|
})();
|
||||||
|
globalThis._createPyodideModule = _createPyodideModule;
|
||||||
Vendored
BIN
Binary file not shown.
Vendored
+6
@@ -0,0 +1,6 @@
|
|||||||
|
"use strict";var loadPyodide=(()=>{var ce=Object.create;var A=Object.defineProperty;var de=Object.getOwnPropertyDescriptor;var ue=Object.getOwnPropertyNames;var fe=Object.getPrototypeOf,me=Object.prototype.hasOwnProperty;var o=(e,t)=>A(e,"name",{value:t,configurable:!0}),m=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var pe=(e,t)=>{for(var r in t)A(e,r,{get:t[r],enumerable:!0})},H=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of ue(t))!me.call(e,a)&&a!==r&&A(e,a,{get:()=>t[a],enumerable:!(s=de(t,a))||s.enumerable});return e};var b=(e,t,r)=>(r=e!=null?ce(fe(e)):{},H(t||!e||!e.__esModule?A(r,"default",{value:e,enumerable:!0}):r,e)),ge=e=>H(A({},"__esModule",{value:!0}),e);var V=(()=>{for(var e=new Uint8Array(128),t=0;t<64;t++)e[t<26?t+65:t<52?t+71:t<62?t-4:t*4-205]=t;return r=>{for(var s=r.length,a=new Uint8Array((s-(r[s-1]=="=")-(r[s-2]=="="))*3/4|0),n=0,i=0;n<s;){var l=e[r.charCodeAt(n++)],c=e[r.charCodeAt(n++)],d=e[r.charCodeAt(n++)],u=e[r.charCodeAt(n++)];a[i++]=l<<2|c>>4,a[i++]=c<<4|d>>2,a[i++]=d<<6|u}return a}})();var Me={};pe(Me,{loadPyodide:()=>j,version:()=>L});function ye(e){return!isNaN(parseFloat(e))&&isFinite(e)}o(ye,"_isNumber");function E(e){return e.charAt(0).toUpperCase()+e.substring(1)}o(E,"_capitalize");function U(e){return function(){return this[e]}}o(U,"_getter");var k=["isConstructor","isEval","isNative","isToplevel"],I=["columnNumber","lineNumber"],N=["fileName","functionName","source"],be=["args"],ve=["evalOrigin"],T=k.concat(I,N,be,ve);function g(e){if(e)for(var t=0;t<T.length;t++)e[T[t]]!==void 0&&this["set"+E(T[t])](e[T[t]])}o(g,"StackFrame");g.prototype={getArgs:o(function(){return this.args},"getArgs"),setArgs:o(function(e){if(Object.prototype.toString.call(e)!=="[object Array]")throw new TypeError("Args must be an Array");this.args=e},"setArgs"),getEvalOrigin:o(function(){return this.evalOrigin},"getEvalOrigin"),setEvalOrigin:o(function(e){if(e instanceof g)this.evalOrigin=e;else if(e instanceof Object)this.evalOrigin=new g(e);else throw new TypeError("Eval Origin must be an Object or StackFrame")},"setEvalOrigin"),toString:o(function(){var e=this.getFileName()||"",t=this.getLineNumber()||"",r=this.getColumnNumber()||"",s=this.getFunctionName()||"";return this.getIsEval()?e?"[eval] ("+e+":"+t+":"+r+")":"[eval]:"+t+":"+r:s?s+" ("+e+":"+t+":"+r+")":e+":"+t+":"+r},"toString")};g.fromString=o(function(t){var r=t.indexOf("("),s=t.lastIndexOf(")"),a=t.substring(0,r),n=t.substring(r+1,s).split(","),i=t.substring(s+1);if(i.indexOf("@")===0)var l=/@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(i,""),c=l[1],d=l[2],u=l[3];return new g({functionName:a,args:n||void 0,fileName:c,lineNumber:d||void 0,columnNumber:u||void 0})},"StackFrame$$fromString");for(h=0;h<k.length;h++)g.prototype["get"+E(k[h])]=U(k[h]),g.prototype["set"+E(k[h])]=function(e){return function(t){this[e]=!!t}}(k[h]);var h;for(S=0;S<I.length;S++)g.prototype["get"+E(I[S])]=U(I[S]),g.prototype["set"+E(I[S])]=function(e){return function(t){if(!ye(t))throw new TypeError(e+" must be a Number");this[e]=Number(t)}}(I[S]);var S;for(w=0;w<N.length;w++)g.prototype["get"+E(N[w])]=U(N[w]),g.prototype["set"+E(N[w])]=function(e){return function(t){this[e]=String(t)}}(N[w]);var w,D=g;function he(){var e=/^\s*at .*(\S+:\d+|\(native\))/m,t=/^(eval@)?(\[native code])?$/;return{parse:o(function(s){if(s.stack&&s.stack.match(e))return this.parseV8OrIE(s);if(s.stack)return this.parseFFOrSafari(s);throw new Error("Cannot parse given Error object")},"ErrorStackParser$$parse"),extractLocation:o(function(s){if(s.indexOf(":")===-1)return[s];var a=/(.+?)(?::(\d+))?(?::(\d+))?$/,n=a.exec(s.replace(/[()]/g,""));return[n[1],n[2]||void 0,n[3]||void 0]},"ErrorStackParser$$extractLocation"),parseV8OrIE:o(function(s){var a=s.stack.split(`
|
||||||
|
`).filter(function(n){return!!n.match(e)},this);return a.map(function(n){n.indexOf("(eval ")>-1&&(n=n.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(,.*$)/g,""));var i=n.replace(/^\s+/,"").replace(/\(eval code/g,"(").replace(/^.*?\s+/,""),l=i.match(/ (\(.+\)$)/);i=l?i.replace(l[0],""):i;var c=this.extractLocation(l?l[1]:i),d=l&&i||void 0,u=["eval","<anonymous>"].indexOf(c[0])>-1?void 0:c[0];return new D({functionName:d,fileName:u,lineNumber:c[1],columnNumber:c[2],source:n})},this)},"ErrorStackParser$$parseV8OrIE"),parseFFOrSafari:o(function(s){var a=s.stack.split(`
|
||||||
|
`).filter(function(n){return!n.match(t)},this);return a.map(function(n){if(n.indexOf(" > eval")>-1&&(n=n.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),n.indexOf("@")===-1&&n.indexOf(":")===-1)return new D({functionName:n});var i=/((.*".+"[^@]*)?[^@]*)(?:@)/,l=n.match(i),c=l&&l[1]?l[1]:void 0,d=this.extractLocation(n.replace(i,""));return new D({functionName:c,fileName:d[0],lineNumber:d[1],columnNumber:d[2],source:n})},this)},"ErrorStackParser$$parseFFOrSafari")}}o(he,"ErrorStackParser");var Se=new he;var z=Se;var y=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string"&&!process.browser,C=y&&typeof module<"u"&&typeof module.exports<"u"&&typeof m<"u"&&typeof __dirname<"u",q=y&&!C,ze=typeof globalThis.Bun<"u",we=typeof Deno<"u",J=!y&&!we,Y=J&&typeof window=="object"&&typeof document=="object"&&typeof document.createElement=="function"&&"sessionStorage"in window&&typeof importScripts!="function",K=J&&typeof importScripts=="function"&&typeof self=="object",qe=typeof navigator=="object"&&typeof navigator.userAgent=="string"&&navigator.userAgent.indexOf("Chrome")==-1&&navigator.userAgent.indexOf("Safari")>-1,R=typeof read=="function"&&typeof load=="function";var X,M,Q,G,B;async function W(){if(!y||(X=(await import(/* webpackIgnore */"node:url")).default,G=await import(/* webpackIgnore */"node:fs"),B=await import(/* webpackIgnore */"node:fs/promises"),Q=(await import(/* webpackIgnore */"node:vm")).default,M=await import(/* webpackIgnore */"node:path"),$=M.sep,typeof m<"u"))return;let e=G,t=await import(/* webpackIgnore */"node:crypto"),r=await import(/* webpackIgnore */"ws"),s=await import(/* webpackIgnore */"node:child_process"),a={fs:e,crypto:t,ws:r,child_process:s};globalThis.require=function(n){return a[n]}}o(W,"initNodeModules");function Ee(e,t){return M.resolve(t||".",e)}o(Ee,"node_resolvePath");function Pe(e,t){return t===void 0&&(t=location),new URL(e,t).toString()}o(Pe,"browser_resolvePath");var x;y?x=Ee:R?x=o(e=>e,"resolvePath"):x=Pe;var $;y||($="/");function ke(e,t){return e.startsWith("file://")&&(e=e.slice(7)),e.includes("://")?{response:fetch(e)}:{binary:B.readFile(e).then(r=>new Uint8Array(r.buffer,r.byteOffset,r.byteLength))}}o(ke,"node_getBinaryResponse");function Ie(e,t){if(e.startsWith("file://")&&(e=e.slice(7)),e.includes("://"))throw new Error("Shell cannot fetch urls");return{binary:Promise.resolve(new Uint8Array(readbuffer(e)))}}o(Ie,"shell_getBinaryResponse");function Ne(e,t){let r=new URL(e,location);return{response:fetch(r,t?{integrity:t}:{})}}o(Ne,"browser_getBinaryResponse");var _;y?_=ke:R?_=Ie:_=Ne;async function Z(e,t){let{response:r,binary:s}=_(e,t);if(s)return s;let a=await r;if(!a.ok)throw new Error(`Failed to load '${e}': request failed.`);return new Uint8Array(await a.arrayBuffer())}o(Z,"loadBinaryFile");var F;if(Y)F=o(async e=>await import(/* webpackIgnore */e),"loadScript");else if(K)F=o(async e=>{try{globalThis.importScripts(e)}catch(t){if(t instanceof TypeError)await import(/* webpackIgnore */e);else throw t}},"loadScript");else if(y)F=Fe;else if(R)F=load;else throw new Error("Cannot determine runtime environment");async function Fe(e){e.startsWith("file://")&&(e=e.slice(7)),e.includes("://")?Q.runInThisContext(await(await fetch(e)).text()):await import(/* webpackIgnore */X.pathToFileURL(e).href)}o(Fe,"nodeLoadScript");async function ee(e){if(y){await W();let t=await B.readFile(e,{encoding:"utf8"});return JSON.parse(t)}else if(R){let t=read(e);return JSON.parse(t)}else return await(await fetch(e)).json()}o(ee,"loadLockFile");async function te(){if(C)return __dirname;let e;try{throw new Error}catch(s){e=s}let t=z.parse(e)[0].fileName;if(y&&!t.startsWith("file://")&&(t=`file://${t}`),q){let s=await import(/* webpackIgnore */"node:path");return(await import(/* webpackIgnore */"node:url")).fileURLToPath(s.dirname(t))}let r=t.lastIndexOf($);if(r===-1)throw new Error("Could not extract indexURL path from pyodide module location");return t.slice(0,r)}o(te,"calculateDirname");function ne(e){return e.substring(0,e.lastIndexOf("/")+1)||globalThis.location?.toString()||"."}o(ne,"calculateInstallBaseUrl");function re(e){let t=e.FS,r=e.FS.filesystems.MEMFS,s=e.PATH,a={DIR_MODE:16895,FILE_MODE:33279,mount:o(function(n){if(!n.opts.fileSystemHandle)throw new Error("opts.fileSystemHandle is required");return r.mount.apply(null,arguments)},"mount"),syncfs:o(async(n,i,l)=>{try{let c=a.getLocalSet(n),d=await a.getRemoteSet(n),u=i?d:c,f=i?c:d;await a.reconcile(n,u,f),l(null)}catch(c){l(c)}},"syncfs"),getLocalSet:o(n=>{let i=Object.create(null);function l(u){return u!=="."&&u!==".."}o(l,"isRealDir");function c(u){return f=>s.join2(u,f)}o(c,"toAbsolute");let d=t.readdir(n.mountpoint).filter(l).map(c(n.mountpoint));for(;d.length;){let u=d.pop(),f=t.stat(u);t.isDir(f.mode)&&d.push.apply(d,t.readdir(u).filter(l).map(c(u))),i[u]={timestamp:f.mtime,mode:f.mode}}return{type:"local",entries:i}},"getLocalSet"),getRemoteSet:o(async n=>{let i
Line truncated
|
||||||
|
try{Object.assign(exports,loadPyodide)}catch(_){}
|
||||||
|
globalThis.loadPyodide=loadPyodide.loadPyodide;
|
||||||
|
//# sourceMappingURL=pyodide.js.map
|
||||||
Vendored
BIN
Binary file not shown.
@@ -0,0 +1,20 @@
|
|||||||
|
"use strict";
|
||||||
|
importScripts("/vendor/pyodide.js");
|
||||||
|
const ready = (async () => {
|
||||||
|
const py = await loadPyodide({indexURL: "/vendor/", fullStdLib:false});
|
||||||
|
const response = await fetch("/rules.json", {credentials:"omit"});
|
||||||
|
if (!response.ok) throw Error("Файлы движка недоступны");
|
||||||
|
const files = await response.json();
|
||||||
|
for (const file of ["catalog.json","engine.py","strategy.py","local_game.py"]) {
|
||||||
|
py.FS.writeFile("/home/pyodide/"+file, files[file]);
|
||||||
|
}
|
||||||
|
return py.runPython("from local_game import dispatch\ndispatch");
|
||||||
|
})();
|
||||||
|
onmessage = async ({data}) => {
|
||||||
|
try {
|
||||||
|
const dispatch = await ready;
|
||||||
|
postMessage({result:JSON.parse(dispatch(JSON.stringify(data)))});
|
||||||
|
} catch {
|
||||||
|
postMessage({error:"Не удалось открыть позицию. Попробуйте начать новую партию."});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS catalogs (digest TEXT PRIMARY KEY, content TEXT NOT NULL);
|
||||||
|
CREATE TABLE IF NOT EXISTS games (
|
||||||
|
id TEXT PRIMARY KEY, owner TEXT NOT NULL, created TEXT NOT NULL, updated TEXT NOT NULL,
|
||||||
|
version INTEGER NOT NULL, seq INTEGER NOT NULL, state BYTEA NOT NULL,
|
||||||
|
next_actor INTEGER, winner INTEGER, colors TEXT NOT NULL, turn INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS by_owner ON games(owner,created);
|
||||||
|
CREATE INDEX IF NOT EXISTS bot_work ON games(next_actor,updated);
|
||||||
|
CREATE TABLE IF NOT EXISTS events (
|
||||||
|
game_id TEXT NOT NULL REFERENCES games(id), seq INTEGER NOT NULL, turn INTEGER NOT NULL,
|
||||||
|
kind TEXT NOT NULL, at TEXT NOT NULL, data TEXT NOT NULL, snapshot BYTEA NOT NULL,
|
||||||
|
PRIMARY KEY(game_id,seq)
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS commands (
|
||||||
|
game_id TEXT NOT NULL REFERENCES games(id), command_id TEXT NOT NULL,
|
||||||
|
payload TEXT NOT NULL, result TEXT NOT NULL, PRIMARY KEY(game_id,command_id)
|
||||||
|
)
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
|
||||||
+478
@@ -0,0 +1,478 @@
|
|||||||
|
import asyncio
|
||||||
|
import gzip
|
||||||
|
from functools import lru_cache
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
import uuid
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from pathlib import Path
|
||||||
|
from urllib.request import Request as UrlRequest, urlopen
|
||||||
|
|
||||||
|
from fastapi import FastAPI, HTTPException, Query, Request, Response
|
||||||
|
from fastapi.staticfiles import StaticFiles
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
from . import engine as e
|
||||||
|
from .store import Database, pack, unpack
|
||||||
|
|
||||||
|
db = Database()
|
||||||
|
logger = logging.getLogger("dispatch")
|
||||||
|
COOKIE = "dispatch_owner"
|
||||||
|
WORKER = os.getenv("BOT_URL", "http://127.0.0.1:8081").rstrip("/")
|
||||||
|
|
||||||
|
|
||||||
|
def now():
|
||||||
|
return datetime.now(timezone.utc).isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
def owner(request, response=None):
|
||||||
|
token = request.cookies.get(COOKIE)
|
||||||
|
if not token or len(token) != 64:
|
||||||
|
if response is None:
|
||||||
|
raise HTTPException(404, "Партия не найдена")
|
||||||
|
token = secrets.token_hex(32)
|
||||||
|
response.set_cookie(
|
||||||
|
COOKIE,
|
||||||
|
token,
|
||||||
|
httponly=True,
|
||||||
|
samesite="strict",
|
||||||
|
secure=os.getenv("COOKIE_SECURE") == "1",
|
||||||
|
max_age=365 * 86400,
|
||||||
|
)
|
||||||
|
return hashlib.sha256(token.encode()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def require(row):
|
||||||
|
if row is None:
|
||||||
|
raise HTTPException(404, "Партия не найдена")
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
def recorder(run, gid, start):
|
||||||
|
seq = start
|
||||||
|
|
||||||
|
def emit(s, kind, data):
|
||||||
|
nonlocal seq
|
||||||
|
seq += 1
|
||||||
|
data.setdefault("seat", s["active"])
|
||||||
|
run(
|
||||||
|
"INSERT INTO events VALUES (?,?,?,?,?,?,?)",
|
||||||
|
(gid, seq, s["turn"], kind, now(), json.dumps(data), pack(s)),
|
||||||
|
)
|
||||||
|
|
||||||
|
return emit, lambda: seq
|
||||||
|
|
||||||
|
|
||||||
|
def filtered(kind, data, seat):
|
||||||
|
if seat != "full":
|
||||||
|
if kind == "draw" and data["seat"] != seat:
|
||||||
|
return {"seat": data["seat"]}
|
||||||
|
if kind == "decision" and data["seat"] != seat:
|
||||||
|
return {"seat": data["seat"]}
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def events(run, gid, seat, after=0, end=2147483647):
|
||||||
|
rows = run(
|
||||||
|
"SELECT seq,turn,kind,at,data FROM events WHERE game_id=? AND seq>? AND seq<=? ORDER BY seq",
|
||||||
|
(gid, after, end),
|
||||||
|
)
|
||||||
|
return [
|
||||||
|
dict(seq=n, turn=t, kind=k, at=a, data=filtered(k, json.loads(d), seat))
|
||||||
|
for n, t, k, a, d in rows
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def commit(gid, account, rev, cid, cmd, trace=None, bot=False):
|
||||||
|
payload = json.dumps([rev, cmd], sort_keys=True)
|
||||||
|
with db.transaction(True) as run:
|
||||||
|
row = require(db.row(run, gid, account, True))
|
||||||
|
old = run(
|
||||||
|
"SELECT payload,result FROM commands WHERE game_id=? AND command_id=?",
|
||||||
|
(gid, cid),
|
||||||
|
).fetchone()
|
||||||
|
if old:
|
||||||
|
if old[0] != payload:
|
||||||
|
raise HTTPException(409, "Ключ команды уже использован")
|
||||||
|
return json.loads(old[1])
|
||||||
|
_, version, blob, seq = row
|
||||||
|
if rev != version:
|
||||||
|
raise HTTPException(409, f"Текущая версия {version}")
|
||||||
|
s = unpack(blob)
|
||||||
|
if s["catalog"] != e.DIGEST:
|
||||||
|
raise HTTPException(409, "Требуется исходная версия каталога")
|
||||||
|
if s["winner"] is not None or ((e.actor(s) != 0) != bot):
|
||||||
|
raise HTTPException(409, "Сейчас ход другого участника или игра окончена")
|
||||||
|
emit, last = recorder(run, gid, seq)
|
||||||
|
if trace:
|
||||||
|
emit(s, "decision", dict(seat=e.actor(s), observed_seq=seq, **trace))
|
||||||
|
try:
|
||||||
|
e.Turn(s, emit).apply(cmd)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(422, str(exc)) from exc
|
||||||
|
result = dict(version=version + 1, seq=last())
|
||||||
|
run(
|
||||||
|
"UPDATE games SET version=?,seq=?,state=?,next_actor=?,winner=?,turn=?,updated=? WHERE id=?",
|
||||||
|
(
|
||||||
|
version + 1,
|
||||||
|
last(),
|
||||||
|
pack(s),
|
||||||
|
e.actor(s) if s["winner"] is None else None,
|
||||||
|
s["winner"],
|
||||||
|
s["turn"],
|
||||||
|
now(),
|
||||||
|
gid,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
run(
|
||||||
|
"INSERT INTO commands VALUES (?,?,?,?)",
|
||||||
|
(gid, cid, payload, json.dumps(result)),
|
||||||
|
)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def tick():
|
||||||
|
with db.transaction() as run:
|
||||||
|
item = run(
|
||||||
|
"SELECT id,version,state,seq FROM games WHERE next_actor>0 ORDER BY updated LIMIT 1"
|
||||||
|
).fetchone()
|
||||||
|
if not item:
|
||||||
|
return False
|
||||||
|
gid, rev, raw, seq = item
|
||||||
|
s = unpack(raw)
|
||||||
|
seat = e.actor(s)
|
||||||
|
choices = e.actions(s)
|
||||||
|
body = dict(
|
||||||
|
view=e.observation(s, seat),
|
||||||
|
actions=choices,
|
||||||
|
history=events(run, gid, seat, end=seq),
|
||||||
|
)
|
||||||
|
encoded = json.dumps(body).encode()
|
||||||
|
for _ in range(2):
|
||||||
|
try:
|
||||||
|
req = UrlRequest(
|
||||||
|
WORKER + "/decide",
|
||||||
|
data=encoded,
|
||||||
|
headers={"Content-Type": "application/json"},
|
||||||
|
)
|
||||||
|
with urlopen(req, timeout=4) as answer:
|
||||||
|
trace = json.load(answer)
|
||||||
|
cmd = trace["command"]
|
||||||
|
if not isinstance(trace["alternatives"], list):
|
||||||
|
raise ValueError("worker protocol")
|
||||||
|
break
|
||||||
|
except (OSError, ValueError, KeyError):
|
||||||
|
trace = None
|
||||||
|
if not trace:
|
||||||
|
cmd = choices[0]
|
||||||
|
if cmd["kind"] == "exchange":
|
||||||
|
cmd = dict(kind="exchange", cards=[body["view"]["hand"][0]])
|
||||||
|
trace = dict(
|
||||||
|
command=cmd, alternatives=[], reason="Резервное решение: воркер недоступен"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
commit(gid, None, rev, "bot-" + str(rev), cmd, trace, True)
|
||||||
|
except HTTPException as exc:
|
||||||
|
if exc.status_code not in (404, 409):
|
||||||
|
raise
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
async def loop():
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
worked = await asyncio.to_thread(tick)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Не удалось обработать очередь ботов")
|
||||||
|
worked = False
|
||||||
|
await asyncio.sleep(0.08 if worked else 0.4)
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(app):
|
||||||
|
db.init()
|
||||||
|
task = asyncio.create_task(loop())
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
task.cancel()
|
||||||
|
try:
|
||||||
|
await task
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
app = FastAPI(title="Взлёт разрешён!", lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
|
||||||
|
|
||||||
|
|
||||||
|
@app.middleware("http")
|
||||||
|
async def privacy(request, call_next):
|
||||||
|
response = await call_next(request)
|
||||||
|
if request.url.path.startswith("/api/"):
|
||||||
|
response.headers["Cache-Control"] = "no-store"
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
|
class Setup(BaseModel):
|
||||||
|
bots: int = Field(ge=3, le=5)
|
||||||
|
color: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class Move(BaseModel):
|
||||||
|
command_id: uuid.UUID
|
||||||
|
expected_version: int = Field(ge=0)
|
||||||
|
command: dict
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/health")
|
||||||
|
def health():
|
||||||
|
with db.transaction() as run:
|
||||||
|
run("SELECT 1")
|
||||||
|
return {"ready": True}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/catalog")
|
||||||
|
def catalog():
|
||||||
|
return e.CAT
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/games", status_code=201)
|
||||||
|
def create(data: Setup, request: Request, response: Response):
|
||||||
|
if data.color and data.color not in e.CAT["fleets"]:
|
||||||
|
raise HTTPException(422, "Неизвестная авиакомпания")
|
||||||
|
account = owner(request, response)
|
||||||
|
gid = uuid.uuid4().hex
|
||||||
|
s = e.new_game(data.bots, data.color)
|
||||||
|
ts = now()
|
||||||
|
with db.transaction(True) as run:
|
||||||
|
run(
|
||||||
|
"INSERT INTO catalogs VALUES (?,?) ON CONFLICT (digest) DO NOTHING",
|
||||||
|
(e.DIGEST, json.dumps(e.CAT)),
|
||||||
|
)
|
||||||
|
run(
|
||||||
|
"INSERT INTO games VALUES (?,?,?,?,?,?,?,?,?,?,?)",
|
||||||
|
(
|
||||||
|
gid,
|
||||||
|
account,
|
||||||
|
ts,
|
||||||
|
ts,
|
||||||
|
0,
|
||||||
|
1,
|
||||||
|
pack(s),
|
||||||
|
e.actor(s),
|
||||||
|
None,
|
||||||
|
json.dumps(s["colors"]),
|
||||||
|
1,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
emit, _ = recorder(run, gid, 0)
|
||||||
|
emit(s, "start", dict(seat=s["active"]))
|
||||||
|
return dict(
|
||||||
|
id=gid,
|
||||||
|
version=0,
|
||||||
|
seq=1,
|
||||||
|
view=e.observation(s, 0),
|
||||||
|
actions=e.actions(s) if e.actor(s) == 0 else [],
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/games")
|
||||||
|
def archive(request: Request, response: Response):
|
||||||
|
account = owner(request, response)
|
||||||
|
with db.transaction() as run:
|
||||||
|
rows = run(
|
||||||
|
"SELECT id,created,updated,turn,winner,colors,state FROM games WHERE owner=? ORDER BY created DESC",
|
||||||
|
(account,),
|
||||||
|
)
|
||||||
|
return [
|
||||||
|
dict(
|
||||||
|
id=k,
|
||||||
|
created=a,
|
||||||
|
updated=b,
|
||||||
|
turn=t,
|
||||||
|
winner=w,
|
||||||
|
colors=json.loads(c),
|
||||||
|
rules=unpack(blob)["catalog"],
|
||||||
|
strategy=unpack(blob)["strategy"],
|
||||||
|
)
|
||||||
|
for k, a, b, t, w, c, blob in rows
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class ArchiveRemoval(BaseModel):
|
||||||
|
ids: list[uuid.UUID] = Field(min_length=1)
|
||||||
|
allow_active: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/archive/remove")
|
||||||
|
def remove_games(data: ArchiveRemoval, request: Request):
|
||||||
|
account = owner(request)
|
||||||
|
ids = sorted({gid.hex for gid in data.ids})
|
||||||
|
if data.allow_active and len(ids) != 1:
|
||||||
|
raise HTTPException(422, "Текущие партии удаляются только по одной")
|
||||||
|
removed = 0
|
||||||
|
with db.transaction(True) as run:
|
||||||
|
for offset in range(0, len(ids), 300):
|
||||||
|
chunk = ids[offset:offset+300]
|
||||||
|
marks = ",".join("?" for _ in chunk)
|
||||||
|
lookup = f"SELECT id FROM games WHERE owner=? AND id IN ({marks})"
|
||||||
|
if not data.allow_active:
|
||||||
|
lookup += " AND winner IS NOT NULL"
|
||||||
|
lookup += " ORDER BY id"
|
||||||
|
if db.dsn:
|
||||||
|
lookup += " FOR UPDATE"
|
||||||
|
matched = [row[0] for row in run(lookup, [account, *chunk])]
|
||||||
|
if not matched:
|
||||||
|
continue
|
||||||
|
marks = ",".join("?" for _ in matched)
|
||||||
|
for table in ("commands", "events"):
|
||||||
|
run(f"DELETE FROM {table} WHERE game_id IN ({marks})", matched)
|
||||||
|
run(f"DELETE FROM games WHERE id IN ({marks})", matched)
|
||||||
|
removed += len(matched)
|
||||||
|
return {"removed": removed}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/games/{gid}")
|
||||||
|
def state(gid: str, request: Request):
|
||||||
|
with db.transaction() as run:
|
||||||
|
_, rev, blob, seq = require(db.row(run, gid, owner(request)))
|
||||||
|
s = unpack(blob)
|
||||||
|
return dict(
|
||||||
|
view=e.observation(s, 0),
|
||||||
|
version=rev,
|
||||||
|
seq=seq,
|
||||||
|
actions=e.actions(s) if e.actor(s) == 0 else [],
|
||||||
|
recent=events(run, gid, 0, max(0, seq - 8), seq),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/games/{gid}/commands")
|
||||||
|
def command(gid: str, data: Move, request: Request):
|
||||||
|
return commit(
|
||||||
|
gid, owner(request), data.expected_version, str(data.command_id), data.command
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/games/{gid}/events")
|
||||||
|
def stream(gid: str, request: Request, after: int = Query(0, ge=0)):
|
||||||
|
with db.transaction() as run:
|
||||||
|
row = require(db.row(run, gid, owner(request)))
|
||||||
|
return events(run, gid, 0, after, row[3])
|
||||||
|
|
||||||
|
|
||||||
|
def perspective_seat(s, perspective):
|
||||||
|
if perspective not in ["full", *map(str, range(len(s["colors"])))]:
|
||||||
|
raise HTTPException(422, "Неизвестная перспектива")
|
||||||
|
if perspective != "0" and s["winner"] is None:
|
||||||
|
raise HTTPException(403, "Доступно после окончания партии")
|
||||||
|
seat = perspective if perspective == "full" else int(perspective)
|
||||||
|
return seat
|
||||||
|
|
||||||
|
|
||||||
|
def replay_frame(point, seat, seq, timeline, finished):
|
||||||
|
v = e.observation(point, 0 if seat == "full" else seat)
|
||||||
|
if seat == "full":
|
||||||
|
v.update(hands=point["hands"], deck=list(reversed(point["deck"])))
|
||||||
|
for later in timeline[seq:]:
|
||||||
|
later["data"] = {}
|
||||||
|
later["kind"] = "future"
|
||||||
|
return dict(
|
||||||
|
view=v, seq=seq, last=len(timeline), finished=finished, timeline=timeline
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=1)
|
||||||
|
def reference():
|
||||||
|
with gzip.open(
|
||||||
|
Path(__file__).with_name("fixtures") / "reference.json.gz",
|
||||||
|
"rt",
|
||||||
|
encoding="utf8",
|
||||||
|
) as f:
|
||||||
|
return json.load(f)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/reference/replay")
|
||||||
|
def reference_replay(seq: int = Query(1, ge=1), perspective: str = "0"):
|
||||||
|
records = reference()["events"]
|
||||||
|
seat = perspective_seat(records[-1]["state"], perspective)
|
||||||
|
seq = min(seq, len(records))
|
||||||
|
timeline = [
|
||||||
|
dict(
|
||||||
|
seq=r["seq"],
|
||||||
|
turn=r["turn"],
|
||||||
|
kind=r["kind"],
|
||||||
|
at=r["at"],
|
||||||
|
data=filtered(r["kind"], r["data"], seat),
|
||||||
|
)
|
||||||
|
for r in records
|
||||||
|
]
|
||||||
|
return replay_frame(records[seq - 1]["state"], seat, seq, timeline, True)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/reference/export")
|
||||||
|
def reference_export():
|
||||||
|
return Response(
|
||||||
|
json.dumps(reference(), ensure_ascii=False),
|
||||||
|
media_type="application/json",
|
||||||
|
headers={"Content-Disposition": 'attachment; filename="reference.json"'},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/games/{gid}/replay")
|
||||||
|
def replay(
|
||||||
|
gid: str, request: Request, seq: int = Query(1, ge=1), perspective: str = "0"
|
||||||
|
):
|
||||||
|
with db.transaction() as run:
|
||||||
|
_, _, current, last = require(db.row(run, gid, owner(request)))
|
||||||
|
s = unpack(current)
|
||||||
|
seat = perspective_seat(s, perspective)
|
||||||
|
seq = min(seq, last)
|
||||||
|
raw = run(
|
||||||
|
"SELECT snapshot FROM events WHERE game_id=? AND seq=?", (gid, seq)
|
||||||
|
).fetchone()[0]
|
||||||
|
point = unpack(raw)
|
||||||
|
return replay_frame(
|
||||||
|
point, seat, seq, events(run, gid, seat, end=last), s["winner"] is not None
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/games/{gid}/export")
|
||||||
|
def export(gid: str, request: Request):
|
||||||
|
with db.transaction() as run:
|
||||||
|
_, _, blob, _ = require(db.row(run, gid, owner(request)))
|
||||||
|
s = unpack(blob)
|
||||||
|
if s["winner"] is None:
|
||||||
|
raise HTTPException(403, "Экспорт доступен после окончания")
|
||||||
|
rows = run(
|
||||||
|
"SELECT seq,turn,kind,at,data,snapshot FROM events WHERE game_id=? ORDER BY seq",
|
||||||
|
(gid,),
|
||||||
|
)
|
||||||
|
data = dict(
|
||||||
|
schema=1,
|
||||||
|
id=gid,
|
||||||
|
rules=s["catalog"],
|
||||||
|
catalog=json.loads(
|
||||||
|
run(
|
||||||
|
"SELECT content FROM catalogs WHERE digest=?", (s["catalog"],)
|
||||||
|
).fetchone()[0]
|
||||||
|
),
|
||||||
|
strategy=s["strategy"],
|
||||||
|
events=[
|
||||||
|
dict(seq=n, turn=t, kind=k, at=a, data=json.loads(d), state=unpack(b))
|
||||||
|
for n, t, k, a, d, b in rows
|
||||||
|
],
|
||||||
|
)
|
||||||
|
return Response(
|
||||||
|
json.dumps(data, ensure_ascii=False),
|
||||||
|
media_type="application/json",
|
||||||
|
headers={"Content-Disposition": f'attachment; filename="dispatch-{gid}.json"'},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
app.mount(
|
||||||
|
"/", StaticFiles(directory=Path(__file__).with_name("static"), html=True), name="ui"
|
||||||
|
)
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
{
|
||||||
|
"version": "00475-web-1",
|
||||||
|
"cards": {
|
||||||
|
"A": 24,
|
||||||
|
"B": 18,
|
||||||
|
"C": 18,
|
||||||
|
"D": 24,
|
||||||
|
"LC": 18,
|
||||||
|
"VIP": 5,
|
||||||
|
"FLR": 4,
|
||||||
|
"DLY": 4,
|
||||||
|
"AI": 12,
|
||||||
|
"SC": 2,
|
||||||
|
"FG": 3,
|
||||||
|
"SN": 4,
|
||||||
|
"CW": 2,
|
||||||
|
"ICE": 4,
|
||||||
|
"31L": 2,
|
||||||
|
"31R": 2
|
||||||
|
},
|
||||||
|
"fleets": {
|
||||||
|
"purple": [
|
||||||
|
3,
|
||||||
|
3,
|
||||||
|
3,
|
||||||
|
3
|
||||||
|
],
|
||||||
|
"red": [
|
||||||
|
3,
|
||||||
|
3,
|
||||||
|
2,
|
||||||
|
2,
|
||||||
|
2
|
||||||
|
],
|
||||||
|
"green": [
|
||||||
|
2,
|
||||||
|
2,
|
||||||
|
2,
|
||||||
|
2,
|
||||||
|
2,
|
||||||
|
2
|
||||||
|
],
|
||||||
|
"blue": [
|
||||||
|
3,
|
||||||
|
3,
|
||||||
|
1,
|
||||||
|
1,
|
||||||
|
1,
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"cyan": [
|
||||||
|
3,
|
||||||
|
2,
|
||||||
|
2,
|
||||||
|
2,
|
||||||
|
1,
|
||||||
|
1
|
||||||
|
],
|
||||||
|
"yellow": [
|
||||||
|
1,
|
||||||
|
1,
|
||||||
|
1,
|
||||||
|
1,
|
||||||
|
1,
|
||||||
|
1,
|
||||||
|
1
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"board": {
|
||||||
|
"ab_stands": 6,
|
||||||
|
"b_stands": 3,
|
||||||
|
"ac_stands": 3,
|
||||||
|
"vip_lanes": 2,
|
||||||
|
"queue_capacity": 6,
|
||||||
|
"runways": [
|
||||||
|
"31L",
|
||||||
|
"31R"
|
||||||
|
],
|
||||||
|
"vip_runways": {
|
||||||
|
"31L": [
|
||||||
|
"31L",
|
||||||
|
"31R"
|
||||||
|
],
|
||||||
|
"31R": [
|
||||||
|
"31L",
|
||||||
|
"31R"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"ab_targets": {
|
||||||
|
"B1": [
|
||||||
|
"B1",
|
||||||
|
"B2",
|
||||||
|
"B3"
|
||||||
|
],
|
||||||
|
"B2": [
|
||||||
|
"B1",
|
||||||
|
"B2",
|
||||||
|
"B3"
|
||||||
|
],
|
||||||
|
"B3": [
|
||||||
|
"B1",
|
||||||
|
"B2",
|
||||||
|
"B3"
|
||||||
|
],
|
||||||
|
"B4": [
|
||||||
|
"B1",
|
||||||
|
"B2",
|
||||||
|
"B3"
|
||||||
|
],
|
||||||
|
"B5": [
|
||||||
|
"B1",
|
||||||
|
"B2",
|
||||||
|
"B3"
|
||||||
|
],
|
||||||
|
"B6": [
|
||||||
|
"B1",
|
||||||
|
"B2",
|
||||||
|
"B3"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+398
@@ -0,0 +1,398 @@
|
|||||||
|
"""Authoritative turn engine. Only observation() and actions() cross the player boundary."""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import random
|
||||||
|
from collections import Counter
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
RAW = Path(__file__).with_name("catalog.json").read_bytes()
|
||||||
|
CAT = json.loads(RAW)
|
||||||
|
DIGEST = hashlib.sha256(RAW).hexdigest()
|
||||||
|
WEATHER = {"SC", "FG", "SN", "CW", "ICE", "31L", "31R"}
|
||||||
|
TROUBLE = {"FLR", "DLY"}
|
||||||
|
LANES = ("31L", "31R")
|
||||||
|
HAND = 9
|
||||||
|
RNG = random.SystemRandom()
|
||||||
|
STRATEGY = "dispatch-1"
|
||||||
|
|
||||||
|
|
||||||
|
def new_game(bots, color=None, rng=RNG):
|
||||||
|
colors = list(CAT["fleets"])
|
||||||
|
rng.shuffle(colors)
|
||||||
|
if color:
|
||||||
|
colors.remove(color)
|
||||||
|
colors.insert(0, color)
|
||||||
|
colors = colors[: bots + 1]
|
||||||
|
deck = [card for card, n in CAT["cards"].items() for _ in range(n)]
|
||||||
|
rng.shuffle(deck)
|
||||||
|
hands = [[deck.pop() for _ in range(HAND)] for _ in colors]
|
||||||
|
planes = {}
|
||||||
|
for seat, company in enumerate(colors):
|
||||||
|
for n, size in enumerate(CAT["fleets"][company], 1):
|
||||||
|
planes[f"{company}-{n}"] = dict(owner=seat, size=size, pos="H", since=0)
|
||||||
|
return dict(
|
||||||
|
colors=colors,
|
||||||
|
planes=planes,
|
||||||
|
deck=deck,
|
||||||
|
hands=hands,
|
||||||
|
discard=[],
|
||||||
|
known=[{} for _ in colors],
|
||||||
|
weather=None,
|
||||||
|
transit=None,
|
||||||
|
active=rng.randrange(len(colors)),
|
||||||
|
turn=1,
|
||||||
|
pending=None,
|
||||||
|
owed=0,
|
||||||
|
winner=None,
|
||||||
|
catalog=DIGEST,
|
||||||
|
strategy=STRATEGY,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def occupancy(s):
|
||||||
|
return {
|
||||||
|
p["pos"]: key for key, p in s["planes"].items() if p["pos"] not in ("H", "F")
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def queue(lane):
|
||||||
|
return [f"D:{lane}:{i}" for i in range(CAT["board"]["queue_capacity"])]
|
||||||
|
|
||||||
|
|
||||||
|
def tail(s, lane):
|
||||||
|
slots = queue(lane)
|
||||||
|
occupied = occupancy(s)
|
||||||
|
idx = max((i for i, slot in enumerate(slots) if slot in occupied), default=-1) + 1
|
||||||
|
return slots[idx] if idx < len(slots) else None
|
||||||
|
|
||||||
|
|
||||||
|
def actor(s):
|
||||||
|
return s["pending"]["seat"] if s["pending"] else s["active"]
|
||||||
|
|
||||||
|
|
||||||
|
def stage(pos):
|
||||||
|
return pos.split(":")[0]
|
||||||
|
|
||||||
|
|
||||||
|
def rank(pos):
|
||||||
|
k = stage(pos)
|
||||||
|
if k == "D":
|
||||||
|
return 9 - int(pos.split(":")[2])
|
||||||
|
return {"H": 0, "A": 1, "V1": 1, "B": 2, "C": 2, "V2": 2, "F": 10}[k]
|
||||||
|
|
||||||
|
|
||||||
|
def observation(s, seat):
|
||||||
|
return {
|
||||||
|
**{
|
||||||
|
k: s[k]
|
||||||
|
for k in (
|
||||||
|
"colors",
|
||||||
|
"planes",
|
||||||
|
"weather",
|
||||||
|
"active",
|
||||||
|
"turn",
|
||||||
|
"winner",
|
||||||
|
"known",
|
||||||
|
"pending",
|
||||||
|
"owed",
|
||||||
|
"strategy",
|
||||||
|
)
|
||||||
|
},
|
||||||
|
"seat": seat,
|
||||||
|
"hand": sorted(s["hands"][seat]),
|
||||||
|
"deck_count": len(s["deck"]),
|
||||||
|
"hand_counts": list(map(len, s["hands"])),
|
||||||
|
"discard": list(s["discard"]),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def actions(s):
|
||||||
|
if s["winner"] is not None:
|
||||||
|
return []
|
||||||
|
if s["pending"]:
|
||||||
|
if s["pending"].get("type") == "runway":
|
||||||
|
return [
|
||||||
|
dict(kind="runway", plane=s["pending"]["plane"], to=pos)
|
||||||
|
for pos in s["pending"]["targets"]
|
||||||
|
]
|
||||||
|
return [dict(kind="choose", plane=p) for p in s["pending"]["targets"]]
|
||||||
|
seat = actor(s)
|
||||||
|
hand = Counter(s["hands"][seat])
|
||||||
|
occ = occupancy(s)
|
||||||
|
result = [dict(kind="exchange")] if hand else []
|
||||||
|
for card in sorted(WEATHER & hand.keys()):
|
||||||
|
result.append(dict(kind="weather", cards=[card]))
|
||||||
|
entries = [
|
||||||
|
f"A:{path}{n}"
|
||||||
|
for path, count in (
|
||||||
|
("B", CAT["board"]["ab_stands"]),
|
||||||
|
("C", CAT["board"]["ac_stands"]),
|
||||||
|
)
|
||||||
|
for n in range(1, count + 1)
|
||||||
|
]
|
||||||
|
for key, p in s["planes"].items():
|
||||||
|
pos = p["pos"]
|
||||||
|
k = stage(pos)
|
||||||
|
if k == "F":
|
||||||
|
continue
|
||||||
|
if p["owner"] != seat:
|
||||||
|
for card in sorted(TROUBLE & hand.keys()):
|
||||||
|
if k != "H" and (card == "FLR" or k != "D"):
|
||||||
|
result.append(dict(kind="attack", plane=key, cards=[card]))
|
||||||
|
continue
|
||||||
|
if hand["VIP"] and k in ("H", "A", "B", "C"):
|
||||||
|
for lane in LANES:
|
||||||
|
if f"V1:{lane}" not in occ and f"V2:{lane}" not in occ:
|
||||||
|
result.append(
|
||||||
|
dict(kind="move", plane=key, to=f"V1:{lane}", cards=["VIP"])
|
||||||
|
)
|
||||||
|
if (
|
||||||
|
k == "D"
|
||||||
|
and pos.endswith(":0")
|
||||||
|
and s["weather"] == "ICE"
|
||||||
|
and p["since"] < s["turn"]
|
||||||
|
):
|
||||||
|
if hand["AI"] >= p["size"]:
|
||||||
|
result.append(dict(kind="ice", plane=key, cards=["AI"] * p["size"]))
|
||||||
|
if k == "H":
|
||||||
|
targets = [
|
||||||
|
x for x in entries if not (x.startswith("A:C") and "C:" + x[2:] in occ)
|
||||||
|
]
|
||||||
|
elif k == "A":
|
||||||
|
stand = pos.split(":")[1]
|
||||||
|
targets = (
|
||||||
|
["B:" + target for target in CAT["board"]["ab_targets"][stand]]
|
||||||
|
if stand.startswith("B")
|
||||||
|
else ["C:" + stand]
|
||||||
|
)
|
||||||
|
elif k in ("B", "C"):
|
||||||
|
targets = [tail(s, lane) for lane in LANES]
|
||||||
|
else:
|
||||||
|
targets = []
|
||||||
|
price = p["size"] + int(s["weather"] == "SN")
|
||||||
|
for target in targets:
|
||||||
|
if not target or target in occ:
|
||||||
|
continue
|
||||||
|
card = stage(target)
|
||||||
|
for lc in range(max(0, price - hand[card]), min(price, hand["LC"]) + 1):
|
||||||
|
result.append(
|
||||||
|
dict(
|
||||||
|
kind="move",
|
||||||
|
plane=key,
|
||||||
|
to=target,
|
||||||
|
cards=[card] * (price - lc) + ["LC"] * lc,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
class Turn:
|
||||||
|
def __init__(self, state, emit, rng=RNG):
|
||||||
|
self.s = state
|
||||||
|
self.emit = emit
|
||||||
|
self.rng = rng
|
||||||
|
|
||||||
|
def event(self, kind, **data):
|
||||||
|
self.emit(self.s, kind, data)
|
||||||
|
|
||||||
|
def move(self, key, pos, reason):
|
||||||
|
p = self.s["planes"][key]
|
||||||
|
old = p["pos"]
|
||||||
|
p.update(pos=pos, since=self.s["turn"])
|
||||||
|
self.event(
|
||||||
|
"move", plane=key, seat=p["owner"], origin=old, to=pos, reason=reason
|
||||||
|
)
|
||||||
|
|
||||||
|
def compact(self):
|
||||||
|
s = self.s
|
||||||
|
for lane in LANES:
|
||||||
|
if s["weather"] in ("FG", lane):
|
||||||
|
continue
|
||||||
|
slots = queue(lane)
|
||||||
|
occ = occupancy(s)
|
||||||
|
for pos, key in zip(slots, [occ[v] for v in slots if v in occ]):
|
||||||
|
if s["planes"][key]["pos"] != pos:
|
||||||
|
self.move(key, pos, "queue")
|
||||||
|
|
||||||
|
def weather(self, card):
|
||||||
|
if self.s["weather"]:
|
||||||
|
self.s["discard"].append(self.s["weather"])
|
||||||
|
self.s["weather"] = card
|
||||||
|
self.s["transit"] = None
|
||||||
|
self.event("weather", card=card)
|
||||||
|
self.compact()
|
||||||
|
|
||||||
|
def draw(self):
|
||||||
|
s = self.s
|
||||||
|
if not s["deck"]:
|
||||||
|
s["deck"], s["discard"] = s["discard"], []
|
||||||
|
self.rng.shuffle(s["deck"])
|
||||||
|
self.event("shuffle")
|
||||||
|
return s["deck"].pop()
|
||||||
|
|
||||||
|
def exchange(self):
|
||||||
|
s = self.s
|
||||||
|
seat = s["active"]
|
||||||
|
while s["owed"]:
|
||||||
|
card = self.draw()
|
||||||
|
if card in WEATHER:
|
||||||
|
s["transit"] = card
|
||||||
|
self.event("reveal", card=card)
|
||||||
|
self.weather(card)
|
||||||
|
elif card in TROUBLE:
|
||||||
|
s["discard"].append(card)
|
||||||
|
self.event("reveal", card=card)
|
||||||
|
candidates = {
|
||||||
|
key: (rank(p["pos"]), p["size"])
|
||||||
|
for key, p in s["planes"].items()
|
||||||
|
if p["owner"] == seat
|
||||||
|
and p["pos"] not in ("H", "F")
|
||||||
|
and (card == "FLR" or stage(p["pos"]) != "D")
|
||||||
|
}
|
||||||
|
if candidates:
|
||||||
|
top = max(candidates.values())
|
||||||
|
keys = [key for key, score in candidates.items() if score == top]
|
||||||
|
if len(keys) > 1:
|
||||||
|
s["pending"] = dict(
|
||||||
|
seat=(seat + 1) % len(s["colors"]), targets=keys, card=card
|
||||||
|
)
|
||||||
|
self.event("choice", seat=actor(s), targets=keys)
|
||||||
|
return
|
||||||
|
self.move(keys[0], "H", card)
|
||||||
|
self.compact()
|
||||||
|
else:
|
||||||
|
s["hands"][seat].append(card)
|
||||||
|
known = s["known"][seat]
|
||||||
|
known[card] = known.get(card, 0) + 1
|
||||||
|
s["owed"] -= 1
|
||||||
|
self.event("open_draw", seat=seat, card=card)
|
||||||
|
self.finish()
|
||||||
|
|
||||||
|
def finish(self):
|
||||||
|
s = self.s
|
||||||
|
seat = s["active"]
|
||||||
|
for key, p in s["planes"].items():
|
||||||
|
if p["owner"] != seat or p["since"] >= s["turn"]:
|
||||||
|
continue
|
||||||
|
k = stage(p["pos"])
|
||||||
|
if k in ("V1", "V2"):
|
||||||
|
lane = p["pos"].split(":")[1]
|
||||||
|
if k == "V1":
|
||||||
|
dest = f"V2:{lane}"
|
||||||
|
else:
|
||||||
|
available = [
|
||||||
|
tail(s, runway) for runway in CAT["board"]["vip_runways"][lane]
|
||||||
|
]
|
||||||
|
available = [pos for pos in available if pos]
|
||||||
|
if len(available) > 1:
|
||||||
|
s["pending"] = dict(
|
||||||
|
type="runway", seat=seat, plane=key, targets=available
|
||||||
|
)
|
||||||
|
self.event("choice", seat=seat, targets=available, plane=key)
|
||||||
|
return
|
||||||
|
dest = available[0] if available else None
|
||||||
|
if dest and dest not in occupancy(s):
|
||||||
|
self.move(key, dest, "vip")
|
||||||
|
for lane in LANES:
|
||||||
|
slots = queue(lane)
|
||||||
|
occ = occupancy(s)
|
||||||
|
key = occ.get(slots[0])
|
||||||
|
if not key:
|
||||||
|
continue
|
||||||
|
p = s["planes"][key]
|
||||||
|
w = s["weather"]
|
||||||
|
if p["owner"] != seat or p["since"] >= s["turn"] or w in ("FG", lane):
|
||||||
|
continue
|
||||||
|
if (
|
||||||
|
w == "ICE"
|
||||||
|
or (w == "SN" and p["size"] == 3)
|
||||||
|
or (w == "CW" and p["size"] == 1)
|
||||||
|
):
|
||||||
|
waiting = [occ[x] for x in slots[1:] if x in occ]
|
||||||
|
if waiting:
|
||||||
|
# Move the queue as one event so its intermediate positions never overlap.
|
||||||
|
order = waiting + [key]
|
||||||
|
for dest, plane in zip(slots, order):
|
||||||
|
s["planes"][plane].update(pos=dest, since=s["turn"])
|
||||||
|
self.event(
|
||||||
|
"rotate", plane=key, seat=seat, lane=lane, order=order, reason=w
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self.move(key, "F", "takeoff")
|
||||||
|
self.compact()
|
||||||
|
if all(p["pos"] == "F" for p in s["planes"].values() if p["owner"] == seat):
|
||||||
|
s["winner"] = seat
|
||||||
|
self.event("winner", seat=seat)
|
||||||
|
else:
|
||||||
|
s["active"] = (seat + 1) % len(s["colors"])
|
||||||
|
s["turn"] += 1
|
||||||
|
self.event("turn", seat=s["active"])
|
||||||
|
|
||||||
|
def apply(self, cmd):
|
||||||
|
s = self.s
|
||||||
|
if not isinstance(cmd, dict) or s["winner"] is not None:
|
||||||
|
raise ValueError("Партия завершена или команда некорректна")
|
||||||
|
seat = actor(s)
|
||||||
|
hand = s["hands"][seat]
|
||||||
|
kind = cmd.get("kind")
|
||||||
|
cards = cmd.get("cards", [])
|
||||||
|
if not isinstance(cards, list) or not all(isinstance(v, str) for v in cards):
|
||||||
|
raise ValueError("Некорректный набор карт")
|
||||||
|
if kind == "exchange":
|
||||||
|
if (
|
||||||
|
s["pending"]
|
||||||
|
or set(cmd) != {"kind", "cards"}
|
||||||
|
or not 1 <= len(cards) <= 4
|
||||||
|
or Counter(cards) - Counter(hand)
|
||||||
|
):
|
||||||
|
raise ValueError("Выберите от одной до четырёх карт из руки")
|
||||||
|
elif cmd not in actions(s):
|
||||||
|
raise ValueError("Действие недоступно")
|
||||||
|
if kind == "runway":
|
||||||
|
s["pending"] = None
|
||||||
|
self.move(cmd["plane"], cmd["to"], "vip")
|
||||||
|
self.finish()
|
||||||
|
return
|
||||||
|
if kind == "choose":
|
||||||
|
reason = s["pending"]["card"]
|
||||||
|
s["pending"] = None
|
||||||
|
self.move(cmd["plane"], "H", reason)
|
||||||
|
self.compact()
|
||||||
|
self.exchange()
|
||||||
|
return
|
||||||
|
for card in cards:
|
||||||
|
hand.remove(card)
|
||||||
|
known = s["known"][seat]
|
||||||
|
if known.get(card):
|
||||||
|
known[card] -= 1
|
||||||
|
if not known[card]:
|
||||||
|
del known[card]
|
||||||
|
if kind != "weather":
|
||||||
|
s["discard"].append(card)
|
||||||
|
if kind == "weather":
|
||||||
|
s["transit"] = cards[0]
|
||||||
|
if kind == "exchange":
|
||||||
|
s["owed"] = len(cards)
|
||||||
|
self.event(
|
||||||
|
"play",
|
||||||
|
seat=seat,
|
||||||
|
**{"action": kind},
|
||||||
|
cards=cards,
|
||||||
|
**{k: cmd[k] for k in ("plane", "to") if k in cmd},
|
||||||
|
)
|
||||||
|
if kind == "exchange":
|
||||||
|
self.exchange()
|
||||||
|
return
|
||||||
|
if kind == "weather":
|
||||||
|
self.weather(cards[0])
|
||||||
|
elif kind == "move":
|
||||||
|
self.move(cmd["plane"], cmd["to"], "card")
|
||||||
|
elif kind in ("attack", "ice"):
|
||||||
|
self.move(cmd["plane"], "H" if kind == "attack" else "F", cards[0])
|
||||||
|
self.compact()
|
||||||
|
while len(hand) < HAND:
|
||||||
|
card = self.draw()
|
||||||
|
hand.append(card)
|
||||||
|
self.event("draw", seat=seat, card=card)
|
||||||
|
self.finish()
|
||||||
Binary file not shown.
@@ -0,0 +1,42 @@
|
|||||||
|
"""Copy a consistent PostgreSQL snapshot into an empty SQLite database."""
|
||||||
|
import sqlite3
|
||||||
|
|
||||||
|
from .store import Database
|
||||||
|
|
||||||
|
|
||||||
|
def migrate():
|
||||||
|
import psycopg
|
||||||
|
|
||||||
|
store = Database()
|
||||||
|
if not store.dsn:
|
||||||
|
raise SystemExit("Укажите исходную PostgreSQL через DATABASE_URL или DB_PASSWORD_FILE")
|
||||||
|
source = store.dsn
|
||||||
|
store.dsn = None
|
||||||
|
store.init()
|
||||||
|
tables = ("catalogs", "games", "events", "commands")
|
||||||
|
with psycopg.connect(source) as pg, sqlite3.connect(store.path, timeout=30) as dest:
|
||||||
|
pg.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY")
|
||||||
|
dest.execute("PRAGMA foreign_keys=ON")
|
||||||
|
dest.execute("BEGIN IMMEDIATE")
|
||||||
|
for table in tables:
|
||||||
|
if dest.execute(f"SELECT 1 FROM {table} LIMIT 1").fetchone():
|
||||||
|
raise SystemExit("Целевая SQLite уже содержит данные")
|
||||||
|
for table in tables:
|
||||||
|
columns = [row[1] for row in dest.execute(f"PRAGMA table_info({table})")]
|
||||||
|
projection = ",".join(columns)
|
||||||
|
marks = ",".join("?" for _ in columns)
|
||||||
|
with pg.cursor(name="copy_" + table) as cur:
|
||||||
|
cur.execute(f"SELECT {projection} FROM {table}")
|
||||||
|
while rows := cur.fetchmany(256):
|
||||||
|
dest.executemany(f"INSERT INTO {table} ({projection}) VALUES ({marks})", rows)
|
||||||
|
count = dest.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]
|
||||||
|
if count != pg.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0]:
|
||||||
|
raise RuntimeError(f"Расхождение числа строк в {table}")
|
||||||
|
print(f"{table}: {count}")
|
||||||
|
if dest.execute("PRAGMA integrity_check").fetchone()[0] != "ok":
|
||||||
|
raise RuntimeError("SQLite integrity_check failed")
|
||||||
|
print("Перенос завершён")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
migrate()
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
"""Stream an online SQLite backup, or restore it to a new database path."""
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import sqlite3
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from contextlib import closing
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from .store import Database
|
||||||
|
|
||||||
|
|
||||||
|
def checked(connection):
|
||||||
|
if connection.execute("PRAGMA integrity_check").fetchone()[0] != "ok":
|
||||||
|
raise ValueError("Нарушена целостность базы")
|
||||||
|
for table in ("games", "catalogs", "commands", "events"):
|
||||||
|
connection.execute(f"SELECT 1 FROM {table} LIMIT 0")
|
||||||
|
if connection.execute("PRAGMA foreign_key_check").fetchone():
|
||||||
|
raise ValueError("Нарушена целостность связей")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--restore", action="store_true")
|
||||||
|
args = parser.parse_args()
|
||||||
|
store = Database()
|
||||||
|
if store.dsn:
|
||||||
|
parser.error("Для PostgreSQL используйте pg_dump")
|
||||||
|
path = Path(store.path).resolve()
|
||||||
|
with tempfile.TemporaryDirectory(dir=path.parent if args.restore else None) as tmp:
|
||||||
|
copy = Path(tmp) / "backup.db"
|
||||||
|
if args.restore:
|
||||||
|
with copy.open("wb") as out:
|
||||||
|
shutil.copyfileobj(sys.stdin.buffer, out)
|
||||||
|
with closing(sqlite3.connect(copy)) as con:
|
||||||
|
checked(con)
|
||||||
|
os.link(copy, path)
|
||||||
|
else:
|
||||||
|
with closing(sqlite3.connect(path.as_uri()+"?mode=ro", uri=True)) as src:
|
||||||
|
with closing(sqlite3.connect(copy)) as dst:
|
||||||
|
src.backup(dst)
|
||||||
|
checked(dst)
|
||||||
|
with copy.open("rb") as stream:
|
||||||
|
shutil.copyfileobj(stream, sys.stdout.buffer)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
const width = 1080, height = 548;
|
||||||
|
const laneY = (lane) => (lane === "31R" ? 57 : 491);
|
||||||
|
const queueY = (lane) => (lane === "31R" ? 129 : 419);
|
||||||
|
const spread = (i, n, from, to) => n <= 1 ? (from + to) / 2 : from + ((to - from) * i) / (n - 1);
|
||||||
|
function geometry(b) {
|
||||||
|
const points = {};
|
||||||
|
const add = (id, x, y, angle, label) => (points[id] = { x, y, angle, label });
|
||||||
|
for (const lane of b.runways) {
|
||||||
|
const sy = laneY(lane), qy = queueY(lane);
|
||||||
|
add("D:" + lane + ":0", 987, sy, -90, "D");
|
||||||
|
for (let n = 1; n < b.queue_capacity; n++)
|
||||||
|
add("D:" + lane + ":" + n, spread(n - 1, b.queue_capacity - 1, 949, 670), qy, 90, "D" + n);
|
||||||
|
}
|
||||||
|
for (let n = 0; n < b.ab_stands; n++) {
|
||||||
|
const upper = n < Math.ceil(b.ab_stands / 2), count = upper ? Math.ceil(b.ab_stands / 2) : Math.floor(b.ab_stands / 2);
|
||||||
|
add("A:B" + (n + 1), spread(upper ? n : n - Math.ceil(b.ab_stands / 2), count, 440, 600), upper ? 215 : 332, upper ? 180 : 0, "A" + (n + 1));
|
||||||
|
}
|
||||||
|
for (let n = 0; n < b.b_stands; n++)
|
||||||
|
add("B:B" + (n + 1), spread(n, b.b_stands, 410, 638), n % 2 ? 371 : 176, 90, "B" + (n + 1));
|
||||||
|
for (let n = 0; n < b.ac_stands; n++) {
|
||||||
|
const x = spread(n, b.ac_stands, 116, 258);
|
||||||
|
add("A:C" + (n + 1), x, 260, 0, "A" + (n + 1));
|
||||||
|
add("C:C" + (n + 1), x, 311, 180, "C" + (n + 1));
|
||||||
|
}
|
||||||
|
for (const lane of b.runways) {
|
||||||
|
const upper = lane === "31R";
|
||||||
|
add("V1:" + lane, 834, upper ? 231 : 317, 90, "VIP1");
|
||||||
|
add("V2:" + lane, 914, upper ? 231 : 317, 90, "VIP2");
|
||||||
|
}
|
||||||
|
return points;
|
||||||
|
}
|
||||||
|
function runway(lane, weather) {
|
||||||
|
const y = laneY(lane);
|
||||||
|
const bars = Array.from({ length: 6 }, (_, i) => '<path d="M54 ' +
|
||||||
|
(y - 13 + i * 5) +
|
||||||
|
"h31 M1026 " +
|
||||||
|
(y - 13 + i * 5) +
|
||||||
|
'h-30"/>').join("");
|
||||||
|
const lights = Array.from({ length: 24 }, (_, i) => '<path d="M' + (44 + i * 43) + " " + (y - 22) + 'v2 m0 40v2"/>').join("");
|
||||||
|
return `<g><rect x="28" y="${y - 25}" width="1024" height="50" rx="5" fill="#687773" stroke="#92a492" stroke-width="5"/>
|
||||||
|
<rect x="34" y="${y - 19}" width="1012" height="38" fill="url(#asphalt)" stroke="#c5cdc0" stroke-width="1.4"/>
|
||||||
|
<g stroke="#ecebdd" stroke-width="2.6">${bars}<path d="M171 ${y}H920" stroke-dasharray="20 16"/></g>
|
||||||
|
<path d="M225 ${y - 10}h35 m0 20h-35 M785 ${y - 10}h35 m0 20h-35" stroke="#d1d7cb" stroke-width="4"/>
|
||||||
|
<g stroke="#e5dfad" stroke-width="3">${lights}</g>
|
||||||
|
<text x="106" y="${y + 8}" class="rw-number">${lane}</text>
|
||||||
|
${weather === lane || weather === "FG" ? '<path d="M930 ' + (y - 12) + 'l23 24m0 -24l-23 24" stroke="#ff9c64" stroke-width="5"/>' : ""}</g>`;
|
||||||
|
}
|
||||||
|
const fieldDefs = `<defs>
|
||||||
|
<pattern id="grass" width="21" height="17" patternUnits="userSpaceOnUse"><rect width="21" height="17" fill="#9aa780"/><path d="M2 3h4m8 7h3m-8 4h3" stroke="#718765" stroke-width=".9" opacity=".38"/></pattern>
|
||||||
|
<pattern id="roof" width="8" height="8" patternUnits="userSpaceOnUse"><rect width="8" height="8" fill="#c5d3cb"/><path d="M1 0v8" stroke="#a3b8ad"/></pattern>
|
||||||
|
<pattern id="asphalt" width="23" height="16" patternUnits="userSpaceOnUse"><rect width="23" height="16" fill="#515e60"/><path d="M0 0h23m-17 0v16" stroke="#657073" stroke-width=".7"/></pattern>
|
||||||
|
<pattern id="apron" width="30" height="28" patternUnits="userSpaceOnUse"><rect width="30" height="28" fill="#bdc4ae"/><path d="M0 28V0h30" fill="none" stroke="#9ca896" stroke-width="1.4"/></pattern>
|
||||||
|
<g id="tree"><path d="M-6 4l1-8 4-5 6 2 4 6-3 7-7 1z" fill="#546f54"/><path d="M-6 1l1-7 5-4 5 3 1 6-5 5z" fill="#71885e"/><path d="M-4-4l4-4 3 3" fill="#889967"/></g>
|
||||||
|
<g id="vent"><rect width="12" height="9" rx="1" fill="#82988d"/><circle cx="6" cy="4.5" r="3" fill="#a5b5a9" stroke="#506a62"/><path d="M3 4.5h6m-3-3v6" stroke="#657d72"/></g>
|
||||||
|
<g id="jet1"><path d="M0-15Q3-13 2-2L14 1v3L2 3l-1 8 5 3v2l-6-2-6 2v-2l5-3-1-8-12 1V1l12-3Q-3-13 0-15Z"/></g>
|
||||||
|
<g id="jet2"><path d="M0-19Q3-18 3-6L19 4v4L3 3l-1 10 6 4v2l-8-3-8 3v-2l6-4-1-10-16 5V4L-3-6Q-3-18 0-19Z"/><path d="M-9-2v7m18-7v7" stroke-width="3"/></g>
|
||||||
|
<g id="jet3"><path d="M0-22Q4-20 3.8-7L23 4v5L4 4l-2 11 8 5v3l-10-4-10 4v-3l8-5-2-11-19 5V4L-3.8-7Q-4-20 0-22Z"/><path d="M-15 0v7m7-10v8m16-8v8m7-5v7" stroke-width="3.6"/></g>
|
||||||
|
</defs>`;
|
||||||
|
function building(x, y, w, h) {
|
||||||
|
const vents = Array.from({ length: Math.max(1, Math.floor(w / 44)) }, (_, i) => `<use href="#vent" x="${x + 8 + 35 * i}" y="${y + 5}"/>`).join("");
|
||||||
|
return `<g><rect x="${x + 4}" y="${y + 5}" width="${w}" height="${h}" rx="3" fill="#54685c" opacity=".5"/>
|
||||||
|
<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="3" fill="url(#roof)" stroke="#667d72" stroke-width="2"/>
|
||||||
|
<path d="M${x + 4} ${y + h - 3}h${w - 8}" stroke="#73979a" stroke-width="4" stroke-dasharray="8 3"/>${vents}</g>`;
|
||||||
|
}
|
||||||
|
function apronEquipment() {
|
||||||
|
const carts = (x, y, angle) => `<g transform="translate(${x} ${y}) rotate(${angle})"><path d="M0 0h28" stroke="#58675b" stroke-width="2"/>
|
||||||
|
<rect x="-3" y="-3" width="8" height="6" rx="1" fill="#bc7643" stroke="#687168"/><path d="M1-2v4" stroke="#cbdfe0"/>
|
||||||
|
${[9, 18, 27].map((x) => `<rect x="${x}" y="-2.6" width="6" height="5" rx=".7" fill="#d6d4bb" stroke="#677269" stroke-width=".8"/>`).join("")}</g>`;
|
||||||
|
const hatches = Array.from({ length: 9 }, (_, i) => `<path d="M${383 + i * 7} 294l6-8 M${591 + i * 7} 248l6-8"/>`).join("");
|
||||||
|
return `<g fill="none" stroke="#f7f3d5" stroke-width="1.1">${hatches}
|
||||||
|
<path d="M374 239h33v26h-33z M662 249h22v59h-22z" stroke-dasharray="4 3"/>
|
||||||
|
<path d="M95 240h183 M95 329h183" stroke="#c9a651" stroke-width="2"/></g>
|
||||||
|
${carts(374, 317, 0)}${carts(626, 288, 90)}${carts(786, 299, -90)}
|
||||||
|
<g transform="translate(701 289)"><ellipse cx="6" cy="10" rx="10" ry="3" fill="#899980"/>
|
||||||
|
<path d="M0 9v-25" stroke="#53675b" stroke-width="2"/><path d="M0-17l18 3-2 4-16-1z" fill="#ce693d" stroke="#765f47"/><path d="M5-16v5m6-4v4" stroke="#fff3d5" stroke-width="2.5"/></g>
|
||||||
|
<g transform="translate(287 348)"><path d="M-4 13l2-22h5l3 22z" fill="#d4ddd1" stroke="#6d8278"/><path d="M-7-12h15l-2 6h-11z" fill="#76959a" stroke="#4a6360"/><path d="M-8-12l3-3h11l3 3z" fill="#c5cfc2"/></g>`;
|
||||||
|
}
|
||||||
|
function terrain(points) {
|
||||||
|
let seed = 49075;
|
||||||
|
function rand() {
|
||||||
|
seed = (1664525 * seed + 1013904223) >>> 0;
|
||||||
|
return seed / 4294967296;
|
||||||
|
}
|
||||||
|
const trees = [
|
||||||
|
[45, 172, 34, 202],
|
||||||
|
[65, 91, 265, 22],
|
||||||
|
[69, 447, 270, 18],
|
||||||
|
[383, 96, 200, 15],
|
||||||
|
[361, 442, 214, 12],
|
||||||
|
[1012, 187, 31, 161],
|
||||||
|
]
|
||||||
|
.map(([x, y, w, h]) => Array.from({ length: Math.ceil((w * h) / 180) }, () => `<use href="#tree" transform="translate(${Math.round(x + rand() * w)} ${Math.round(y + rand() * h)}) scale(${(0.48 + rand() * 0.48).toFixed(2)})"/>`).join(""))
|
||||||
|
.join("");
|
||||||
|
const routes = [
|
||||||
|
"M91 129H938Q987 129 987 90V57",
|
||||||
|
"M91 419H938Q987 419 987 458V491",
|
||||||
|
"M91 129Q72 129 72 151V397Q72 419 91 419",
|
||||||
|
"M350 129V419",
|
||||||
|
"M350 176H680Q722 176 752 129",
|
||||||
|
"M350 371H680Q722 371 752 419",
|
||||||
|
"M776 129Q758 170 758 202V342Q758 374 776 419",
|
||||||
|
"M758 231H914Q955 231 955 265V283Q955 317 914 317H758",
|
||||||
|
];
|
||||||
|
for (const [id, p] of Object.entries(points)) {
|
||||||
|
if (id.startsWith("A:B"))
|
||||||
|
routes.push(`M${p.x} ${p.y}V${p.y < 274 ? 176 : 371}`);
|
||||||
|
if (id.startsWith("A:C"))
|
||||||
|
routes.push(`M${p.x} 129V419`);
|
||||||
|
}
|
||||||
|
const line = routes.map((d) => `<path d="${d}"/>`).join("");
|
||||||
|
const apron = '<path d="M89 156H302L320 177V365L298 389H89Z M364 162H670L710 196V350L676 382H364Z M778 192H926L969 221V321L935 351H778Z" fill="url(#apron)" stroke="#a2ac95" stroke-width="3"/>';
|
||||||
|
const fingers = Object.entries(points)
|
||||||
|
.filter(([k]) => k.startsWith("A:B"))
|
||||||
|
.map(([, p]) => {
|
||||||
|
const top = p.y < 274, y = top ? 235 : 296;
|
||||||
|
return `<g><path d="M${p.x + 10} ${top ? 252 : 296}v${top ? -13 : 12}l-9 ${top ? -7 : 7}" stroke="#667e75" stroke-width="8" fill="none"/><rect x="${p.x - 5}" y="${top ? y - 8 : y + 12}" width="10" height="9" fill="#e1e4d4" stroke="#748777"/></g>`;
|
||||||
|
})
|
||||||
|
.join("");
|
||||||
|
return `<rect width="${width}" height="${height}" fill="url(#grass)"/><path d="M-30 125L370 0H615L-10 187ZM483 548L1080 342V399L671 548Z" fill="#b1b58a" opacity=".38"/>
|
||||||
|
${trees}${apron}<g fill="none" stroke-linecap="round" stroke-linejoin="round"><g stroke="#798879" stroke-width="23">${line}</g><g stroke="#a9b1a2" stroke-width="19">${line}</g><g stroke="#e4cd7e" stroke-width="1.7">${line}</g></g>
|
||||||
|
${apronEquipment()}${fingers}${building(399, 251, 259, 45)}${building(441, 244, 114, 16)}
|
||||||
|
<text x="533" y="281" class="roof-title" text-anchor="middle">ТЕРМИНАЛ</text>
|
||||||
|
${building(805, 259, 99, 36)}<text x="857" y="285" text-anchor="middle" class="roof-title">VIP</text>
|
||||||
|
${building(239, 179, 45, 27)}${building(286, 312, 28, 55)}${building(350, 254, 23, 41)}
|
||||||
|
<path d="M98 226h177m-177 114h177" stroke="#e4dfba" stroke-width="2" stroke-dasharray="4 5"/>
|
||||||
|
<text x="180" y="209" text-anchor="middle" class="ground-title">ПЕРРОН A / C</text>
|
||||||
|
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
function cardBays(v) {
|
||||||
|
const items = [
|
||||||
|
["ПОГОДА", v.piles?.weather ?? "—"],
|
||||||
|
["КОЛОДА", String(v.piles?.deck ?? "—")],
|
||||||
|
["СБРОС", v.piles?.discard ?? "—"],
|
||||||
|
];
|
||||||
|
return items
|
||||||
|
.map(([label, value], i) => `<g transform="translate(${107 + 132 * i} 91)"><rect x="2" y="2" width="119" height="24" rx="3" fill="#4f6554"/>
|
||||||
|
<rect width="119" height="24" rx="3" fill="#d9dfc9" stroke="#657860"/>
|
||||||
|
<path d="M6 5h12v14H6zm2-2h12v14" fill="none" stroke="#6c806a"/>
|
||||||
|
<text x="24" y="16" class="bay-name">${label}</text><text x="111" y="16" text-anchor="end" class="bay-value">${value}</text></g>`)
|
||||||
|
.join("");
|
||||||
|
}
|
||||||
|
export function airfield(v) {
|
||||||
|
const pts = geometry(v.geometry);
|
||||||
|
const markers = Object.entries(pts)
|
||||||
|
.map(([id, p]) => {
|
||||||
|
const m = v.markers[id], dest = v.destinations.has(id), canPick = m && v.pickable.has(m.key);
|
||||||
|
const picked = !!m && m.key === v.selected;
|
||||||
|
const title = m ? m.name + " · " + p.label : p.label + " · " + id;
|
||||||
|
const action = canPick ? "pick" : dest ? "mapdest" : "";
|
||||||
|
const attr = action
|
||||||
|
? `role="button" tabindex="0" data-act="${action}" data-val="${canPick ? m.key : id}"`
|
||||||
|
: "";
|
||||||
|
const label = p.label === "D" ? "СТАРТ" : p.label;
|
||||||
|
return `<g transform="translate(${p.x} ${p.y})" data-position="${id}" class="map-slot ${dest ? "legal" : ""} ${picked ? "picked" : ""}" ${attr} aria-label="${title}"><title>${title}</title><circle r="24" fill="transparent"/>
|
||||||
|
<circle class="spot" r="${m ? 18 : 14}" fill="${id.startsWith("D") ? "#f1d977" : "#e7e8d6"}" fill-opacity=".93" stroke="#465b51" stroke-width="1.8"/>
|
||||||
|
${dest || picked ? '<circle class="focus-ring" r="21" fill="none" stroke="' + (picked ? "#fff" : "#075842") + '" stroke-width="3" stroke-dasharray="5 3"/>' : ""}
|
||||||
|
${m
|
||||||
|
? `<use href="#jet${m.size}" transform="rotate(${p.angle})" fill="${m.color}" stroke="#26382e" stroke-linejoin="round" stroke-width="1.2"/>
|
||||||
|
<rect x="-20" y="18" width="40" height="15" rx="4" fill="#233d33"/><text y="29" class="jet-id">${m.caption}</text>`
|
||||||
|
: `<text y="4" class="spot-label">${label}</text>`}</g>`;
|
||||||
|
})
|
||||||
|
.join("");
|
||||||
|
return `<svg class="airfield" viewBox="0 0 ${width} ${height}" xmlns="http://www.w3.org/2000/svg" role="group" aria-label="Аэродром, полосы 31R и 31L, терминал и стоянки">${fieldDefs}${terrain(pts)}${v.geometry.runways.map((l) => runway(l, v.weather)).join("")}${markers}${cardBays(v)}</svg>`;
|
||||||
|
}
|
||||||
+1014
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,152 @@
|
|||||||
|
const faces = {
|
||||||
|
A: [
|
||||||
|
"Подготовка к вылету",
|
||||||
|
"Boarding",
|
||||||
|
"movement",
|
||||||
|
"Выведите борт из ангара на свободную стоянку A.",
|
||||||
|
],
|
||||||
|
B: [
|
||||||
|
"Буксировка и запуск",
|
||||||
|
"Push and Start",
|
||||||
|
"movement",
|
||||||
|
"Переведите борт с обычной стоянки A на свободную позицию B.",
|
||||||
|
],
|
||||||
|
C: [
|
||||||
|
"Запуск двигателей",
|
||||||
|
"Start Up",
|
||||||
|
"movement",
|
||||||
|
"На стоянке A/C переведите борт с позиции A на C.",
|
||||||
|
],
|
||||||
|
D: [
|
||||||
|
"Отправление на полосу",
|
||||||
|
"Departure",
|
||||||
|
"movement",
|
||||||
|
"Переведите борт с B или C в очередь выбранной ВПП.",
|
||||||
|
],
|
||||||
|
LC: [
|
||||||
|
"Счастливый капитан",
|
||||||
|
"Lucky Captain",
|
||||||
|
"special",
|
||||||
|
"Заменяет одну карту A, B, C или D при оплате движения.",
|
||||||
|
],
|
||||||
|
VIP: [
|
||||||
|
"Обслуживание VIP",
|
||||||
|
"VIP",
|
||||||
|
"special",
|
||||||
|
"Направьте один борт из ангара или с A, B, C на свободную ветку VIP.",
|
||||||
|
],
|
||||||
|
AI: [
|
||||||
|
"Противообледенительная обработка",
|
||||||
|
"Anti-Icing",
|
||||||
|
"special",
|
||||||
|
"При обледенении обработайте борт на старте. Нужно 1–3 карты по размеру.",
|
||||||
|
],
|
||||||
|
FLR: [
|
||||||
|
"Техническая неисправность",
|
||||||
|
"Failure",
|
||||||
|
"incident",
|
||||||
|
"Верните борт соперника с поля в ангар. При открытом доборе действует на свой борт.",
|
||||||
|
],
|
||||||
|
DLY: [
|
||||||
|
"Задержка рейса",
|
||||||
|
"Delay",
|
||||||
|
"incident",
|
||||||
|
"Возврат с A, B, C или VIP в ангар. При розыгрыше цель чужая, при обмене — своя.",
|
||||||
|
],
|
||||||
|
SC: [
|
||||||
|
"Чистое небо",
|
||||||
|
"Sky Clear",
|
||||||
|
"weather",
|
||||||
|
"Вылет разрешён всем типам самолётов с обеих полос.",
|
||||||
|
],
|
||||||
|
FG: [
|
||||||
|
"Туман",
|
||||||
|
"Fog",
|
||||||
|
"weather",
|
||||||
|
"Вылеты и продвижение очередей на обеих полосах приостановлены.",
|
||||||
|
],
|
||||||
|
SN: [
|
||||||
|
"Снег",
|
||||||
|
"Snow",
|
||||||
|
"weather",
|
||||||
|
"Движение стоит на карту больше. Широкофюзеляжные борта не взлетают.",
|
||||||
|
],
|
||||||
|
CW: [
|
||||||
|
"Боковой ветер",
|
||||||
|
"Crosswind",
|
||||||
|
"weather",
|
||||||
|
"Малым самолётам вылет запрещён. При очереди борт уступает старт.",
|
||||||
|
],
|
||||||
|
ICE: [
|
||||||
|
"Обледенение",
|
||||||
|
"Ice",
|
||||||
|
"weather",
|
||||||
|
"Для вылета требуется противообледенительная обработка.",
|
||||||
|
],
|
||||||
|
"31L": [
|
||||||
|
"Левая полоса закрыта",
|
||||||
|
"31L Closed",
|
||||||
|
"weather",
|
||||||
|
"Вылет и продвижение очереди на ВПП 31L приостановлены.",
|
||||||
|
],
|
||||||
|
"31R": [
|
||||||
|
"Правая полоса закрыта",
|
||||||
|
"31R Closed",
|
||||||
|
"weather",
|
||||||
|
"Вылет и продвижение очереди на ВПП 31R приостановлены.",
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const families = {
|
||||||
|
movement: "Движение",
|
||||||
|
weather: "Погода",
|
||||||
|
incident: "Неприятность",
|
||||||
|
special: "Специальная",
|
||||||
|
};
|
||||||
|
const line = (d) => '<path d="' + d + '"/>';
|
||||||
|
const cloud = '<path d="M28 31h32a7 7 0 0 0 0-14 12 12 0 0 0-22-2 8 8 0 1 0-10 16Z"/>';
|
||||||
|
const snowflake = line("M44 7v33m-14-25 28 17m0-17L30 32m10-22 4 4 4-4m0 27-4-4-4 4m-9-17 6-1-1-6m20 15-6 1 1 6m-20-7 6 1-1 6m20-15-6-1 1-6");
|
||||||
|
const nose = line("M20 28l31-5 16-9q7-2 3 4L57 31l-32 3-10-8 5-2z M43 24l-6-11 5-2 12 12");
|
||||||
|
const icons = {
|
||||||
|
A: line("M13 36h21l20-22h12v-5H51L29 31H13z M31 29h7m-2-7h8m-3-6h8 M19 32v-6") + '<circle cx="24" cy="39" r="3"/><circle cx="48" cy="34" r="3"/>',
|
||||||
|
B: line("M15 31v-9h10l4-8h12l4 11h9v7H15zm13-8h12l-3-6h-6z M55 28h11l8-11") +
|
||||||
|
'<circle cx="23" cy="33" r="4"/><circle cx="45" cy="33" r="4"/>',
|
||||||
|
C: '<circle cx="44" cy="24" r="17"/><circle cx="44" cy="24" r="4"/>' +
|
||||||
|
Array.from({ length: 8 }, (_, i) => `<path d="M45 20q8-4 6-9" transform="rotate(${45 * i} 44 24)"/>`).join(""),
|
||||||
|
D: nose + line("M12 40h58m-49-4 8-1m3-1 7-1"),
|
||||||
|
LC: line("M17 18l27-9 27 9-11 7-16-4-16 4z M29 26v5q13 10 30 0v-5 M36 24l8 3 8-3") + '<circle cx="44" cy="17" r="3"/>',
|
||||||
|
VIP: line("M20 14l12 7 12-12 12 12 12-7-5 20H25z M26 39h37") +
|
||||||
|
'<circle cx="44" cy="27" r="2"/>',
|
||||||
|
AI: line("M15 33h35v-8H35l-3-9H21v11h-6z M38 24l12-16 12 4-2 4-8-2-7 11 M65 16l7 3m-9 0 7 5m-10-3 5 7") + '<circle cx="23" cy="35" r="4"/><circle cx="43" cy="35" r="4"/>',
|
||||||
|
FLR: line("M26 37l17-16a12 12 0 0 1 15-14l-8 9 6 5 9-8a12 12 0 0 1-17 14L31 42Z"),
|
||||||
|
DLY: '<circle cx="44" cy="25" r="16"/>' +
|
||||||
|
line("M44 14v12l8 4m-12-25h8m-4 0v3 M22 17h-8m7 8H9m15 8H13"),
|
||||||
|
SC: '<circle cx="44" cy="24" r="9"/>' +
|
||||||
|
line("M44 4v6m0 28v6M24 24h6m28 0h6M30 10l4 4m20 20 4 4m0-28-4 4m-20 20-4 4"),
|
||||||
|
FG: cloud + line("M15 33h34m6 0h18m-52 5h44m-38 5h18m6 0h13"),
|
||||||
|
SN: cloud +
|
||||||
|
line("M33 35v7m-3-5 6 3m0-3-6 3m15-5v6m-3-4 6 2m0-2-6 2m15-6v7m-3-5 6 3m0-3-6 3"),
|
||||||
|
CW: line("M27 40V8m0 4 37 5-4 11-33-6z M39 14l-2 10m12-9-2 11m12-10-2 11 M14 15h7m-10 7h10m47 0h10"),
|
||||||
|
ICE: snowflake,
|
||||||
|
};
|
||||||
|
for (const code of ["31L", "31R"])
|
||||||
|
icons[code] =
|
||||||
|
line("M20 10h46v28H20z M25 13v22m36-22v22m-24-19 14 16m0-16L37 32") +
|
||||||
|
`<text x="73" y="36" fill="currentColor" stroke="none" font-size="12">${code.slice(-1)}</text>`;
|
||||||
|
export function cardLabel(code) {
|
||||||
|
return faces[code]?.[0] || code;
|
||||||
|
}
|
||||||
|
export function cardCaption(code) {
|
||||||
|
return code + " · " + cardLabel(code);
|
||||||
|
}
|
||||||
|
export function cardFace(code, index, selectable, selected) {
|
||||||
|
const [title, english, family, effect] = faces[code];
|
||||||
|
const tag = selectable ? "button" : "div";
|
||||||
|
const action = selectable
|
||||||
|
? `type="button" data-act="card" data-val="${index}" aria-pressed="${selected}"`
|
||||||
|
: "";
|
||||||
|
return `<${tag} class="flight-card fc-${family}${selected ? " chosen" : ""}" ${action} data-code="${code}">
|
||||||
|
<span class="fc-head"><b>${code}</b><span>${families[family]}</span></span>
|
||||||
|
<svg viewBox="0 0 88 48" aria-hidden="true" class="fc-art"><g stroke="currentColor" stroke-width="2" fill="none" stroke-linejoin="round" stroke-linecap="round">${icons[code]}</g></svg>
|
||||||
|
<span class="fc-title">${title}</span><span class="fc-en" lang="en">${english}</span>
|
||||||
|
<span class="fc-effect">${effect}</span></${tag}>`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
const cookieName = "vzlet_demo_v1";
|
||||||
|
let bridge;
|
||||||
|
async function createBridge() {
|
||||||
|
if (!navigator.serviceWorker)
|
||||||
|
throw Error("Откройте демо по HTTPS или через localhost.");
|
||||||
|
await navigator.serviceWorker.register("/cookie-worker.js");
|
||||||
|
await navigator.serviceWorker.ready;
|
||||||
|
if (!navigator.serviceWorker.controller)
|
||||||
|
await new Promise(resolve => navigator.serviceWorker.addEventListener("controllerchange", () => resolve(), { once: true }));
|
||||||
|
return new Promise(resolve => {
|
||||||
|
const frame = document.createElement("iframe");
|
||||||
|
frame.hidden = true;
|
||||||
|
frame.title = "Локальное сохранение";
|
||||||
|
frame.onload = () => resolve(frame);
|
||||||
|
frame.src = "/__local_game__/";
|
||||||
|
document.body.append(frame);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async function cookie(next = null) {
|
||||||
|
const frame = await (bridge ??= createBridge());
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const channel = new MessageChannel();
|
||||||
|
const timeout = setTimeout(() => { channel.port1.close(); reject(Error("Браузер заблокировал локальное сохранение")); }, 5000);
|
||||||
|
channel.port1.onmessage = ({ data }) => {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
channel.port1.close();
|
||||||
|
data.error ? reject(Error(data.error)) : resolve(data.value);
|
||||||
|
};
|
||||||
|
frame.contentWindow.postMessage(next, location.origin, [channel.port2]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let worker, version = "";
|
||||||
|
function run(input) {
|
||||||
|
if (!worker)
|
||||||
|
worker = new Worker("/worker.js");
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
worker.onmessage = ({ data }) => data.error ? reject(Error(data.error)) : resolve(data.result);
|
||||||
|
worker.onerror = () => { worker.terminate(); worker = null; reject(Error("Не удалось загрузить локальный движок")); };
|
||||||
|
worker.postMessage(input);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
export function current() { return cookie(); }
|
||||||
|
export async function play(opts = {}) {
|
||||||
|
if (!navigator.locks)
|
||||||
|
throw Error("Для локальной игры откройте сайт по HTTPS или через localhost.");
|
||||||
|
return navigator.locks.request(cookieName, async () => {
|
||||||
|
const saved = await cookie();
|
||||||
|
if (opts.command && saved !== version)
|
||||||
|
throw Error("Партия изменилась в другой вкладке. Обновите страницу.");
|
||||||
|
const result = await run({ token: opts.reset ? "" : saved, bots: opts.bots || 3, color: opts.color || null, command: opts.command ?? null });
|
||||||
|
await cookie(result.token);
|
||||||
|
version = result.token;
|
||||||
|
return result;
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||||
|
<meta name="theme-color" content="#153e36" />
|
||||||
|
<title>Взлёт разрешён! — Диспетчерская</title>
|
||||||
|
<link rel="stylesheet" href="/style.css" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header>
|
||||||
|
<a class="brand" href="#home"
|
||||||
|
><span class="mark" aria-hidden="true"></span>Взлёт разрешён! <small class="build-version" title="Версия сборки">v0.1.4</small></a
|
||||||
|
>
|
||||||
|
<nav>
|
||||||
|
<a href="#home">Диспетчерская</a><a href="#cards">Карты</a
|
||||||
|
><a href="#archive">Архив партий</a>
|
||||||
|
</nav>
|
||||||
|
</header>
|
||||||
|
<main id="app" aria-busy="true">Загрузка диспетчерской…</main>
|
||||||
|
<div id="notice" role="status"></div>
|
||||||
|
<script type="module" src="/app.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,807 @@
|
|||||||
|
* {
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
html {
|
||||||
|
font:
|
||||||
|
16px/1.45 "Inter",
|
||||||
|
"Segoe UI",
|
||||||
|
Arial,
|
||||||
|
sans-serif;
|
||||||
|
color: #192f2b;
|
||||||
|
background: #f4f3eb;
|
||||||
|
}
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
header {
|
||||||
|
height: 74px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
padding: 0 max(5vw, 20px);
|
||||||
|
border-bottom: 1px solid #c8d0c5;
|
||||||
|
background: #fafaf4;
|
||||||
|
}
|
||||||
|
a {
|
||||||
|
color: inherit;
|
||||||
|
}
|
||||||
|
.brand {
|
||||||
|
font-size: 21px;
|
||||||
|
font-weight: 800;
|
||||||
|
letter-spacing: -0.8px;
|
||||||
|
text-decoration: none;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
.mark {
|
||||||
|
height: 29px;
|
||||||
|
width: 32px;
|
||||||
|
background: repeating-linear-gradient(
|
||||||
|
113deg,
|
||||||
|
#ed7546 0 6px,
|
||||||
|
transparent 6px 9px
|
||||||
|
);
|
||||||
|
clip-path: polygon(0 100%, 55% 0, 100% 0, 65% 100%);
|
||||||
|
}
|
||||||
|
nav {
|
||||||
|
display: flex;
|
||||||
|
gap: 22px;
|
||||||
|
}
|
||||||
|
nav a {
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 650;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
nav a:hover,
|
||||||
|
a:hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
main {
|
||||||
|
max-width: 1320px;
|
||||||
|
margin: auto;
|
||||||
|
padding: 38px 5vw 72px;
|
||||||
|
}
|
||||||
|
h1,
|
||||||
|
h2,
|
||||||
|
h3,
|
||||||
|
p {
|
||||||
|
margin: 0 0 0.65em;
|
||||||
|
}
|
||||||
|
h1 {
|
||||||
|
font-size: clamp(35px, 5vw, 68px);
|
||||||
|
font-weight: 760;
|
||||||
|
letter-spacing: -0.062em;
|
||||||
|
line-height: 1.02;
|
||||||
|
}
|
||||||
|
h2 {
|
||||||
|
font-size: 25px;
|
||||||
|
letter-spacing: -0.045em;
|
||||||
|
}
|
||||||
|
h3 {
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
small,
|
||||||
|
.muted {
|
||||||
|
color: #526962;
|
||||||
|
}
|
||||||
|
.mono,
|
||||||
|
.eyebrow,
|
||||||
|
.tag,
|
||||||
|
th,
|
||||||
|
.runlabel,
|
||||||
|
.serial {
|
||||||
|
font-family: "IBM Plex Mono", Consolas, monospace;
|
||||||
|
}
|
||||||
|
.eyebrow,
|
||||||
|
.tag {
|
||||||
|
font-size: 11px;
|
||||||
|
letter-spacing: 0.1em;
|
||||||
|
text-transform: uppercase;
|
||||||
|
font-weight: 650;
|
||||||
|
}
|
||||||
|
.eyebrow {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 15px;
|
||||||
|
}
|
||||||
|
.homegrid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1.4fr) minmax(300px, 1fr);
|
||||||
|
gap: 18px;
|
||||||
|
}
|
||||||
|
.hero {
|
||||||
|
position: relative;
|
||||||
|
background: #163e35;
|
||||||
|
color: #f6f5e6;
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: clamp(24px, 4vw, 56px);
|
||||||
|
overflow: hidden;
|
||||||
|
min-height: 445px;
|
||||||
|
}
|
||||||
|
.hero .eyebrow {
|
||||||
|
color: #b4cebd;
|
||||||
|
}
|
||||||
|
.hero p {
|
||||||
|
max-width: 31em;
|
||||||
|
color: #dce7d9;
|
||||||
|
}
|
||||||
|
.diagram {
|
||||||
|
height: 160px;
|
||||||
|
position: relative;
|
||||||
|
overflow: hidden;
|
||||||
|
margin: 22px -9px 0;
|
||||||
|
background-image:
|
||||||
|
linear-gradient(#9fb8a61a 1px, transparent 1px),
|
||||||
|
linear-gradient(90deg, #9fb8a61a 1px, transparent 1px);
|
||||||
|
background-size: 19px 19px;
|
||||||
|
transform: skewY(-7deg);
|
||||||
|
}
|
||||||
|
.strip {
|
||||||
|
position: absolute;
|
||||||
|
left: 3%;
|
||||||
|
right: 3%;
|
||||||
|
height: 25px;
|
||||||
|
border: 1px solid #8da795;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 0 8px;
|
||||||
|
font: 11px monospace;
|
||||||
|
color: #e5e6ca;
|
||||||
|
}
|
||||||
|
.strip:after {
|
||||||
|
content: "";
|
||||||
|
flex: 1;
|
||||||
|
border-bottom: 2px dashed #c0cab1;
|
||||||
|
}
|
||||||
|
.strip:first-child {
|
||||||
|
top: 26px;
|
||||||
|
}
|
||||||
|
.strip:nth-child(2) {
|
||||||
|
bottom: 18px;
|
||||||
|
}
|
||||||
|
.taxi {
|
||||||
|
position: absolute;
|
||||||
|
top: 50px;
|
||||||
|
left: 22%;
|
||||||
|
width: 52%;
|
||||||
|
height: 68px;
|
||||||
|
border: 3px double #efa96b;
|
||||||
|
border-radius: 0 0 24px 16px;
|
||||||
|
transform: skewX(-29deg);
|
||||||
|
}
|
||||||
|
.panel {
|
||||||
|
background: #fffef8;
|
||||||
|
border: 1px solid #cbd3c7;
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 24px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.section {
|
||||||
|
margin-top: 32px;
|
||||||
|
}
|
||||||
|
.toolbar,
|
||||||
|
.controls,
|
||||||
|
.chips,
|
||||||
|
.row,
|
||||||
|
.hand {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 9px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
.toolbar {
|
||||||
|
justify-content: space-between;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
.toolbar h1,
|
||||||
|
.toolbar h2 {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
.controls {
|
||||||
|
margin: 14px 0;
|
||||||
|
}
|
||||||
|
fieldset {
|
||||||
|
border: 0;
|
||||||
|
padding: 0;
|
||||||
|
margin: 16px 0 20px;
|
||||||
|
}
|
||||||
|
legend,
|
||||||
|
label.caption {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
font-weight: 650;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
button,
|
||||||
|
select,
|
||||||
|
input {
|
||||||
|
font: inherit;
|
||||||
|
color: inherit;
|
||||||
|
}
|
||||||
|
button,
|
||||||
|
.btn,
|
||||||
|
select,
|
||||||
|
input {
|
||||||
|
border: 1px solid #b9c7ba;
|
||||||
|
background: #fafbf5;
|
||||||
|
border-radius: 6px;
|
||||||
|
padding: 8px 13px;
|
||||||
|
}
|
||||||
|
button,
|
||||||
|
.btn,
|
||||||
|
select {
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.btn {
|
||||||
|
text-decoration: none;
|
||||||
|
display: inline-block;
|
||||||
|
}
|
||||||
|
button:hover,
|
||||||
|
.btn:hover {
|
||||||
|
border-color: #285b4a;
|
||||||
|
background: #e7eee1;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
button:focus-visible,
|
||||||
|
a:focus-visible,
|
||||||
|
input:focus-visible,
|
||||||
|
select:focus-visible {
|
||||||
|
outline: 3px solid #e8773c;
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
button:disabled {
|
||||||
|
cursor: default;
|
||||||
|
opacity: 0.5;
|
||||||
|
}
|
||||||
|
.selected,
|
||||||
|
.selected:hover {
|
||||||
|
background: #dceadc;
|
||||||
|
border-color: #246645;
|
||||||
|
box-shadow: inset 0 0 0 1px #246645;
|
||||||
|
}
|
||||||
|
.primary,
|
||||||
|
.primary:hover {
|
||||||
|
background: #f18551;
|
||||||
|
border-color: #f18551;
|
||||||
|
color: #1b2724;
|
||||||
|
font-weight: 750;
|
||||||
|
padding: 12px 22px;
|
||||||
|
}
|
||||||
|
.wide {
|
||||||
|
width: 100%;
|
||||||
|
margin-top: 7px;
|
||||||
|
}
|
||||||
|
.dot {
|
||||||
|
width: 12px;
|
||||||
|
height: 12px;
|
||||||
|
display: inline-block;
|
||||||
|
border-radius: 100%;
|
||||||
|
margin-right: 6px;
|
||||||
|
}
|
||||||
|
.tag {
|
||||||
|
background: #e3ebdf;
|
||||||
|
border-radius: 4px;
|
||||||
|
padding: 5px 7px;
|
||||||
|
display: inline-block;
|
||||||
|
}
|
||||||
|
.board {
|
||||||
|
background: #193f35;
|
||||||
|
color: #f4f5e8;
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 24px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.board h2 {
|
||||||
|
font-size: 23px;
|
||||||
|
}
|
||||||
|
.board small {
|
||||||
|
color: #c0cebd;
|
||||||
|
}
|
||||||
|
.runway {
|
||||||
|
border: 1px solid #729081;
|
||||||
|
border-radius: 5px;
|
||||||
|
padding: 9px;
|
||||||
|
margin: 9px 0;
|
||||||
|
background: #295046;
|
||||||
|
}
|
||||||
|
.runlabel {
|
||||||
|
font-weight: 700;
|
||||||
|
color: #eee5b4;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
.slots {
|
||||||
|
display: flex;
|
||||||
|
gap: 4px;
|
||||||
|
align-items: stretch;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
margin-top: 6px;
|
||||||
|
}
|
||||||
|
.slot {
|
||||||
|
min-width: 28px;
|
||||||
|
min-height: 24px;
|
||||||
|
padding: 3px 5px;
|
||||||
|
border: 1px solid #789385;
|
||||||
|
border-radius: 3px;
|
||||||
|
font: 12px/1.5 monospace;
|
||||||
|
color: #f6f3de;
|
||||||
|
}
|
||||||
|
.empty {
|
||||||
|
border-style: dashed;
|
||||||
|
color: #b7cbbc;
|
||||||
|
}
|
||||||
|
.plane {
|
||||||
|
background: #fbfaf1;
|
||||||
|
color: #202d27;
|
||||||
|
border-left: 4px solid var(--c);
|
||||||
|
font: 600 12px monospace;
|
||||||
|
padding: 5px;
|
||||||
|
display: inline-block;
|
||||||
|
border-radius: 3px;
|
||||||
|
}
|
||||||
|
.standrow {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
padding: 5px 0;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
.standrow b {
|
||||||
|
font-size: 13px;
|
||||||
|
min-width: 44px;
|
||||||
|
}
|
||||||
|
.card {
|
||||||
|
min-width: 44px;
|
||||||
|
text-align: center;
|
||||||
|
background: #f8f5e9;
|
||||||
|
border: 1px solid #c9c8b3;
|
||||||
|
border-top: 4px solid #54846d;
|
||||||
|
padding: 9px 6px;
|
||||||
|
border-radius: 5px;
|
||||||
|
font: bold 14px monospace;
|
||||||
|
}
|
||||||
|
.hand {
|
||||||
|
gap: 5px;
|
||||||
|
}
|
||||||
|
.pay {
|
||||||
|
font: 13px monospace;
|
||||||
|
}
|
||||||
|
.log {
|
||||||
|
padding-left: 1.4em;
|
||||||
|
}
|
||||||
|
.log li {
|
||||||
|
margin: 0.4em 0;
|
||||||
|
}
|
||||||
|
.choices {
|
||||||
|
max-height: 295px;
|
||||||
|
overflow: auto;
|
||||||
|
display: grid;
|
||||||
|
gap: 6px;
|
||||||
|
margin: 8px 0;
|
||||||
|
}
|
||||||
|
.choices button {
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
.ledger {
|
||||||
|
display: grid;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
.entry {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
background: #fffef7;
|
||||||
|
border: 1px solid #c9d1c6;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 16px;
|
||||||
|
}
|
||||||
|
.entry small {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
table {
|
||||||
|
border-collapse: collapse;
|
||||||
|
width: 100%;
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
th,
|
||||||
|
td {
|
||||||
|
text-align: left;
|
||||||
|
padding: 8px;
|
||||||
|
border-bottom: 1px solid #d1d8cd;
|
||||||
|
}
|
||||||
|
th {
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
.scroll {
|
||||||
|
overflow-x: auto;
|
||||||
|
}
|
||||||
|
#notice {
|
||||||
|
position: fixed;
|
||||||
|
bottom: 16px;
|
||||||
|
left: 50%;
|
||||||
|
transform: translateX(-50%);
|
||||||
|
background: #203e34;
|
||||||
|
color: #fff;
|
||||||
|
padding: 9px 16px;
|
||||||
|
border-radius: 6px;
|
||||||
|
display: none;
|
||||||
|
z-index: 3;
|
||||||
|
}
|
||||||
|
#notice.show {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
.range {
|
||||||
|
width: 100%;
|
||||||
|
accent-color: #2d6851;
|
||||||
|
}
|
||||||
|
.serial {
|
||||||
|
font-size: 12px;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.selector {
|
||||||
|
display: grid;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
.selector select {
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
.sub {
|
||||||
|
font-size: 13px;
|
||||||
|
color: #536c5e;
|
||||||
|
}
|
||||||
|
.space {
|
||||||
|
margin-top: 14px;
|
||||||
|
}
|
||||||
|
@media (max-width: 800px) {
|
||||||
|
main {
|
||||||
|
padding: 20px 14px 62px;
|
||||||
|
}
|
||||||
|
.homegrid {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
.hero {
|
||||||
|
min-height: unset;
|
||||||
|
}
|
||||||
|
.diagram {
|
||||||
|
height: 125px;
|
||||||
|
}
|
||||||
|
.taxi {
|
||||||
|
height: 37px;
|
||||||
|
}
|
||||||
|
header {
|
||||||
|
height: auto;
|
||||||
|
padding: 15px;
|
||||||
|
gap: 10px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
nav {
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
.board,
|
||||||
|
.panel {
|
||||||
|
padding: 17px;
|
||||||
|
}
|
||||||
|
.entry {
|
||||||
|
align-items: flex-start;
|
||||||
|
}
|
||||||
|
.toolbar {
|
||||||
|
align-items: flex-start;
|
||||||
|
}
|
||||||
|
.section {
|
||||||
|
margin-top: 20px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.slot.allowed {
|
||||||
|
background: #e7edb4;
|
||||||
|
color: #193d35;
|
||||||
|
border: 1px solid #eff5af;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Vector board and printed card faces */
|
||||||
|
.home-field {
|
||||||
|
margin: 24px -22px -32px;
|
||||||
|
overflow: hidden;
|
||||||
|
border: 5px solid #7c9681;
|
||||||
|
border-radius: 6px;
|
||||||
|
box-shadow: 0 12px 35px #12271d55;
|
||||||
|
transform: rotate(-3deg);
|
||||||
|
}
|
||||||
|
.home-field .airfield {
|
||||||
|
width: 100%;
|
||||||
|
height: auto;
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
.tablegrid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1fr);
|
||||||
|
gap: 16px;
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
.tablegrid select {max-width: 100%}
|
||||||
|
@media (min-width: 960px) {
|
||||||
|
main:has(.tablegrid) {
|
||||||
|
max-width: 1920px;
|
||||||
|
padding: 24px clamp(18px, 2vw, 40px) 60px;
|
||||||
|
}
|
||||||
|
.tablegrid {
|
||||||
|
grid-template-columns: minmax(0, 3fr) minmax(366px, 2fr);
|
||||||
|
gap: clamp(12px, 1.2vw, 24px);
|
||||||
|
}
|
||||||
|
.tablegrid > .panel {padding: clamp(14px, 1.2vw, 24px)}
|
||||||
|
.tablegrid .flight-hand {
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(min(100%, 126px), 1fr));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.map-panel {
|
||||||
|
overflow: hidden;
|
||||||
|
border-radius: 12px;
|
||||||
|
border: 1px solid #b8c5b4;
|
||||||
|
background: #1f4037;
|
||||||
|
min-width: 0;
|
||||||
|
color: #f0f3e7;
|
||||||
|
}
|
||||||
|
.map-heading {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75em;
|
||||||
|
padding: 12px 18px;
|
||||||
|
}
|
||||||
|
.map-heading h2 {
|
||||||
|
font-size: 21px;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
.map-zoom {
|
||||||
|
font-size: 13px;
|
||||||
|
background: #34554a;
|
||||||
|
color: #fff;
|
||||||
|
border-color: #779281;
|
||||||
|
}
|
||||||
|
.map-zoom:hover {
|
||||||
|
background: #496a5e;
|
||||||
|
}
|
||||||
|
.map-window {
|
||||||
|
overflow: auto;
|
||||||
|
overscroll-behavior-x: contain;
|
||||||
|
scrollbar-color: #96a88e #304c3b;
|
||||||
|
}
|
||||||
|
.map-window .airfield {
|
||||||
|
width: 100%;
|
||||||
|
height: auto;
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
.map-window.zoomed .airfield {
|
||||||
|
width: 150%;
|
||||||
|
min-width: 1000px;
|
||||||
|
}
|
||||||
|
.map-legend {
|
||||||
|
display: flex;
|
||||||
|
gap: 24px;
|
||||||
|
padding: 10px 18px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
.map-legend span {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
align-items: baseline;
|
||||||
|
}
|
||||||
|
.map-legend small {
|
||||||
|
color: #c9d7c4;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
.map-legend b {
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
.airfield text {
|
||||||
|
font-family: Consolas, "Liberation Mono", monospace;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
.rw-number {
|
||||||
|
font-size: 26px;
|
||||||
|
font-weight: bold;
|
||||||
|
fill: #f3f2e5;
|
||||||
|
letter-spacing: 1px;
|
||||||
|
}
|
||||||
|
.ground-title {
|
||||||
|
font-size: 10px;
|
||||||
|
letter-spacing: 2px;
|
||||||
|
font-weight: bold;
|
||||||
|
fill: #3e5744;
|
||||||
|
}
|
||||||
|
.roof-title {
|
||||||
|
font-size: 12px;
|
||||||
|
letter-spacing: 2px;
|
||||||
|
font-weight: bold;
|
||||||
|
fill: #3b514b;
|
||||||
|
}
|
||||||
|
.spot-label,
|
||||||
|
.jet-id {
|
||||||
|
font-weight: 700;
|
||||||
|
text-anchor: middle;
|
||||||
|
fill: #2a372d;
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
.jet-id {
|
||||||
|
fill: white;
|
||||||
|
font-size: 11px;
|
||||||
|
}
|
||||||
|
.map-slot[data-act] {
|
||||||
|
cursor: pointer;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
.map-slot[data-act]:hover .spot,
|
||||||
|
.map-slot[data-act]:focus-visible .spot {
|
||||||
|
stroke: #fff;
|
||||||
|
stroke-width: 4;
|
||||||
|
}
|
||||||
|
.map-slot.legal .spot {
|
||||||
|
fill: #e8ffb0;
|
||||||
|
stroke: #1d6146;
|
||||||
|
}
|
||||||
|
.flight-hand {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(136px, 1fr));
|
||||||
|
gap: 8px;
|
||||||
|
align-items: stretch;
|
||||||
|
margin: 8px 0 16px;
|
||||||
|
}
|
||||||
|
.flight-card {
|
||||||
|
--ink: #275744;
|
||||||
|
--wash: #e2ecdb;
|
||||||
|
position: relative;
|
||||||
|
min-width: 0;
|
||||||
|
display: flex;
|
||||||
|
align-items: stretch;
|
||||||
|
flex-direction: column;
|
||||||
|
text-align: left;
|
||||||
|
border-radius: 7px;
|
||||||
|
padding: 9px 10px 11px;
|
||||||
|
border: 1px solid #b5bfac;
|
||||||
|
border-top: 4px solid var(--ink);
|
||||||
|
background: #fffdf2;
|
||||||
|
color: #192f27;
|
||||||
|
box-shadow: 0 2px 0 #cbd0bd;
|
||||||
|
}
|
||||||
|
.fc-weather {
|
||||||
|
--ink: #375e75;
|
||||||
|
--wash: #dfebeb;
|
||||||
|
}
|
||||||
|
.fc-incident {
|
||||||
|
--ink: #924e39;
|
||||||
|
--wash: #f1e1cd;
|
||||||
|
}
|
||||||
|
.fc-special {
|
||||||
|
--ink: #695476;
|
||||||
|
--wash: #eae3ed;
|
||||||
|
}
|
||||||
|
.fc-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 3px;
|
||||||
|
font-size: 10px;
|
||||||
|
color: var(--ink);
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
.fc-head b {
|
||||||
|
font:
|
||||||
|
700 17px/1.1 Consolas,
|
||||||
|
monospace;
|
||||||
|
}
|
||||||
|
.fc-art {
|
||||||
|
height: 39px;
|
||||||
|
width: 100%;
|
||||||
|
margin: 7px 0;
|
||||||
|
background: repeating-linear-gradient(
|
||||||
|
125deg,
|
||||||
|
var(--wash) 0 9px,
|
||||||
|
#fff7 9px 10px,
|
||||||
|
var(--wash) 10px 19px
|
||||||
|
);
|
||||||
|
border-radius: 3px;
|
||||||
|
color: var(--ink);
|
||||||
|
}
|
||||||
|
.fc-title {
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 740;
|
||||||
|
line-height: 1.2;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
hyphens: auto;
|
||||||
|
}
|
||||||
|
.fc-en {
|
||||||
|
font-size: 11px;
|
||||||
|
color: var(--ink);
|
||||||
|
margin-top: 3px;
|
||||||
|
}
|
||||||
|
.fc-effect {
|
||||||
|
display: block;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.35;
|
||||||
|
margin-top: 8px;
|
||||||
|
padding-top: 7px;
|
||||||
|
border-top: 1px solid #d9ddce;
|
||||||
|
color: #394d40;
|
||||||
|
}
|
||||||
|
button.flight-card:hover {
|
||||||
|
background: #fff9de;
|
||||||
|
border-color: var(--ink);
|
||||||
|
}
|
||||||
|
button.flight-card.chosen {
|
||||||
|
outline: 3px solid #29724e;
|
||||||
|
outline-offset: -2px;
|
||||||
|
background: #e9f1d8;
|
||||||
|
}
|
||||||
|
button.flight-card.chosen .fc-art {
|
||||||
|
box-shadow: inset 0 0 0 1px #4f865f;
|
||||||
|
}
|
||||||
|
.selector select {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
@media (min-width: 1050px) {
|
||||||
|
.flight-hand {
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(144px, 1fr));
|
||||||
|
}
|
||||||
|
.homegrid {
|
||||||
|
align-items: stretch;
|
||||||
|
}
|
||||||
|
.hero {
|
||||||
|
padding-bottom: 40px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@media (max-width: 800px) {
|
||||||
|
.map-window .airfield {
|
||||||
|
min-width: 620px;
|
||||||
|
}
|
||||||
|
.map-window.zoomed .airfield {
|
||||||
|
min-width: 1000px;
|
||||||
|
}
|
||||||
|
.map-heading,
|
||||||
|
.map-legend {
|
||||||
|
padding: 10px 12px;
|
||||||
|
}
|
||||||
|
.map-legend {
|
||||||
|
gap: 6px 15px;
|
||||||
|
}
|
||||||
|
.flight-hand {
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(122px, 1fr));
|
||||||
|
}
|
||||||
|
.home-field {
|
||||||
|
margin: 16px -5px -5px;
|
||||||
|
}
|
||||||
|
.map-panel,
|
||||||
|
.tablegrid > .panel {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.bay-name {
|
||||||
|
font-size: 11px;
|
||||||
|
letter-spacing: 0.6px;
|
||||||
|
fill: #405744;
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
.bay-value {
|
||||||
|
font-size: 12px;
|
||||||
|
fill: #193e31;
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
@media (max-width: 800px) {
|
||||||
|
.map-window:not(.zoomed) .airfield {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.map-window.zoomed {
|
||||||
|
max-height: 68vh;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.build-version { font: 600 12px/1.2 Consolas, monospace; color: #455f55; letter-spacing: 0; white-space: nowrap; }
|
||||||
|
|
||||||
|
.danger{color:#883725;border-color:#b58d80}.archive-tools:empty{display:none}.ledger .entry{flex-wrap:wrap}
|
||||||
|
|
||||||
|
.hangar {padding: .85rem 1rem; border-top: 1px solid #acb9ad}
|
||||||
|
.hangar h3,.hangar p {margin: 0}
|
||||||
|
.hangar ul {display:flex;flex-wrap:wrap;gap:.4rem;margin:.5rem 0 0;padding:0;list-style:none}
|
||||||
|
.hangar li {display:flex;align-items:center;gap:.3rem;border:1px solid #acb9ad;border-radius:.3rem;padding:.2rem .45rem;font-size:.8rem}
|
||||||
|
.hangar svg {width:2rem;height:2rem;stroke:currentColor;stroke-width:.7}
|
||||||
|
|
||||||
|
.replay-step {width:6em}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
"""The same transactional store contract on PostgreSQL and local SQLite."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
import zlib
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def pack(obj):
|
||||||
|
return zlib.compress(
|
||||||
|
json.dumps(obj, ensure_ascii=False, separators=(",", ":")).encode(), 3
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def unpack(blob):
|
||||||
|
return json.loads(zlib.decompress(blob))
|
||||||
|
|
||||||
|
|
||||||
|
class Database:
|
||||||
|
def __init__(self):
|
||||||
|
self.dsn = os.getenv("DATABASE_URL")
|
||||||
|
if not self.dsn and os.getenv("DB_PASSWORD_FILE"):
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
password = Path(os.environ["DB_PASSWORD_FILE"]).read_text().strip()
|
||||||
|
user = quote(os.environ["POSTGRES_USER"], safe="")
|
||||||
|
dbname = quote(os.environ["POSTGRES_DB"], safe="")
|
||||||
|
self.dsn = f"postgresql://{user}:{quote(password, safe='')}@db/{dbname}"
|
||||||
|
self.path = os.getenv("SQLITE_PATH", "dispatch.sqlite3")
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def transaction(self, write=False):
|
||||||
|
if self.dsn:
|
||||||
|
import psycopg
|
||||||
|
|
||||||
|
con = psycopg.connect(self.dsn)
|
||||||
|
if not write:
|
||||||
|
con.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY")
|
||||||
|
else:
|
||||||
|
con = sqlite3.connect(self.path, timeout=30)
|
||||||
|
con.execute("PRAGMA foreign_keys=ON")
|
||||||
|
con.execute("BEGIN IMMEDIATE" if write else "BEGIN")
|
||||||
|
|
||||||
|
def run(sql, args=()):
|
||||||
|
return con.execute(sql.replace("?", "%s") if self.dsn else sql, args)
|
||||||
|
|
||||||
|
try:
|
||||||
|
yield run
|
||||||
|
con.commit()
|
||||||
|
except BaseException:
|
||||||
|
con.rollback()
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
con.close()
|
||||||
|
|
||||||
|
def init(self):
|
||||||
|
if not self.dsn:
|
||||||
|
with sqlite3.connect(self.path) as c:
|
||||||
|
c.execute("PRAGMA journal_mode=WAL")
|
||||||
|
sql = Path(__file__).with_name("001_initial.sql").read_text()
|
||||||
|
with self.transaction(True) as run:
|
||||||
|
for stmt in sql.split(";"):
|
||||||
|
if stmt.strip():
|
||||||
|
run(stmt)
|
||||||
|
|
||||||
|
def row(self, run, gid, owner=None, lock=False):
|
||||||
|
sql = "SELECT owner,version,state,seq FROM games WHERE id=?"
|
||||||
|
args = [gid]
|
||||||
|
if owner is not None:
|
||||||
|
sql += " AND owner=?"
|
||||||
|
args.append(owner)
|
||||||
|
if lock and self.dsn:
|
||||||
|
sql += " FOR UPDATE"
|
||||||
|
return run(sql, args).fetchone()
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
"""Stateless worker. Inputs consist exclusively of the acting seat's view."""
|
||||||
|
|
||||||
|
from collections import Counter
|
||||||
|
|
||||||
|
|
||||||
|
def permitted(weather, size, lane):
|
||||||
|
return weather not in ("FG", "ICE", lane) and (weather, size) not in (
|
||||||
|
("CW", 1),
|
||||||
|
("SN", 3),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def decide(request):
|
||||||
|
v, commands = request["view"], request["actions"]
|
||||||
|
seat = v["seat"]
|
||||||
|
planes = v["planes"]
|
||||||
|
stock = Counter(v["hand"])
|
||||||
|
remaining = Counter(p["owner"] for p in planes.values() if p["pos"] != "F")
|
||||||
|
heads = [
|
||||||
|
(p, p["pos"].split(":")[1])
|
||||||
|
for p in planes.values()
|
||||||
|
if p["pos"].startswith("D:") and p["pos"].endswith(":0")
|
||||||
|
]
|
||||||
|
|
||||||
|
def evaluate(cmd):
|
||||||
|
kind = cmd["kind"]
|
||||||
|
p = planes.get(cmd.get("plane"), {})
|
||||||
|
if kind == "runway":
|
||||||
|
lane, position = cmd["to"].split(":")[1:]
|
||||||
|
return 100 - int(position) * 4 + 3 * permitted(
|
||||||
|
v["weather"], p["size"], lane
|
||||||
|
), "Выбор полосы по очереди и погоде"
|
||||||
|
if kind == "choose":
|
||||||
|
return 100, "Выбор среди равноценных целей обязательной неприятности"
|
||||||
|
if kind == "ice":
|
||||||
|
return 125, "Обработка позволяет вылететь сейчас"
|
||||||
|
if kind == "weather":
|
||||||
|
new, old = cmd["cards"][0], v["weather"]
|
||||||
|
gain = sum(
|
||||||
|
(1 if q["owner"] == seat else -0.28)
|
||||||
|
* (
|
||||||
|
int(permitted(new, q["size"], lane))
|
||||||
|
- int(permitted(old, q["size"], lane))
|
||||||
|
)
|
||||||
|
for q, lane in heads
|
||||||
|
)
|
||||||
|
return (
|
||||||
|
10 + gain * 95,
|
||||||
|
"Изменение доступности вылета на исполнительных стартах",
|
||||||
|
)
|
||||||
|
if kind == "attack":
|
||||||
|
st = p["pos"].split(":")[0]
|
||||||
|
advance = {"D": 50, "V2": 30, "V1": 20, "B": 22, "C": 22, "A": 12}[st]
|
||||||
|
return 10 + advance + 58 / remaining[
|
||||||
|
p["owner"]
|
||||||
|
], "Возврат продвинутого борта соперника в ангар"
|
||||||
|
if kind == "move":
|
||||||
|
target = cmd["to"].split(":")
|
||||||
|
base = {"D": 82, "V1": 77, "B": 64, "C": 64, "A": 48}[target[0]]
|
||||||
|
if target[0] == "D":
|
||||||
|
base -= int(target[-1]) * 4
|
||||||
|
base += 3 * permitted(v["weather"], p["size"], target[1])
|
||||||
|
if target[0] == "V1":
|
||||||
|
base += 3 * p["size"]
|
||||||
|
return base - cmd["cards"].count(
|
||||||
|
"LC"
|
||||||
|
) * 2, "Продвижение к старту с учётом очереди, размера и цены"
|
||||||
|
return 26, "Обмен для пополнения руки картами движения"
|
||||||
|
|
||||||
|
ranking = []
|
||||||
|
for cmd in commands:
|
||||||
|
score, reason = evaluate(cmd)
|
||||||
|
if cmd["kind"] == "exchange":
|
||||||
|
|
||||||
|
def keep(c):
|
||||||
|
return {
|
||||||
|
"LC": 10,
|
||||||
|
"VIP": 11,
|
||||||
|
"D": 7,
|
||||||
|
"A": 7,
|
||||||
|
"B": 5,
|
||||||
|
"C": 5,
|
||||||
|
"FLR": 6,
|
||||||
|
"AI": 3,
|
||||||
|
}.get(c, 2) - stock[c] * 0.7
|
||||||
|
|
||||||
|
cards = sorted(v["hand"], key=lambda c: (keep(c), c))
|
||||||
|
cmd = dict(
|
||||||
|
kind="exchange",
|
||||||
|
cards=cards[: min(4, max(1, sum(keep(c) < 5 for c in cards)))],
|
||||||
|
)
|
||||||
|
ranking.append(dict(command=cmd, score=round(score, 2), reason=reason))
|
||||||
|
ranking.sort(key=lambda item: -item["score"])
|
||||||
|
return dict(command=ranking[0]["command"], alternatives=ranking[:3])
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
from fastapi import FastAPI
|
||||||
|
from .strategy import decide
|
||||||
|
|
||||||
|
app = FastAPI(docs_url=None, redoc_url=None)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/health")
|
||||||
|
def health():
|
||||||
|
return {"ready": True}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/decide")
|
||||||
|
def evaluate(payload: dict):
|
||||||
|
return decide(payload)
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
httpx==0.28.1
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
fastapi==0.165.0 --hash=sha256:896f48462042bb4f162147eb8fac7e858753dc1f486765709baf105d70e4fc5b
|
||||||
|
uvicorn==0.54.0 --hash=sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf
|
||||||
|
psycopg==3.3.9 --hash=sha256:d2d7d04a1ce6dab4f5b27316bea3b52585cafa2f2d631e5b09dd69823f5c26f6
|
||||||
|
psycopg-binary==3.3.9 --hash=sha256:66b20619acbd434e4e46d734a915768a1192db09754c2ad041d391d72f30e5eb --hash=sha256:a99f0b9a19ed7a56bf5d6776456b8f15f5364db8853b0f5d184db394a45c391d --hash=sha256:b081348d8992af26e9b252f04876c286428418a6b7845d8d4caae2044b259668 --hash=sha256:e7e2e3543ac17cf5bb3eaf738606fc52bcedf993500b9fc8c55a4475a3731ef9
|
||||||
|
annotated-doc==0.0.7 --hash=sha256:6bc31bbbec6dfaaedc1676dbc11dbda96fe22a2b5c400e9ebad113fec44a9dc6
|
||||||
|
anyio==4.16.0 --hash=sha256:c66ae634e0b8228396b801741beb3294326d4b6102f7bba4041c0dfb58c29026
|
||||||
|
click==8.5.1 --hash=sha256:8bb5376d2006950386f8c6427613334a2acadc5f559cb80e638d00b4df957e37
|
||||||
|
h11==0.16.0 --hash=sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86
|
||||||
|
idna==3.20 --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c
|
||||||
|
opentelemetry-api==1.45.2 --hash=sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34
|
||||||
|
pydantic==2.14.4 --hash=sha256:653a2ad9f6d8858529c77c72717d0ea991d6c6837fe683246b2f4b2bbfc3fadc
|
||||||
|
pydantic_core==2.50.5 --hash=sha256:004c784d4642bd1112a9fa9a022543aa17793fd32004f7e903ee97df2086bad4 --hash=sha256:07a62d44515d674d750cfd86b7ce1dd93111be870f378d7c27b37aeb78d0cb4a --hash=sha256:30988977d38909df645183a9869a9d12211485639ac4757de18585f0ccb6f3dc --hash=sha256:43a6eaee9eeac4a54f2ff6567e1b0ec51651b37a40d862cab2e6fd16109e6528 --hash=sha256:470bbc2495367f60d3ca849a8039e4c164701d10637e7743f4427d92651bdb6d --hash=sha256:7dfc0431e94659ae8449303ca4fb1588dc1e00282d6636d00d72bb4bd6459b4d --hash=sha256:fa66340c6d3e08a276803812e7665312dfc75dd24eedfa8e09f18a0f8e3e0e8f
|
||||||
|
annotated-types==0.8.0 --hash=sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0
|
||||||
|
starlette==1.10.0 --hash=sha256:478c0ab3b4ced6e82719849c118fa406f0278a3499c1a898cd15cd31bdc38ce4
|
||||||
|
typing_extensions==4.16.0 --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8
|
||||||
|
typing-inspection==0.4.5 --hash=sha256:bc210535442b39e1bf2805e0c7a17dfd6a4ace760c84c7f7d16245d23a6b1c39
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
import random
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
import uuid
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from game import api, engine
|
||||||
|
from game.store import Database
|
||||||
|
from game.strategy import decide
|
||||||
|
|
||||||
|
|
||||||
|
class Contract(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.folder = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self.folder.cleanup)
|
||||||
|
store = Database()
|
||||||
|
store.dsn = None
|
||||||
|
store.path = str(Path(self.folder.name) / "games.db")
|
||||||
|
mock = patch.object(api, "db", store)
|
||||||
|
mock.start()
|
||||||
|
self.addCleanup(mock.stop)
|
||||||
|
store.init()
|
||||||
|
self.c = TestClient(api.app)
|
||||||
|
self.addCleanup(self.c.close)
|
||||||
|
self.c.get("/api/games")
|
||||||
|
new_game = engine.new_game
|
||||||
|
|
||||||
|
def fixture(bots, color):
|
||||||
|
state = new_game(bots, color, random.Random(42))
|
||||||
|
state["active"] = 0
|
||||||
|
return state
|
||||||
|
|
||||||
|
with patch.object(engine, "new_game", fixture):
|
||||||
|
response = self.c.post("/api/games", json={"bots": 3, "color": "red"})
|
||||||
|
self.assertEqual(response.status_code, 201)
|
||||||
|
self.url = "/api/games/" + response.json()["id"]
|
||||||
|
|
||||||
|
def test_private_views(self):
|
||||||
|
v = self.c.get(self.url).json()["view"]
|
||||||
|
self.assertNotIn("hands", v)
|
||||||
|
self.assertNotIn("deck", v)
|
||||||
|
self.assertEqual(self.c.get(self.url + "/export").status_code, 403)
|
||||||
|
self.assertEqual(
|
||||||
|
self.c.get(self.url + "/replay?perspective=full").status_code, 403
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
self.c.get(self.url + "/replay?perspective=1").status_code, 403
|
||||||
|
)
|
||||||
|
other = TestClient(api.app)
|
||||||
|
self.addCleanup(other.close)
|
||||||
|
self.assertEqual(other.get(self.url).status_code, 404)
|
||||||
|
self.assertEqual(other.get("/api/games").json(), [])
|
||||||
|
|
||||||
|
def test_competing_requests_and_restart(self):
|
||||||
|
s = self.c.get(self.url).json()
|
||||||
|
cmd = decide(s)["command"]
|
||||||
|
base = dict(command=cmd, expected_version=s["version"])
|
||||||
|
packets = [dict(**base, command_id=str(uuid.uuid4())) for _ in range(2)]
|
||||||
|
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||||
|
answers = list(
|
||||||
|
pool.map(lambda p: self.c.post(self.url + "/commands", json=p), packets)
|
||||||
|
)
|
||||||
|
self.assertEqual(sorted(r.status_code for r in answers), [200, 409])
|
||||||
|
i = next(i for i, r in enumerate(answers) if r.status_code == 200)
|
||||||
|
self.assertEqual(
|
||||||
|
self.c.post(self.url + "/commands", json=packets[i]).json(),
|
||||||
|
answers[i].json(),
|
||||||
|
)
|
||||||
|
changed = {**packets[i], "command": {"kind": "bad"}}
|
||||||
|
self.assertEqual(
|
||||||
|
self.c.post(self.url + "/commands", json=changed).status_code, 409
|
||||||
|
)
|
||||||
|
new_store = Database()
|
||||||
|
new_store.dsn = None
|
||||||
|
new_store.path = api.db.path
|
||||||
|
with patch.object(api, "db", new_store):
|
||||||
|
new_store.init()
|
||||||
|
self.assertEqual(self.c.get(self.url).json()["version"], s["version"] + 1)
|
||||||
|
|
||||||
|
def test_archive_step_privacy(self):
|
||||||
|
doc = self.c.get("/api/reference/export").json()
|
||||||
|
ev = next(r for r in doc["events"] if r["kind"] == "decision")
|
||||||
|
for eye in ["full", str(ev["data"]["seat"]), "0"]:
|
||||||
|
r = self.c.get(
|
||||||
|
"/api/reference/replay", params={"perspective": eye, "seq": ev["seq"]}
|
||||||
|
).json()
|
||||||
|
self.assertEqual("hands" in r["view"], eye == "full")
|
||||||
|
self.assertEqual(
|
||||||
|
"alternatives" in r["timeline"][r["seq"] - 1]["data"], eye != "0"
|
||||||
|
)
|
||||||
|
self.assertTrue(all(not x["data"] for x in r["timeline"][r["seq"] :]))
|
||||||
|
if eye == "full":
|
||||||
|
self.assertEqual(r["view"]["deck"], list(reversed(ev["state"]["deck"])))
|
||||||
|
self.assertEqual(doc["events"][-1]["kind"], "winner")
|
||||||
|
|
||||||
|
def test_archive_cleanup(self):
|
||||||
|
def create():
|
||||||
|
return self.c.post("/api/games",json={"bots":3}).json()["id"]
|
||||||
|
done, other_done, active = create(),create(),create()
|
||||||
|
foreign = TestClient(api.app)
|
||||||
|
self.addCleanup(foreign.close)
|
||||||
|
foreign_id = foreign.post("/api/games", json={"bots":4}).json()["id"]
|
||||||
|
active2 = self.url.split("/")[-1]
|
||||||
|
with api.db.transaction(True) as run:
|
||||||
|
for gid in (done,other_done,foreign_id):
|
||||||
|
run("UPDATE games SET winner=0,next_actor=NULL WHERE id=?", (gid,))
|
||||||
|
run("INSERT INTO commands VALUES (?,?,?,?)",(gid,"test","{}","{}"))
|
||||||
|
def remove(ids,active=False):
|
||||||
|
return self.c.post("/api/archive/remove",json={"ids":ids,"allow_active":active})
|
||||||
|
self.assertEqual(remove([done,active],True).status_code,422)
|
||||||
|
self.assertEqual(remove([done,done,other_done,foreign_id,active]).json(),{"removed":2})
|
||||||
|
self.assertEqual(remove([done]).json(),{"removed":0})
|
||||||
|
self.assertEqual(remove([foreign_id], True).json(),{"removed":0})
|
||||||
|
self.assertEqual(remove([active],True).json(),{"removed":1})
|
||||||
|
with api.db.transaction() as run:
|
||||||
|
for table,col in (("events","game_id"),("commands","game_id"),("games","id")):
|
||||||
|
self.assertEqual(run(f"SELECT COUNT(*) FROM {table} WHERE {col} IN (?,?,?)",
|
||||||
|
(done,other_done,active)).fetchone()[0],0)
|
||||||
|
self.assertGreater(run(f"SELECT COUNT(*) FROM {table} WHERE {col}=?",(foreign_id,)).fetchone()[0],0)
|
||||||
|
self.assertEqual([g["id"] for g in self.c.get("/api/games").json()],[active2])
|
||||||
|
self.assertEqual(self.c.get("/api/reference/replay").status_code,200)
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
"""Round-trip a local game at every decision, including pending choices."""
|
||||||
|
import random
|
||||||
|
import sys
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.extend([str(ROOT / "game"), str(ROOT / "demo")])
|
||||||
|
import local_game as local
|
||||||
|
|
||||||
|
|
||||||
|
class BrowserSave(unittest.TestCase):
|
||||||
|
def test_resumes_with_same_decisions(self):
|
||||||
|
for bots in (3, 4, 5):
|
||||||
|
rng = random.Random(bots)
|
||||||
|
game = local.e.new_game(bots, rng=rng)
|
||||||
|
for _ in range(3000):
|
||||||
|
token = local.encode(game)
|
||||||
|
self.assertLess(len(token), 3500)
|
||||||
|
restored = local.decode(token)
|
||||||
|
self.assertEqual(token, local.encode(restored))
|
||||||
|
self.assertEqual(local.e.actions(game), local.e.actions(restored))
|
||||||
|
if game["winner"] is not None:
|
||||||
|
break
|
||||||
|
view = local.e.observation(game, local.e.actor(game))
|
||||||
|
choice = local.decide(dict(view=view, actions=local.e.actions(game)))
|
||||||
|
local.e.Turn(game, lambda *_: None, rng).apply(choice["command"])
|
||||||
|
self.assertIsNotNone(game["winner"])
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
import copy
|
||||||
|
import random
|
||||||
|
import unittest
|
||||||
|
from collections import Counter
|
||||||
|
|
||||||
|
from game import engine as e
|
||||||
|
from game.strategy import decide
|
||||||
|
|
||||||
|
|
||||||
|
class Rules(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.rng = random.Random(215)
|
||||||
|
self.s = e.new_game(3, "purple", self.rng)
|
||||||
|
self.s["active"] = 0
|
||||||
|
self.log = []
|
||||||
|
self.t = e.Turn(self.s, lambda s, k, d: self.log.append((k, d)), self.rng)
|
||||||
|
self.own = [key for key, p in self.s["planes"].items() if p["owner"] == 0]
|
||||||
|
|
||||||
|
def test_setup_and_full_games(self):
|
||||||
|
for bots in (3, 4, 5):
|
||||||
|
s = e.new_game(bots, rng=self.rng)
|
||||||
|
self.assertEqual(len(s["deck"]), 146 - (bots + 1) * 9)
|
||||||
|
self.assertEqual(len(set(s["colors"])), bots + 1)
|
||||||
|
|
||||||
|
def audit(state, kind, data):
|
||||||
|
cards = [*state["deck"], *state["discard"]]
|
||||||
|
for h in state["hands"]:
|
||||||
|
cards.extend(h)
|
||||||
|
cards.extend(x for x in (state["weather"], state["transit"]) if x)
|
||||||
|
self.assertEqual(Counter(cards), Counter(e.CAT["cards"]))
|
||||||
|
positions = [
|
||||||
|
p["pos"]
|
||||||
|
for p in state["planes"].values()
|
||||||
|
if p["pos"] not in ("H", "F")
|
||||||
|
]
|
||||||
|
self.assertEqual(len(positions), len(set(positions)))
|
||||||
|
|
||||||
|
while s["winner"] is None and s["turn"] < 1800:
|
||||||
|
cmd = decide(
|
||||||
|
dict(view=e.observation(s, e.actor(s)), actions=e.actions(s))
|
||||||
|
)["command"]
|
||||||
|
e.Turn(s, audit, self.rng).apply(cmd)
|
||||||
|
self.assertIsNotNone(s["winner"])
|
||||||
|
self.assertTrue(
|
||||||
|
all(
|
||||||
|
p["pos"] == "F"
|
||||||
|
for p in s["planes"].values()
|
||||||
|
if p["owner"] == s["winner"]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_snow_and_captain(self):
|
||||||
|
key = self.own[0]
|
||||||
|
self.s["planes"][key]["pos"] = "A:B1"
|
||||||
|
self.s["hands"][0] = ["B", "B", "LC", "LC"]
|
||||||
|
self.s["weather"] = "SN"
|
||||||
|
cmd = dict(kind="move", plane=key, to="B:B1", cards=["B", "B", "LC"])
|
||||||
|
prev = copy.deepcopy(self.s)
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
self.t.apply(cmd)
|
||||||
|
self.assertEqual(prev, self.s)
|
||||||
|
cmd["cards"].append("LC")
|
||||||
|
self.t.apply(cmd)
|
||||||
|
self.assertEqual(self.s["planes"][key]["pos"], "B:B1")
|
||||||
|
|
||||||
|
def test_exchange_pauses_then_continues(self):
|
||||||
|
s = self.s
|
||||||
|
for i, key in enumerate(self.own[:2]):
|
||||||
|
s["planes"][key]["pos"] = "A:B" + str(i + 1)
|
||||||
|
s["deck"].extend(["B", "DLY", "A", "FG"])
|
||||||
|
self.t.apply(dict(kind="exchange", cards=s["hands"][0][:2]))
|
||||||
|
self.assertEqual(e.actor(s), 1)
|
||||||
|
self.assertEqual(s["deck"][-1], "B")
|
||||||
|
self.assertEqual(s["owed"], 1)
|
||||||
|
self.assertEqual(s["weather"], "FG")
|
||||||
|
self.assertEqual(len(e.actions(s)), 2)
|
||||||
|
self.t.apply(e.actions(s)[0])
|
||||||
|
self.assertEqual(s["known"][0], {"A": 1, "B": 1})
|
||||||
|
self.assertEqual(s["planes"][self.own[0]]["pos"], "H")
|
||||||
|
self.assertEqual(s["turn"], 2)
|
||||||
|
|
||||||
|
def test_private_draw(self):
|
||||||
|
self.s["hands"][0] = ["SC"] * 7 + ["A", "A"]
|
||||||
|
self.s["deck"].extend(["FG", "DLY", "ICE"])
|
||||||
|
self.t.apply(dict(kind="weather", cards=["SC"]))
|
||||||
|
self.assertEqual(self.s["weather"], "SC")
|
||||||
|
self.assertIn("ICE", self.s["hands"][0])
|
||||||
|
self.assertEqual(self.s["known"][0], {})
|
||||||
|
|
||||||
|
def test_vip_and_runway_choice(self):
|
||||||
|
key = self.own[0]
|
||||||
|
s = self.s
|
||||||
|
s["hands"][0][0] = "VIP"
|
||||||
|
self.t.apply(dict(kind="move", plane=key, to="V1:31L", cards=["VIP"]))
|
||||||
|
self.assertEqual(s["planes"][key]["pos"], "V1:31L")
|
||||||
|
s["active"] = 0
|
||||||
|
self.t.finish()
|
||||||
|
self.assertEqual(s["planes"][key]["pos"], "V2:31L")
|
||||||
|
s["active"] = 0
|
||||||
|
self.t.finish()
|
||||||
|
self.assertTrue(s["pending"])
|
||||||
|
self.t.apply(dict(kind="runway", plane=key, to="D:31R:0"))
|
||||||
|
self.assertEqual(s["planes"][key]["pos"], "D:31R:0")
|
||||||
|
s["active"] = 0
|
||||||
|
self.t.finish()
|
||||||
|
self.assertEqual(s["planes"][key]["pos"], "F")
|
||||||
|
|
||||||
|
def test_two_takeoffs_and_no_chain(self):
|
||||||
|
for key, pos in zip(self.own, ["D:31L:0", "D:31R:0", "D:31R:1"]):
|
||||||
|
self.s["planes"][key]["pos"] = pos
|
||||||
|
self.t.finish()
|
||||||
|
self.assertEqual(
|
||||||
|
[self.s["planes"][k]["pos"] for k in self.own[:3]], ["F", "F", "D:31R:0"]
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_crosswind_snow_ice_and_closed(self):
|
||||||
|
for weather in ["FG", "31L", "CW", "SN", "ICE", "SC"]:
|
||||||
|
for size in (1, 2, 3):
|
||||||
|
s = copy.deepcopy(self.s)
|
||||||
|
head, follower = self.own[:2]
|
||||||
|
s["planes"][head].update(pos="D:31L:0", size=size)
|
||||||
|
s["planes"][follower]["pos"] = "D:31L:1"
|
||||||
|
s["weather"] = weather
|
||||||
|
e.Turn(s, lambda *args: None).finish()
|
||||||
|
expected = (
|
||||||
|
"D:31L:0"
|
||||||
|
if weather in ("FG", "31L")
|
||||||
|
else "D:31L:1"
|
||||||
|
if weather == "ICE" or (weather, size) in (("CW", 1), ("SN", 3))
|
||||||
|
else "F"
|
||||||
|
)
|
||||||
|
self.assertEqual(s["planes"][head]["pos"], expected)
|
||||||
|
self.s["weather"] = "ICE"
|
||||||
|
for n, lane in enumerate(e.LANES):
|
||||||
|
self.s["planes"][self.own[n]]["pos"] = f"D:{lane}:0"
|
||||||
|
self.s["hands"][0] = ["AI"] * 9
|
||||||
|
self.t.apply(dict(kind="ice", plane=self.own[0], cards=["AI"] * 3))
|
||||||
|
self.assertEqual(self.s["planes"][self.own[1]]["pos"], "D:31R:0")
|
||||||
|
|
||||||
|
def test_invisible_redistribution(self):
|
||||||
|
s = self.s
|
||||||
|
for pending in [None, dict(seat=1, card="DLY", targets=self.own[:2])]:
|
||||||
|
s["pending"] = pending
|
||||||
|
seat = e.actor(s)
|
||||||
|
other = (seat + 1) % len(s["hands"])
|
||||||
|
altered = copy.deepcopy(s)
|
||||||
|
altered["deck"].reverse()
|
||||||
|
h = altered["hands"][other]
|
||||||
|
h[0], altered["deck"][-1] = altered["deck"][-1], h[0]
|
||||||
|
|
||||||
|
def req(game):
|
||||||
|
return dict(view=e.observation(game, seat), actions=e.actions(game))
|
||||||
|
|
||||||
|
self.assertEqual(req(s), req(altered))
|
||||||
|
self.assertEqual(decide(req(s)), decide(req(altered)))
|
||||||
|
|
||||||
|
def test_blocked_stand_and_frozen_queue(self):
|
||||||
|
key = self.own[0]
|
||||||
|
self.s["planes"][key]["pos"] = "C:C1"
|
||||||
|
self.s["hands"][0] = ["A"] * 9
|
||||||
|
self.assertFalse(any(c.get("to") == "A:C1" for c in e.actions(self.s)))
|
||||||
|
self.s["weather"] = "FG"
|
||||||
|
self.s["planes"][key]["pos"] = "D:31L:2"
|
||||||
|
self.t.compact()
|
||||||
|
self.assertEqual(e.tail(self.s, "31L"), "D:31L:3")
|
||||||
|
self.t.weather("SC")
|
||||||
|
self.assertEqual(self.s["planes"][key]["pos"], "D:31L:0")
|
||||||
|
|
||||||
|
def test_attack_targets_and_refill(self):
|
||||||
|
enemy = next(k for k, p in self.s["planes"].items() if p["owner"] == 1)
|
||||||
|
self.s["planes"][enemy]["pos"] = "D:31L:0"
|
||||||
|
self.s["hands"][0] = ["DLY", "FLR"] + ["A"] * 7
|
||||||
|
commands = e.actions(self.s)
|
||||||
|
flr = dict(kind="attack", plane=enemy, cards=["FLR"])
|
||||||
|
self.assertIn(flr, commands)
|
||||||
|
self.assertNotIn(dict(kind="attack", plane=enemy, cards=["DLY"]), commands)
|
||||||
|
self.t.apply(flr)
|
||||||
|
self.assertEqual(self.s["planes"][enemy]["pos"], "H")
|
||||||
|
self.s["active"] = 0
|
||||||
|
self.s["deck"] = ["A"]
|
||||||
|
self.s["discard"] = ["B", "B", "C"]
|
||||||
|
self.s["weather"] = "ICE"
|
||||||
|
self.t.apply(dict(kind="exchange", cards=["A", "A"]))
|
||||||
|
self.assertEqual(len(self.s["hands"][0]), 9)
|
||||||
|
self.assertEqual(self.s["weather"], "ICE")
|
||||||
|
self.assertIn("shuffle", [kind for kind, _ in self.log])
|
||||||
|
|
||||||
|
def test_closed_hand_can_hold_trouble_and_weather(self):
|
||||||
|
s = self.s
|
||||||
|
key = self.own[0]
|
||||||
|
s["hands"][0] = ["A"] * 9
|
||||||
|
s["deck"].extend(["FG", "DLY", "SN"])
|
||||||
|
self.t.apply(dict(kind="move", plane=key, to="A:B1", cards=["A"] * 3))
|
||||||
|
self.assertIsNone(s["weather"])
|
||||||
|
self.assertEqual(s["planes"][key]["pos"], "A:B1")
|
||||||
|
self.assertTrue({"FG", "DLY", "SN"}.issubset(s["hands"][0]))
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import test from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
import { airfield } from "../game/static/airfield.js";
|
||||||
|
import { cardFace } from "../game/static/cards.js";
|
||||||
|
|
||||||
|
const catalog = JSON.parse(
|
||||||
|
readFileSync(new URL("../game/catalog.json", import.meta.url)),
|
||||||
|
);
|
||||||
|
const empty = {
|
||||||
|
geometry: catalog.board,
|
||||||
|
markers: {},
|
||||||
|
selected: "",
|
||||||
|
pickable: new Set(),
|
||||||
|
destinations: new Set(),
|
||||||
|
weather: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
test("A labelled vector face exists for each card in the rules catalog", () => {
|
||||||
|
for (const code of Object.keys(catalog.cards)) {
|
||||||
|
const card = cardFace(code, 0, true, true);
|
||||||
|
assert.ok(card.includes('data-code="' + code + '"'));
|
||||||
|
for (const cls of ["fc-title", "fc-en", "fc-effect"])
|
||||||
|
assert.match(card, new RegExp('class="' + cls + '"[^>]*>[^<]+<'));
|
||||||
|
assert.match(card, /<svg[^>]*>.*<path/s);
|
||||||
|
assert.match(card, /aria-pressed="true"/);
|
||||||
|
assert.doesNotMatch(card, /undefined/);
|
||||||
|
assert.doesNotMatch(cardFace(code, 0, false, false), /data-act=/);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
test("Positions are unique and all six positions on each runway have a marker", () => {
|
||||||
|
const svg = airfield(empty);
|
||||||
|
const ids = Array.from(svg.matchAll(/data-position="([^"]+)"/g), (m) => m[1]);
|
||||||
|
assert.equal(ids.length, new Set(ids).size);
|
||||||
|
const b = catalog.board;
|
||||||
|
assert.equal(
|
||||||
|
ids.length,
|
||||||
|
b.ab_stands +
|
||||||
|
b.b_stands +
|
||||||
|
2 * b.ac_stands +
|
||||||
|
b.vip_lanes * 2 +
|
||||||
|
b.runways.length * b.queue_capacity,
|
||||||
|
);
|
||||||
|
for (const lane of b.runways)
|
||||||
|
for (let i = 0; i < b.queue_capacity; i++)
|
||||||
|
assert.ok(ids.includes("D:" + lane + ":" + i));
|
||||||
|
});
|
||||||
|
test("Only supplied targets are interactive; the preview is read-only", () => {
|
||||||
|
assert.doesNotMatch(airfield(empty), /data-act=/);
|
||||||
|
const svg = airfield({
|
||||||
|
...empty,
|
||||||
|
markers: {
|
||||||
|
"A:B2": {
|
||||||
|
key: "blue-1",
|
||||||
|
caption: "С1",
|
||||||
|
size: 3,
|
||||||
|
color: "#345",
|
||||||
|
name: "Синяя",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
pickable: new Set(["blue-1"]),
|
||||||
|
destinations: new Set(["B:B3"]),
|
||||||
|
selected: "blue-1",
|
||||||
|
});
|
||||||
|
assert.match(svg, /data-act="pick" data-val="blue-1"/);
|
||||||
|
assert.match(svg, /data-act="mapdest" data-val="B:B3"/);
|
||||||
|
assert.equal([...svg.matchAll(/data-act=/g)].length, 2);
|
||||||
|
assert.match(svg, /href="#jet3"/);
|
||||||
|
});
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
"""Verify and inspect a finished JSON export without a server or bot."""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import gzip
|
||||||
|
import json
|
||||||
|
from collections import Counter
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def verify(doc):
|
||||||
|
if doc.get("schema") != 1:
|
||||||
|
raise ValueError("Неизвестная версия экспорта")
|
||||||
|
events = doc["events"]
|
||||||
|
expected = Counter(doc["catalog"]["cards"])
|
||||||
|
if not events or events[0]["kind"] != "start" or events[-1]["kind"] != "winner":
|
||||||
|
raise ValueError("Нет начала или завершения партии")
|
||||||
|
previous_turn = 1
|
||||||
|
initial = events[0]["state"]
|
||||||
|
for seq, event in enumerate(events, 1):
|
||||||
|
s = event["state"]
|
||||||
|
if (
|
||||||
|
event["seq"] != seq
|
||||||
|
or event["turn"] != s["turn"]
|
||||||
|
or not previous_turn <= s["turn"] <= previous_turn + 1
|
||||||
|
):
|
||||||
|
raise ValueError(f"Нарушена последовательность на шаге {seq}")
|
||||||
|
previous_turn = s["turn"]
|
||||||
|
cards = Counter(s["deck"]) + Counter(s["discard"])
|
||||||
|
for hand in s["hands"]:
|
||||||
|
cards.update(hand)
|
||||||
|
cards.update(c for c in (s["weather"], s.get("transit")) if c)
|
||||||
|
if cards != expected:
|
||||||
|
raise ValueError(f"Состав колоды нарушен на шаге {seq}")
|
||||||
|
positions = [
|
||||||
|
p["pos"] for p in s["planes"].values() if p["pos"] not in ("H", "F")
|
||||||
|
]
|
||||||
|
if (
|
||||||
|
len(positions) != len(set(positions))
|
||||||
|
or s["planes"].keys() != initial["planes"].keys()
|
||||||
|
or s["catalog"] != doc["rules"]
|
||||||
|
or s["colors"] != initial["colors"]
|
||||||
|
):
|
||||||
|
raise ValueError(f"Некорректное поле или каталог на шаге {seq}")
|
||||||
|
winner = events[-1]["data"]["seat"]
|
||||||
|
if s["winner"] != winner or any(
|
||||||
|
p["pos"] != "F" for p in s["planes"].values() if p["owner"] == winner
|
||||||
|
):
|
||||||
|
raise ValueError("Результат не совпадает с состоянием флота")
|
||||||
|
return len(events), s["turn"], winner
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("file", type=Path)
|
||||||
|
parser.add_argument(
|
||||||
|
"--step", type=int, help="Вывести полный снимок указанного события"
|
||||||
|
)
|
||||||
|
args = parser.parse_args()
|
||||||
|
opener = gzip.open if args.file.suffix == ".gz" else open
|
||||||
|
try:
|
||||||
|
with opener(args.file, "rt", encoding="utf8") as stream:
|
||||||
|
doc = json.load(stream)
|
||||||
|
n, t, w = verify(doc)
|
||||||
|
print(
|
||||||
|
f"Проверено событий: {n}. Ходов: {t}. Победитель: {doc['events'][-1]['state']['colors'][w]}."
|
||||||
|
)
|
||||||
|
if args.step is not None:
|
||||||
|
if not 1 <= args.step <= n:
|
||||||
|
raise ValueError(f"Номер события должен быть от 1 до {n}")
|
||||||
|
print(
|
||||||
|
json.dumps(doc["events"][args.step - 1], ensure_ascii=False, indent=2)
|
||||||
|
)
|
||||||
|
except (ValueError, KeyError, IndexError, TypeError, OSError) as exc:
|
||||||
|
parser.exit(1, f"Ошибка проверки: {exc}\n")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Reference in new issue
Block a user