Initial
This commit is contained in:
commit
2ca7a264b3
53 files changed
+7113
No files matched your search
@@ -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)
|
||||
Reference in new issue
Block a user