This commit is contained in:
latypov committed 2026-11-23 23:55:37 +07:00
commit 2ca7a264b3
53 files changed
+7113

No files matched your search

+398
View File
@@ -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()