-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdriver.py
More file actions
94 lines (77 loc) · 2.38 KB
/
driver.py
File metadata and controls
94 lines (77 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import json
from typing import TypedDict
from uuid import uuid4
import ray
from pypiles.actors import (
CenterPile,
CenterPileState,
GameStatus,
GameStatusState,
Player,
PlayerState,
)
from pypiles.deck import prepare_game_cards
from pypiles.logger import setup_logger
from pypiles.strategies.greedy import GreedySwapper
class CompleteGameState(TypedDict):
id: str
game_status: GameStatusState
center_pile: CenterPileState
players: list[PlayerState]
def main():
NUM_PLAYERS = 2
PILE_SIZE = 4
NUM_PILES_PER_PLAYERS = 6
WINNING_SCORE = None
game_id = str(uuid4())
logger = setup_logger(name=__name__, log_file=f"logs/{game_id}/driver.log")
center_pile_cards, player_cards = prepare_game_cards(
num_players=NUM_PLAYERS,
pile_size=PILE_SIZE,
num_piles_per_player=NUM_PILES_PER_PLAYERS,
)
game_status = GameStatus.remote(
winning_score=WINNING_SCORE
if WINNING_SCORE is not None
else NUM_PILES_PER_PLAYERS
)
center_pile = CenterPile.remote(
cards=center_pile_cards, log_file=f"logs/{game_id}/cp.log"
)
players = [
Player.remote(
id=f"P{i+1}",
cards=player_piles,
strategy=GreedySwapper(),
log_file=f"logs/{game_id}/p{i+1}.log",
)
for i, player_piles in enumerate(player_cards)
]
try:
results = ray.get(
[
p.play.remote(center_pile=center_pile, game_status=game_status)
for p in players
]
)
except Exception as e:
logger.info(f"!!! An error occurred during game play: {e}")
finally:
# collect all object states
combined_game_state = CompleteGameState(
id=game_id,
game_status=ray.get(game_status.get_game_state.remote()),
center_pile=ray.get(center_pile.get_center_pile_state.remote()),
players=[ray.get(p.get_player_state.remote()) for p in players],
)
# save to file
state_filepath = f"logs/{game_id}/state.json"
logger.info(f"Saving final game state to {state_filepath}")
with open(state_filepath, mode="w") as outfile:
json.dump(combined_game_state, outfile)
outfile.close()
## -- shutdown ray
ray.shutdown()
return
if __name__ == "__main__":
main()