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