-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhog_gui.py
188 lines (155 loc) · 5.35 KB
/
hog_gui.py
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
"""Web server for the hog GUI."""
import io
import os
import logging
from contextlib import redirect_stdout
from gui_files.common_server import route, start
import hog
import dice
import default_graphics
PORT = 31415
DEFAULT_SERVER = "https://hog.cs61a.org"
GUI_FOLDER = "gui_files/"
PATHS = {}
class HogLoggingException(Exception):
pass
@route
def take_turn(prev_rolls, move_history, goal, game_rules):
"""Simulate the whole game up to the current turn."""
fair_dice = dice.make_fair_dice(6)
dice_results = []
more_boar = game_rules["More Boar"]
try:
old_more_boar = hog.more_boar
if not more_boar:
hog.more_boar = lambda score0, score1: False
def logged_dice():
if len(dice_results) < len(prev_rolls):
out = prev_rolls[len(dice_results)]
else:
out = fair_dice()
dice_results.append(out)
return out
final_scores = None
final_message = None
who = 0
commentary = hog.both(
hog.announce_highest(0),
hog.both(hog.announce_highest(1), hog.announce_lead_changes()),
)
def log(*logged_scores):
nonlocal final_message, commentary
f = io.StringIO()
with redirect_stdout(f):
commentary = commentary(*logged_scores)
final_message = f.getvalue()
return log
move_cnt = 0
def strategy_for(player):
def strategy(*scores):
nonlocal final_scores, move_cnt, who
final_scores = scores
if player:
final_scores = final_scores[::-1]
who = player
if move_cnt == len(move_history):
raise HogLoggingException()
move = move_history[move_cnt]
move_cnt += 1
return move
return strategy
game_over = False
try:
final_scores = trace_play(
hog.play,
strategy_for(0),
strategy_for(1),
0,
0,
dice=logged_dice,
say=log,
goal=goal,
)[:2]
except HogLoggingException:
pass
else:
game_over = True
finally:
hog.more_boar = old_more_boar
return {
"rolls": dice_results,
"finalScores": final_scores,
"message": final_message,
"gameOver": game_over,
"who": who,
}
@route
def strategy(name, scores):
STRATEGIES = {
"piggypoints_strategy": hog.piggypoints_strategy,
"more_boar_strategy": hog.more_boar_strategy,
"final_strategy": hog.final_strategy,
}
return STRATEGIES[name](*scores[::-1])
@route("dice_graphic.svg")
def draw_dice_graphic(num):
num = int(num[0])
# Either draw student-provided dice or our default dice
if hasattr(hog, "draw_dice"):
graphic = hog.draw_dice(num)
return str(graphic)
return default_graphics.dice[num]
def safe(commentary):
def new_commentary(*args, **kwargs):
try:
result = commentary(*args, **kwargs)
except TypeError:
result = commentary
return safe(result)
return new_commentary
def trace_play(play, strategy0, strategy1, score0, score1, dice, goal, say):
"""Wraps the user's play function and
(1) ensures that strategy0 and strategy1 are called exactly once per turn
(2) records the entire game, returning the result as a list of dictionaries,
each with keys "s0_start", "s1_start", "who", "num_dice", "dice_values"
Returns (s0, s1, trace) where s0, s1 are the return values from play and trace
is the trace as specified above.
This might seem a bit overcomplicated but it will also used to create the game
traces for the fuzz test (when run against the staff solution).
"""
game_trace = []
def mod_strategy(who, my_score, opponent_score):
if game_trace:
prev_total_score = game_trace[-1]["s0_start"] + game_trace[-1]["s1_start"]
if prev_total_score == my_score + opponent_score:
# game is still on last turn since the total number of points
# goes up every turn
return game_trace[-1]["num_dice"]
current_num_dice = (strategy0, strategy1)[who](my_score, opponent_score)
current_turn = {
"s0_start": [my_score, opponent_score][who],
"s1_start": [my_score, opponent_score][1 - who],
"who": who,
"num_dice": current_num_dice,
"dice_values": [], # no dice rolled yet
}
game_trace.append(current_turn)
return current_num_dice
def mod_dice():
roll = dice()
if not game_trace:
raise RuntimeError("roll_dice called before either strategy function")
game_trace[-1]["dice_values"].append(roll)
return roll
s0, s1 = play(
lambda a, b: mod_strategy(0, a, b),
lambda a, b: mod_strategy(1, a, b),
score0,
score1,
dice=mod_dice,
goal=goal,
say=safe(say),
)
return s0, s1, game_trace
if __name__ == "__main__" or "gunicorn" in os.environ.get("SERVER_SOFTWARE", ""):
app = start(PORT, DEFAULT_SERVER, GUI_FOLDER)