bgb-engine 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bgb_engine/__init__.py +63 -0
- bgb_engine/base.py +313 -0
- bgb_engine/examples/__init__.py +7 -0
- bgb_engine/examples/card_sample/__init__.py +5 -0
- bgb_engine/examples/card_sample/definition.py +308 -0
- bgb_engine/examples/graph_sample/__init__.py +5 -0
- bgb_engine/examples/graph_sample/definition.py +190 -0
- bgb_engine/examples/grid_sample/__init__.py +5 -0
- bgb_engine/examples/grid_sample/definition.py +312 -0
- bgb_engine/primitives/__init__.py +0 -0
- bgb_engine/primitives/counters.py +50 -0
- bgb_engine/primitives/graph.py +49 -0
- bgb_engine/primitives/grid.py +35 -0
- bgb_engine/primitives/pending.py +19 -0
- bgb_engine/primitives/phases.py +34 -0
- bgb_engine/primitives/projection.py +13 -0
- bgb_engine/primitives/rng.py +8 -0
- bgb_engine/primitives/turn.py +26 -0
- bgb_engine/primitives/zones.py +55 -0
- bgb_engine/py.typed +0 -0
- bgb_engine-0.1.0.dist-info/METADATA +92 -0
- bgb_engine-0.1.0.dist-info/RECORD +25 -0
- bgb_engine-0.1.0.dist-info/WHEEL +4 -0
- bgb_engine-0.1.0.dist-info/entry_points.txt +4 -0
- bgb_engine-0.1.0.dist-info/licenses/LICENSE +21 -0
bgb_engine/__init__.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""BoardGameBot Engine contracts, primitives and reference games."""
|
|
2
|
+
|
|
3
|
+
from .base import (Action, ActionOption, CardView, CellView, Context,
|
|
4
|
+
CounterView, GameDefinition, GraphEdgeView, GraphNodeView,
|
|
5
|
+
GraphView, GridView, IllegalAction, LogEntry, LogEntryView,
|
|
6
|
+
OutboxItem, Param, PendingRef, PendingSpec, PendingView,
|
|
7
|
+
RenderModel, SeatRef, SeatView, Setup, TokenView,
|
|
8
|
+
Transition, UpgradableRules, ZoneView)
|
|
9
|
+
from .primitives.counters import Counters
|
|
10
|
+
from .primitives.graph import BoardGraph
|
|
11
|
+
from .primitives.grid import BoardGrid
|
|
12
|
+
from .primitives.pending import for_seat, is_legal
|
|
13
|
+
from .primitives.phases import PhaseMachine
|
|
14
|
+
from .primitives.projection import hand_view
|
|
15
|
+
from .primitives.rng import rng_for
|
|
16
|
+
from .primitives.turn import TurnOrder
|
|
17
|
+
from .primitives.zones import Card, extract, find, shuffled, take
|
|
18
|
+
|
|
19
|
+
__version__ = '0.1.0'
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
'Action',
|
|
23
|
+
'ActionOption',
|
|
24
|
+
'BoardGraph',
|
|
25
|
+
'BoardGrid',
|
|
26
|
+
'Card',
|
|
27
|
+
'CardView',
|
|
28
|
+
'CellView',
|
|
29
|
+
'Context',
|
|
30
|
+
'CounterView',
|
|
31
|
+
'Counters',
|
|
32
|
+
'GameDefinition',
|
|
33
|
+
'GraphEdgeView',
|
|
34
|
+
'GraphNodeView',
|
|
35
|
+
'GraphView',
|
|
36
|
+
'GridView',
|
|
37
|
+
'IllegalAction',
|
|
38
|
+
'LogEntry',
|
|
39
|
+
'LogEntryView',
|
|
40
|
+
'OutboxItem',
|
|
41
|
+
'Param',
|
|
42
|
+
'PendingRef',
|
|
43
|
+
'PendingSpec',
|
|
44
|
+
'PendingView',
|
|
45
|
+
'PhaseMachine',
|
|
46
|
+
'RenderModel',
|
|
47
|
+
'SeatRef',
|
|
48
|
+
'SeatView',
|
|
49
|
+
'Setup',
|
|
50
|
+
'TokenView',
|
|
51
|
+
'Transition',
|
|
52
|
+
'TurnOrder',
|
|
53
|
+
'UpgradableRules',
|
|
54
|
+
'ZoneView',
|
|
55
|
+
'extract',
|
|
56
|
+
'find',
|
|
57
|
+
'for_seat',
|
|
58
|
+
'hand_view',
|
|
59
|
+
'is_legal',
|
|
60
|
+
'rng_for',
|
|
61
|
+
'shuffled',
|
|
62
|
+
'take',
|
|
63
|
+
]
|
bgb_engine/base.py
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
"""The contract every game definition implements.
|
|
2
|
+
|
|
3
|
+
Nothing here imports Django: a definition is played in memory, and the
|
|
4
|
+
persistence layer adapts its rows to these plain values.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Any, Protocol, runtime_checkable
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class IllegalAction(Exception):
|
|
12
|
+
"""The actor may not take this action in the current context."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class SeatRef:
|
|
17
|
+
"""A seat as the engine sees it; no Django model crosses this boundary."""
|
|
18
|
+
|
|
19
|
+
position: int
|
|
20
|
+
role: str = ''
|
|
21
|
+
player_id: int | None = None
|
|
22
|
+
name: str = ''
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class Param:
|
|
27
|
+
"""One argument an action needs, with the values the UI may offer."""
|
|
28
|
+
|
|
29
|
+
key: str
|
|
30
|
+
label: str
|
|
31
|
+
kind: str = 'option'
|
|
32
|
+
options: tuple[Any, ...] = ()
|
|
33
|
+
labels: tuple[str, ...] = ()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True)
|
|
38
|
+
class ActionOption:
|
|
39
|
+
"""A legal action, rendered as a button, a form or a select."""
|
|
40
|
+
|
|
41
|
+
id: str
|
|
42
|
+
label: str
|
|
43
|
+
params: tuple[Param, ...] = ()
|
|
44
|
+
group: str = ''
|
|
45
|
+
enabled: bool = True
|
|
46
|
+
cost: dict[str, int] = field(default_factory=dict)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class Action:
|
|
51
|
+
"""What an actor asks to do; ``id`` must be one of the legal options."""
|
|
52
|
+
|
|
53
|
+
actor: int
|
|
54
|
+
id: str
|
|
55
|
+
params: dict[str, Any] = field(default_factory=dict)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(frozen=True)
|
|
59
|
+
class PendingRef:
|
|
60
|
+
"""A choice still waiting for an answer."""
|
|
61
|
+
|
|
62
|
+
seat: int
|
|
63
|
+
kind: str
|
|
64
|
+
label: str = ''
|
|
65
|
+
options: tuple[Any, ...] = ()
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True)
|
|
69
|
+
class PendingSpec:
|
|
70
|
+
"""A choice to open, or to close when ``close`` is set."""
|
|
71
|
+
|
|
72
|
+
seat: int
|
|
73
|
+
kind: str
|
|
74
|
+
label: str = ''
|
|
75
|
+
options: tuple[Any, ...] = ()
|
|
76
|
+
context: dict[str, Any] = field(default_factory=dict)
|
|
77
|
+
close: bool = False
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass(frozen=True)
|
|
81
|
+
class LogEntry:
|
|
82
|
+
text: str
|
|
83
|
+
kind: str = 'info'
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass(frozen=True)
|
|
87
|
+
class OutboxItem:
|
|
88
|
+
kind: str
|
|
89
|
+
payload: dict[str, Any] = field(default_factory=dict)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass(frozen=True)
|
|
93
|
+
class Setup:
|
|
94
|
+
"""The initial deal: public state, shared hidden state, per-seat state."""
|
|
95
|
+
|
|
96
|
+
state: dict[str, Any]
|
|
97
|
+
hidden: dict[str, Any] = field(default_factory=dict)
|
|
98
|
+
private: dict[int, dict[str, Any]] = field(default_factory=dict)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@dataclass(frozen=True)
|
|
102
|
+
class Transition:
|
|
103
|
+
"""What one legal action produced.
|
|
104
|
+
|
|
105
|
+
``state`` replaces the public state; ``hidden`` and ``private`` are
|
|
106
|
+
patches merged into the stored dictionaries.
|
|
107
|
+
"""
|
|
108
|
+
|
|
109
|
+
state: dict[str, Any]
|
|
110
|
+
hidden: dict[str, Any] = field(default_factory=dict)
|
|
111
|
+
private: dict[int, dict[str, Any]] = field(default_factory=dict)
|
|
112
|
+
pending: tuple[PendingSpec, ...] = ()
|
|
113
|
+
log: tuple[LogEntry, ...] = ()
|
|
114
|
+
outbox: tuple[OutboxItem, ...] = ()
|
|
115
|
+
active: int | None = None
|
|
116
|
+
phase: str | None = None
|
|
117
|
+
over: bool = False
|
|
118
|
+
random: bool = False
|
|
119
|
+
reveals: bool | None = None
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@dataclass(frozen=True)
|
|
123
|
+
class Context:
|
|
124
|
+
"""Everything a definition may read while computing a view or an action."""
|
|
125
|
+
|
|
126
|
+
slug: str
|
|
127
|
+
seed: int
|
|
128
|
+
options: dict[str, Any]
|
|
129
|
+
state: dict[str, Any]
|
|
130
|
+
hidden: dict[str, Any]
|
|
131
|
+
private: dict[int, dict[str, Any]]
|
|
132
|
+
seats: tuple[SeatRef, ...]
|
|
133
|
+
phase: str
|
|
134
|
+
active: int | None
|
|
135
|
+
pending: tuple[PendingRef, ...] = ()
|
|
136
|
+
|
|
137
|
+
def seat(self, position: int) -> SeatRef:
|
|
138
|
+
"""Return the seat at ``position``; raise ``KeyError`` when absent."""
|
|
139
|
+
for seat in self.seats:
|
|
140
|
+
if seat.position == position:
|
|
141
|
+
return seat
|
|
142
|
+
raise KeyError(f'No seat at position {position}.')
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@dataclass(frozen=True)
|
|
146
|
+
class CardView:
|
|
147
|
+
"""A card a front end may render."""
|
|
148
|
+
|
|
149
|
+
id: str
|
|
150
|
+
label: str = ''
|
|
151
|
+
value: int = 0
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@dataclass(frozen=True)
|
|
155
|
+
class ZoneView:
|
|
156
|
+
"""A pile of cards, hidden ones replaced by their count."""
|
|
157
|
+
|
|
158
|
+
kind: str
|
|
159
|
+
label: str
|
|
160
|
+
private: bool = False
|
|
161
|
+
|
|
162
|
+
cards: tuple[CardView, ...] = ()
|
|
163
|
+
hidden_count: int | None = None
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
@dataclass(frozen=True)
|
|
167
|
+
class SeatView:
|
|
168
|
+
"""A seat in the standings, with its public counters."""
|
|
169
|
+
|
|
170
|
+
position: int
|
|
171
|
+
label: str
|
|
172
|
+
is_active: bool = False
|
|
173
|
+
eliminated: bool = False
|
|
174
|
+
counters: dict[str, int] = field(default_factory=dict)
|
|
175
|
+
hidden_cards: int = 0
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
@dataclass(frozen=True)
|
|
179
|
+
class CounterView:
|
|
180
|
+
"""One named counter across every seat."""
|
|
181
|
+
|
|
182
|
+
key: str
|
|
183
|
+
label: str
|
|
184
|
+
values: dict[int, int] = field(default_factory=dict)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
@dataclass(frozen=True)
|
|
188
|
+
class PendingView:
|
|
189
|
+
"""The choice this seat has to answer, if any."""
|
|
190
|
+
|
|
191
|
+
kind: str
|
|
192
|
+
label: str
|
|
193
|
+
options: tuple[Any, ...] = ()
|
|
194
|
+
deadline: str | None = None
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
@dataclass(frozen=True)
|
|
198
|
+
class GraphNodeView:
|
|
199
|
+
id: str
|
|
200
|
+
label: str = ''
|
|
201
|
+
x: float = 0.0
|
|
202
|
+
y: float = 0.0
|
|
203
|
+
kind: str = ''
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
@dataclass(frozen=True)
|
|
207
|
+
class GraphEdgeView:
|
|
208
|
+
source: str
|
|
209
|
+
target: str
|
|
210
|
+
kind: str = ''
|
|
211
|
+
label: str = ''
|
|
212
|
+
owners: tuple[int, ...] = ()
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
@dataclass(frozen=True)
|
|
216
|
+
class TokenView:
|
|
217
|
+
node: str
|
|
218
|
+
label: str = ''
|
|
219
|
+
owner: int | None = None
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@dataclass(frozen=True)
|
|
223
|
+
class GraphView:
|
|
224
|
+
"""A board of nodes and edges, with tokens on nodes."""
|
|
225
|
+
|
|
226
|
+
nodes: tuple[GraphNodeView, ...] = ()
|
|
227
|
+
edges: tuple[GraphEdgeView, ...] = ()
|
|
228
|
+
tokens: tuple[TokenView, ...] = ()
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
@dataclass(frozen=True)
|
|
232
|
+
class CellView:
|
|
233
|
+
column: int
|
|
234
|
+
row: int
|
|
235
|
+
label: str = ''
|
|
236
|
+
kind: str = ''
|
|
237
|
+
tokens: tuple[TokenView, ...] = ()
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
@dataclass(frozen=True)
|
|
241
|
+
class GridView:
|
|
242
|
+
"""A board of squares or hexes."""
|
|
243
|
+
|
|
244
|
+
columns: int
|
|
245
|
+
rows: int
|
|
246
|
+
hexes: bool = False
|
|
247
|
+
cells: tuple[CellView, ...] = ()
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
@dataclass(frozen=True)
|
|
251
|
+
class LogEntryView:
|
|
252
|
+
text: str
|
|
253
|
+
kind: str = 'info'
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
@dataclass(frozen=True)
|
|
257
|
+
class RenderModel:
|
|
258
|
+
"""One structure both front ends consume."""
|
|
259
|
+
|
|
260
|
+
board: GraphView | GridView | None = None
|
|
261
|
+
zones: tuple[ZoneView, ...] = ()
|
|
262
|
+
seats: tuple[SeatView, ...] = ()
|
|
263
|
+
counters: tuple[CounterView, ...] = ()
|
|
264
|
+
actions: tuple[ActionOption, ...] = ()
|
|
265
|
+
pending: PendingView | None = None
|
|
266
|
+
log: tuple[LogEntryView, ...] = ()
|
|
267
|
+
status: str = ''
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
@runtime_checkable
|
|
271
|
+
class GameDefinition(Protocol):
|
|
272
|
+
"""The rules of one game, registered under a slug."""
|
|
273
|
+
|
|
274
|
+
slug: str
|
|
275
|
+
name: str
|
|
276
|
+
version: int
|
|
277
|
+
min_players: int
|
|
278
|
+
max_players: int
|
|
279
|
+
capabilities: frozenset[str]
|
|
280
|
+
|
|
281
|
+
def validate_setup(self, options: dict[str, Any],
|
|
282
|
+
seats: tuple[SeatRef, ...]) -> None: ...
|
|
283
|
+
|
|
284
|
+
def setup(self, options: dict[str, Any], seats: tuple[SeatRef, ...],
|
|
285
|
+
seed: int) -> Setup: ...
|
|
286
|
+
|
|
287
|
+
def initial_phase(self) -> str: ...
|
|
288
|
+
|
|
289
|
+
def legal_actions(self, ctx: Context,
|
|
290
|
+
actor: int) -> tuple[ActionOption, ...]: ...
|
|
291
|
+
|
|
292
|
+
def apply(self, ctx: Context, action: Action) -> Transition: ...
|
|
293
|
+
|
|
294
|
+
def view(self, ctx: Context, position: int | None) -> RenderModel: ...
|
|
295
|
+
|
|
296
|
+
def summary(self, ctx: Context,
|
|
297
|
+
position: int | None) -> dict[str, Any]: ...
|
|
298
|
+
|
|
299
|
+
def is_over(self, ctx: Context) -> bool: ...
|
|
300
|
+
|
|
301
|
+
def scores(self, ctx: Context) -> list[dict[str, Any]]: ...
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
@runtime_checkable
|
|
306
|
+
class UpgradableRules(Protocol):
|
|
307
|
+
"""A definition that can carry a running match to newer rules."""
|
|
308
|
+
|
|
309
|
+
def upgrade(self, from_version: int, state: dict[str, Any],
|
|
310
|
+
hidden: dict[str, Any],
|
|
311
|
+
private: dict[int, dict[str, Any]],
|
|
312
|
+
seats: tuple[SeatRef, ...], options: dict[str, Any],
|
|
313
|
+
seed: int) -> Setup | None: ...
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
"""A minimal numbered-card scoring game, written to exercise the framework.
|
|
2
|
+
|
|
3
|
+
CardSampleGame uses hands, shared hidden state, counters, phases, turn order
|
|
4
|
+
and a pending choice, which is the surface a real game needs. It is an
|
|
5
|
+
original sample, not an adaptation of a published game.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import copy
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from ...base import (Action, ActionOption, CardView, Context, IllegalAction,
|
|
12
|
+
LogEntry, OutboxItem, Param, PendingSpec, PendingView,
|
|
13
|
+
RenderModel, SeatRef, SeatView, Setup, Transition,
|
|
14
|
+
ZoneView)
|
|
15
|
+
from ...primitives.counters import Counters
|
|
16
|
+
from ...primitives.pending import for_seat
|
|
17
|
+
from ...primitives.phases import PhaseMachine
|
|
18
|
+
from ...primitives.projection import hand_view
|
|
19
|
+
from ...primitives.turn import TurnOrder
|
|
20
|
+
from ...primitives.zones import Card, find, shuffled
|
|
21
|
+
|
|
22
|
+
PHASES = PhaseMachine(('play', 'finished'))
|
|
23
|
+
DECK_VALUES = (0, 1, 2, 3, 4, 5)
|
|
24
|
+
STARTING_CARDS = 3
|
|
25
|
+
DECK_ROUNDS = 2
|
|
26
|
+
STARTING_CARDS_MIN = 1
|
|
27
|
+
STARTING_CARDS_MAX = 5
|
|
28
|
+
DECK_ROUNDS_MIN = 1
|
|
29
|
+
DECK_ROUNDS_MAX = 5
|
|
30
|
+
MIN_PLAYERS = 2
|
|
31
|
+
MAX_PLAYERS = 4
|
|
32
|
+
VERSION = 1
|
|
33
|
+
SWAP = 0
|
|
34
|
+
COINS = 'coins'
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class CardSampleGame:
|
|
38
|
+
"""Play a card to score its value; the swap card trades counters."""
|
|
39
|
+
|
|
40
|
+
slug = 'card-sample-game'
|
|
41
|
+
name = 'Card Sample Game'
|
|
42
|
+
version = VERSION
|
|
43
|
+
min_players = MIN_PLAYERS
|
|
44
|
+
max_players = MAX_PLAYERS
|
|
45
|
+
capabilities = frozenset({'hands', 'counters', 'pending', 'private'})
|
|
46
|
+
|
|
47
|
+
def validate_setup(self, options: dict[str, Any],
|
|
48
|
+
seats: tuple[SeatRef, ...]) -> None:
|
|
49
|
+
count = options.get('starting_cards', STARTING_CARDS)
|
|
50
|
+
if not isinstance(count, int) or not (
|
|
51
|
+
STARTING_CARDS_MIN <= count <= STARTING_CARDS_MAX):
|
|
52
|
+
raise ValueError(
|
|
53
|
+
f'starting_cards must be an integer from '
|
|
54
|
+
f'{STARTING_CARDS_MIN} to {STARTING_CARDS_MAX}.')
|
|
55
|
+
rounds = options.get('deck_rounds', DECK_ROUNDS)
|
|
56
|
+
if not isinstance(rounds, int) or not (
|
|
57
|
+
DECK_ROUNDS_MIN <= rounds <= DECK_ROUNDS_MAX):
|
|
58
|
+
raise ValueError(
|
|
59
|
+
f'deck_rounds must be an integer from '
|
|
60
|
+
f'{DECK_ROUNDS_MIN} to {DECK_ROUNDS_MAX}.')
|
|
61
|
+
if not self.min_players <= len(seats) <= self.max_players:
|
|
62
|
+
raise ValueError(f'{self.name} seats {self.min_players} to '
|
|
63
|
+
f'{self.max_players} players.')
|
|
64
|
+
positions = [seat.position for seat in seats]
|
|
65
|
+
if len(set(positions)) != len(positions):
|
|
66
|
+
raise ValueError('Seat positions must be unique.')
|
|
67
|
+
|
|
68
|
+
def setup(self, options: dict[str, Any], seats: tuple[SeatRef, ...],
|
|
69
|
+
seed: int) -> Setup:
|
|
70
|
+
self.validate_setup(options, seats)
|
|
71
|
+
count = options.get('starting_cards', STARTING_CARDS)
|
|
72
|
+
rounds = options.get('deck_rounds', DECK_ROUNDS)
|
|
73
|
+
deck = shuffled(self.deck(len(seats), rounds), seed=seed, salt='deal')
|
|
74
|
+
private = {}
|
|
75
|
+
for seat in seats:
|
|
76
|
+
hand, deck = deck[:count], deck[count:]
|
|
77
|
+
private[seat.position] = {
|
|
78
|
+
'hand': [card.to_dict() for card in hand]}
|
|
79
|
+
state = {
|
|
80
|
+
'counters': {COINS: [0] * len(seats)},
|
|
81
|
+
'discard': [],
|
|
82
|
+
'deck_count': len(deck),
|
|
83
|
+
}
|
|
84
|
+
hidden = {'deck': [card.to_dict() for card in deck]}
|
|
85
|
+
return Setup(state=state, hidden=hidden, private=private)
|
|
86
|
+
|
|
87
|
+
def deck(self, player_count: int,
|
|
88
|
+
rounds: int = DECK_ROUNDS) -> list[Card]:
|
|
89
|
+
"""Return the cards a table of ``player_count`` plays with."""
|
|
90
|
+
cards = []
|
|
91
|
+
for index in range(len(DECK_VALUES) * rounds * player_count):
|
|
92
|
+
value = DECK_VALUES[index % len(DECK_VALUES)]
|
|
93
|
+
label = 'Swap' if value == SWAP else str(value)
|
|
94
|
+
cards.append(Card(id=f'c{index:02d}', label=label, value=value))
|
|
95
|
+
return cards
|
|
96
|
+
|
|
97
|
+
def initial_phase(self) -> str:
|
|
98
|
+
return PHASES.first
|
|
99
|
+
|
|
100
|
+
def legal_actions(self, ctx: Context,
|
|
101
|
+
actor: int) -> tuple[ActionOption, ...]:
|
|
102
|
+
if ctx.active != actor or self.is_over(ctx):
|
|
103
|
+
return ()
|
|
104
|
+
choice = for_seat(ctx.pending, actor)
|
|
105
|
+
if choice is not None:
|
|
106
|
+
return (ActionOption(
|
|
107
|
+
id='resolve_choice', label=choice.label,
|
|
108
|
+
params=(Param('target', 'Target', kind='seat',
|
|
109
|
+
options=choice.options),)),)
|
|
110
|
+
hand = self._hand(ctx, actor)
|
|
111
|
+
if not hand:
|
|
112
|
+
return (ActionOption(id='pass', label='Pass'),)
|
|
113
|
+
return (ActionOption(
|
|
114
|
+
id='play_card', label='Play a card',
|
|
115
|
+
params=(Param('card', 'Card', kind='card',
|
|
116
|
+
options=tuple(card['id'] for card in hand)),)),)
|
|
117
|
+
|
|
118
|
+
def apply(self, ctx: Context, action: Action) -> Transition:
|
|
119
|
+
if self.is_over(ctx):
|
|
120
|
+
raise IllegalAction('The game is over.')
|
|
121
|
+
if action.actor != ctx.active:
|
|
122
|
+
raise IllegalAction('It is not your turn.')
|
|
123
|
+
legal = {option.id for option in self.legal_actions(ctx, action.actor)}
|
|
124
|
+
if action.id not in legal:
|
|
125
|
+
raise IllegalAction(f'{action.id!r} is not legal here.')
|
|
126
|
+
|
|
127
|
+
state = copy.deepcopy(ctx.state)
|
|
128
|
+
hidden = copy.deepcopy(ctx.hidden)
|
|
129
|
+
private = {position: copy.deepcopy(values)
|
|
130
|
+
for position, values in ctx.private.items()}
|
|
131
|
+
|
|
132
|
+
if action.id == 'play_card':
|
|
133
|
+
return self._play(ctx, action, state, hidden, private)
|
|
134
|
+
if action.id == 'resolve_choice':
|
|
135
|
+
return self._resolve(ctx, action, state, hidden, private)
|
|
136
|
+
return self._pass(ctx, action, state, hidden, private)
|
|
137
|
+
|
|
138
|
+
def view(self, ctx: Context, position: int | None) -> RenderModel:
|
|
139
|
+
state = ctx.state
|
|
140
|
+
counters = Counters.from_dict(state.get('counters', {}))
|
|
141
|
+
zones = []
|
|
142
|
+
if position is not None:
|
|
143
|
+
cards = [Card.from_dict(entry)
|
|
144
|
+
for entry in self._hand(ctx, position)]
|
|
145
|
+
visible, hidden_count = hand_view(cards, owned=True)
|
|
146
|
+
zones.append(ZoneView(
|
|
147
|
+
kind='hand', label='Your hand',
|
|
148
|
+
cards=tuple(CardView(id=card.id, label=card.label,
|
|
149
|
+
value=card.value) for card in visible),
|
|
150
|
+
hidden_count=hidden_count, private=True))
|
|
151
|
+
zones.append(ZoneView(
|
|
152
|
+
kind='discard', label='Discard',
|
|
153
|
+
cards=tuple(CardView(id=card['id'], label=card['label'],
|
|
154
|
+
value=card['value'])
|
|
155
|
+
for card in state.get('discard', []))))
|
|
156
|
+
zones.append(ZoneView(kind='deck', label='Deck',
|
|
157
|
+
hidden_count=state.get('deck_count', 0)))
|
|
158
|
+
|
|
159
|
+
seats = []
|
|
160
|
+
for seat in ctx.seats:
|
|
161
|
+
owned = seat.position == position
|
|
162
|
+
_, hidden_count = hand_view(
|
|
163
|
+
[Card.from_dict(entry)
|
|
164
|
+
for entry in self._hand(ctx, seat.position)], owned=owned)
|
|
165
|
+
seats.append(SeatView(
|
|
166
|
+
position=seat.position,
|
|
167
|
+
label=self._name(ctx, seat.position),
|
|
168
|
+
is_active=seat.position == ctx.active,
|
|
169
|
+
counters={COINS: counters.get(COINS, seat.position)},
|
|
170
|
+
hidden_cards=hidden_count or 0))
|
|
171
|
+
|
|
172
|
+
choice = for_seat(ctx.pending, position) if position is not None else None
|
|
173
|
+
pending = (PendingView(kind=choice.kind, label=choice.label,
|
|
174
|
+
options=choice.options) if choice else None)
|
|
175
|
+
actions = (self.legal_actions(ctx, position)
|
|
176
|
+
if position is not None else ())
|
|
177
|
+
return RenderModel(zones=tuple(zones), seats=tuple(seats),
|
|
178
|
+
actions=actions, pending=pending,
|
|
179
|
+
status=self._status(ctx))
|
|
180
|
+
|
|
181
|
+
def summary(self, ctx: Context,
|
|
182
|
+
position: int | None) -> dict[str, Any]:
|
|
183
|
+
return {'phase': ctx.phase, 'active': ctx.active,
|
|
184
|
+
'scores': self.scores(ctx)}
|
|
185
|
+
|
|
186
|
+
def is_over(self, ctx: Context) -> bool:
|
|
187
|
+
if ctx.pending:
|
|
188
|
+
return False
|
|
189
|
+
if ctx.state.get('over'):
|
|
190
|
+
return True
|
|
191
|
+
return (ctx.state.get('deck_count', 0) == 0
|
|
192
|
+
and all(not values.get('hand')
|
|
193
|
+
for values in ctx.private.values()))
|
|
194
|
+
|
|
195
|
+
def scores(self, ctx: Context) -> list[dict[str, Any]]:
|
|
196
|
+
counters = Counters.from_dict(ctx.state.get('counters', {}))
|
|
197
|
+
rows = [{'position': seat.position,
|
|
198
|
+
'name': self._name(ctx, seat.position),
|
|
199
|
+
'coins': counters.get(COINS, seat.position)}
|
|
200
|
+
for seat in ctx.seats]
|
|
201
|
+
return sorted(rows, key=lambda row: row['coins'], reverse=True)
|
|
202
|
+
|
|
203
|
+
def _play(self, ctx: Context, action: Action, state: dict[str, Any],
|
|
204
|
+
hidden: dict[str, Any], private: dict[int, dict[str, Any]]) -> Transition:
|
|
205
|
+
card_id = action.params.get('card')
|
|
206
|
+
if not isinstance(card_id, str):
|
|
207
|
+
raise IllegalAction('Pick one of your cards.')
|
|
208
|
+
hand = private[action.actor]['hand']
|
|
209
|
+
card = find([Card.from_dict(entry) for entry in hand], card_id)
|
|
210
|
+
if card is None:
|
|
211
|
+
raise IllegalAction('That card is not in your hand.')
|
|
212
|
+
hand = [entry for entry in hand if entry['id'] != card_id]
|
|
213
|
+
private[action.actor]['hand'] = hand
|
|
214
|
+
state['discard'].append(card.to_dict())
|
|
215
|
+
log = [LogEntry(f'{self._name(ctx, action.actor)} plays {card.label}.')]
|
|
216
|
+
|
|
217
|
+
if card.value == SWAP:
|
|
218
|
+
targets = tuple(seat.position for seat in ctx.seats
|
|
219
|
+
if seat.position != action.actor)
|
|
220
|
+
return Transition(
|
|
221
|
+
state=state, hidden=hidden,
|
|
222
|
+
private={action.actor: {'hand': hand}},
|
|
223
|
+
pending=(PendingSpec(
|
|
224
|
+
seat=action.actor, kind='swap_target',
|
|
225
|
+
label='Swap counters with which seat?',
|
|
226
|
+
options=targets),),
|
|
227
|
+
log=tuple(log), active=action.actor)
|
|
228
|
+
counters = Counters.from_dict(state['counters'])
|
|
229
|
+
state['counters'] = counters.with_add(
|
|
230
|
+
COINS, action.actor, card.value).as_dict()
|
|
231
|
+
return self._end_turn(ctx, state, hidden, private, action.actor, log)
|
|
232
|
+
|
|
233
|
+
def _resolve(self, ctx: Context, action: Action, state: dict[str, Any],
|
|
234
|
+
hidden: dict[str, Any], private: dict[int, dict[str, Any]]) -> Transition:
|
|
235
|
+
choice = for_seat(ctx.pending, action.actor)
|
|
236
|
+
if choice is None:
|
|
237
|
+
raise IllegalAction('You have no choice to resolve.')
|
|
238
|
+
target = action.params.get('target')
|
|
239
|
+
if not isinstance(target, int):
|
|
240
|
+
raise IllegalAction('Pick one of the offered seats.')
|
|
241
|
+
if target not in choice.options:
|
|
242
|
+
raise IllegalAction('That target is not offered.')
|
|
243
|
+
counters = Counters.from_dict(state['counters'])
|
|
244
|
+
state['counters'] = counters.with_swap(
|
|
245
|
+
COINS, action.actor, target).as_dict()
|
|
246
|
+
log = [LogEntry(f'{self._name(ctx, action.actor)} swaps counters with '
|
|
247
|
+
f'{self._name(ctx, target)}.')]
|
|
248
|
+
close = PendingSpec(seat=action.actor, kind=choice.kind, close=True)
|
|
249
|
+
return self._end_turn(ctx, state, hidden, private, action.actor, log,
|
|
250
|
+
pending=(close,))
|
|
251
|
+
|
|
252
|
+
def _pass(self, ctx: Context, action: Action, state: dict[str, Any],
|
|
253
|
+
hidden: dict[str, Any], private: dict[int, dict[str, Any]]) -> Transition:
|
|
254
|
+
log = [LogEntry(f'{self._name(ctx, action.actor)} passes.')]
|
|
255
|
+
return self._end_turn(ctx, state, hidden, private, action.actor, log,
|
|
256
|
+
draw=False)
|
|
257
|
+
|
|
258
|
+
def _end_turn(self, ctx: Context, state: dict[str, Any],
|
|
259
|
+
hidden: dict[str, Any], private: dict[int, dict[str, Any]],
|
|
260
|
+
actor: int, log: list[LogEntry], *, draw: bool = True,
|
|
261
|
+
pending: tuple[PendingSpec, ...] = ()) -> Transition:
|
|
262
|
+
if draw and hidden.get('deck'):
|
|
263
|
+
deck = [Card.from_dict(entry) for entry in hidden['deck']]
|
|
264
|
+
drawn, deck = deck[0], deck[1:]
|
|
265
|
+
private[actor]['hand'] = private[actor]['hand'] + [drawn.to_dict()]
|
|
266
|
+
hidden['deck'] = [card.to_dict() for card in deck]
|
|
267
|
+
state['deck_count'] = len(deck)
|
|
268
|
+
patch = {actor: {'hand': private[actor]['hand']}}
|
|
269
|
+
|
|
270
|
+
over = (state['deck_count'] == 0
|
|
271
|
+
and all(not values.get('hand')
|
|
272
|
+
for values in private.values()))
|
|
273
|
+
if over:
|
|
274
|
+
return Transition(
|
|
275
|
+
state=state, hidden=hidden, private=patch, pending=pending,
|
|
276
|
+
log=tuple(log), outbox=(OutboxItem(
|
|
277
|
+
kind='match_over',
|
|
278
|
+
payload={'scores': self._scores_from_state(ctx, state)}),),
|
|
279
|
+
active=None, phase=PHASES.last, over=True)
|
|
280
|
+
positions = tuple(seat.position for seat in ctx.seats)
|
|
281
|
+
return Transition(state=state, hidden=hidden, private=patch,
|
|
282
|
+
pending=pending, log=tuple(log),
|
|
283
|
+
active=TurnOrder(positions).after(actor),
|
|
284
|
+
phase=PHASES.first)
|
|
285
|
+
|
|
286
|
+
def _scores_from_state(self, ctx: Context,
|
|
287
|
+
state: dict[str, Any]) -> list[dict[str, Any]]:
|
|
288
|
+
counters = Counters.from_dict(state.get('counters', {}))
|
|
289
|
+
return [{'position': seat.position,
|
|
290
|
+
'name': self._name(ctx, seat.position),
|
|
291
|
+
'coins': counters.get(COINS, seat.position)}
|
|
292
|
+
for seat in ctx.seats]
|
|
293
|
+
|
|
294
|
+
def _hand(self, ctx: Context, position: int) -> list[dict[str, Any]]:
|
|
295
|
+
return list(ctx.private.get(position, {}).get('hand', []))
|
|
296
|
+
|
|
297
|
+
def _name(self, ctx: Context, position: int) -> str:
|
|
298
|
+
seat = ctx.seat(position)
|
|
299
|
+
return seat.name or f'Seat {position + 1}'
|
|
300
|
+
|
|
301
|
+
def _status(self, ctx: Context) -> str:
|
|
302
|
+
if self.is_over(ctx):
|
|
303
|
+
return 'Game over.'
|
|
304
|
+
if ctx.active is None:
|
|
305
|
+
return 'No active seat.'
|
|
306
|
+
return f'{self._name(ctx, ctx.active)} to act.'
|
|
307
|
+
|
|
308
|
+
|