-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhog.py
More file actions
326 lines (256 loc) · 10.1 KB
/
hog.py
File metadata and controls
326 lines (256 loc) · 10.1 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
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
"""The Game of Hog."""
from dice import six_sided, make_test_dice
from ucb import main, trace, interact
GOAL = 100 # The goal of Hog is to score 100 points.
######################
# Phase 1: Simulator #
######################
def roll_dice(num_rolls, dice=six_sided):
"""Simulate rolling the DICE exactly NUM_ROLLS > 0 times. Return the sum of
the outcomes unless any of the outcomes is 1. In that case, return 1.
num_rolls: The number of dice rolls that will be made.
dice: A function that simulates a single dice roll outcome.
"""
# These assert statements ensure that num_rolls is a positive integer.
assert type(num_rolls) == int, 'num_rolls must be an integer.'
assert num_rolls > 0, 'Must roll at least once.'
# BEGIN PROBLEM 1
"*** YOUR CODE HERE ***"
cnt = 0
sum = 0
flag = 0
while(cnt < num_rolls):
this = dice()
if this == 1:
flag = 1
sum += this
cnt += 1
if flag == 1:
return 1
else:
return sum
# END PROBLEM 1
def boar_brawl(player_score, opponent_score):
"""Return the points scored by rolling 0 dice according to Boar Brawl.
player_score: The total score of the current player.
opponent_score: The total score of the other player.
"""
# BEGIN PROBLEM 2
"*** YOUR CODE HERE ***"
yours = player_score % 10
theirs = (opponent_score // 10) % 10
sc = abs(theirs - yours) * 3
if sc == 0:
sc = 1
return sc
# END PROBLEM 2
def take_turn(num_rolls, player_score, opponent_score, dice=six_sided):
"""Return the points scored on a turn rolling NUM_ROLLS dice when the
player has PLAYER_SCORE points and the opponent has OPPONENT_SCORE points.
num_rolls: The number of dice rolls that will be made.
player_score: The total score of the current player.
opponent_score: The total score of the other player.
dice: A function that simulates a single dice roll outcome.
"""
# Leave these assert statements here; they help check for errors.
assert type(num_rolls) == int, 'num_rolls must be an integer.'
assert num_rolls >= 0, 'Cannot roll a negative number of dice in take_turn.'
assert num_rolls <= 10, 'Cannot roll more than 10 dice.'
# BEGIN PROBLEM 3
"*** YOUR CODE HERE ***"
if num_rolls == 0:
return boar_brawl(player_score, opponent_score)
else:
return roll_dice(num_rolls, dice)
# END PROBLEM 3
def simple_update(num_rolls, player_score, opponent_score, dice=six_sided):
"""Return the total score of a player who starts their turn with
PLAYER_SCORE and then rolls NUM_ROLLS DICE, ignoring Sus Fuss.
"""
score = player_score + take_turn(num_rolls, player_score, opponent_score, dice)
return score
def is_prime(n):
"""Return whether N is prime."""
if n == 1:
return False
k = 2
while k < n:
if n % k == 0:
return False
k += 1
return True
def num_factors(n):
"""Return the number of factors of N, including 1 and N itself."""
# BEGIN PROBLEM 4
"*** YOUR CODE HERE ***"
# END PROBLEM 4
def sus_points(score):
"""Return the new score of a player taking into account the Sus Fuss rule."""
# BEGIN PROBLEM 4
"*** YOUR CODE HERE ***"
# END PROBLEM 4
def sus_update(num_rolls, player_score, opponent_score, dice=six_sided):
"""Return the total score of a player who starts their turn with
PLAYER_SCORE and then rolls NUM_ROLLS DICE, *including* Sus Fuss.
"""
# BEGIN PROBLEM 4
"*** YOUR CODE HERE ***"
# END PROBLEM 4
def always_roll_5(score, opponent_score):
"""A strategy of always rolling 5 dice, regardless of the player's score or
the opponent's score.
"""
return 5
def play(strategy0, strategy1, update,
score0=0, score1=0, dice=six_sided, goal=GOAL):
"""Simulate a game and return the final scores of both players, with
Player 0's score first and Player 1's score second.
E.g., play(always_roll_5, always_roll_5, sus_update) simulates a game in
which both players always choose to roll 5 dice on every turn and the Sus
Fuss rule is in effect.
A strategy function, such as always_roll_5, takes the current player's
score and their opponent's score and returns the number of dice the current
player chooses to roll.
An update function, such as sus_update or simple_update, takes the number
of dice to roll, the current player's score, the opponent's score, and the
dice function used to simulate rolling dice. It returns the updated score
of the current player after they take their turn.
strategy0: The strategy for player0.
strategy1: The strategy for player1.
update: The update function (used for both players).
score0: Starting score for Player 0
score1: Starting score for Player 1
dice: A function of zero arguments that simulates a dice roll.
goal: The game ends and someone wins when this score is reached.
"""
who = 0 # Who is about to take a turn, 0 (first) or 1 (second)
# BEGIN PROBLEM 5
"*** YOUR CODE HERE ***"
# END PROBLEM 5
return score0, score1
#######################
# Phase 2: Strategies #
#######################
def always_roll(n):
"""Return a player strategy that always rolls N dice.
A player strategy is a function that takes two total scores as arguments
(the current player's score, and the opponent's score), and returns a
number of dice that the current player will roll this turn.
>>> strategy = always_roll(3)
>>> strategy(0, 0)
3
>>> strategy(99, 99)
3
"""
assert n >= 0 and n <= 10
# BEGIN PROBLEM 6
"*** YOUR CODE HERE ***"
# END PROBLEM 6
def catch_up(score, opponent_score):
"""A player strategy that always rolls 5 dice unless the opponent
has a higher score, in which case 6 dice are rolled.
>>> catch_up(9, 4)
5
>>> strategy(17, 18)
6
"""
if score < opponent_score:
return 6 # Roll one more to catch up
else:
return 5
def is_always_roll(strategy, goal=GOAL):
"""Return whether STRATEGY always chooses the same number of dice to roll
given a game that goes to GOAL points.
>>> is_always_roll(always_roll_5)
True
>>> is_always_roll(always_roll(3))
True
>>> is_always_roll(catch_up)
False
"""
# BEGIN PROBLEM 7
"*** YOUR CODE HERE ***"
# END PROBLEM 7
def make_averaged(original_function, samples_count=1000):
"""Return a function that returns the average value of ORIGINAL_FUNCTION
called SAMPLES_COUNT times.
To implement this function, you will have to use *args syntax.
>>> dice = make_test_dice(4, 2, 5, 1)
>>> averaged_dice = make_averaged(roll_dice, 40)
>>> averaged_dice(1, dice) # The avg of 10 4's, 10 2's, 10 5's, and 10 1's
3.0
"""
# BEGIN PROBLEM 8
"*** YOUR CODE HERE ***"
# END PROBLEM 8
def max_scoring_num_rolls(dice=six_sided, samples_count=1000):
"""Return the number of dice (1 to 10) that gives the highest average turn score
by calling roll_dice with the provided DICE a total of SAMPLES_COUNT times.
Assume that the dice always return positive outcomes.
>>> dice = make_test_dice(1, 6)
>>> max_scoring_num_rolls(dice)
1
"""
# BEGIN PROBLEM 9
"*** YOUR CODE HERE ***"
# END PROBLEM 9
def winner(strategy0, strategy1):
"""Return 0 if strategy0 wins against strategy1, and 1 otherwise."""
score0, score1 = play(strategy0, strategy1, sus_update)
if score0 > score1:
return 0
else:
return 1
def average_win_rate(strategy, baseline=always_roll(6)):
"""Return the average win rate of STRATEGY against BASELINE. Averages the
winrate when starting the game as player 0 and as player 1.
"""
win_rate_as_player_0 = 1 - make_averaged(winner)(strategy, baseline)
win_rate_as_player_1 = make_averaged(winner)(baseline, strategy)
return (win_rate_as_player_0 + win_rate_as_player_1) / 2
def run_experiments():
"""Run a series of strategy experiments and report results."""
six_sided_max = max_scoring_num_rolls(six_sided)
print('Max scoring num rolls for six-sided dice:', six_sided_max)
print('always_roll(6) win rate:', average_win_rate(always_roll(6))) # near 0.5
print('catch_up win rate:', average_win_rate(catch_up))
print('always_roll(3) win rate:', average_win_rate(always_roll(3)))
print('always_roll(8) win rate:', average_win_rate(always_roll(8)))
print('boar_strategy win rate:', average_win_rate(boar_strategy))
print('sus_strategy win rate:', average_win_rate(sus_strategy))
print('final_strategy win rate:', average_win_rate(final_strategy))
"*** You may add additional experiments as you wish ***"
def boar_strategy(score, opponent_score, threshold=11, num_rolls=6):
"""This strategy returns 0 dice if Boar Brawl gives at least THRESHOLD
points, and returns NUM_ROLLS otherwise. Ignore score and Sus Fuss.
"""
# BEGIN PROBLEM 10
return num_rolls # Remove this line once implemented.
# END PROBLEM 10
def sus_strategy(score, opponent_score, threshold=11, num_rolls=6):
"""This strategy returns 0 dice when your score would increase by at least threshold."""
# BEGIN PROBLEM 11
return num_rolls # Remove this line once implemented.
# END PROBLEM 11
def final_strategy(score, opponent_score):
"""Write a brief description of your final strategy.
*** YOUR DESCRIPTION HERE ***
"""
# BEGIN PROBLEM 12
return 6 # Remove this line once implemented.
# END PROBLEM 12
##########################
# Command Line Interface #
##########################
# NOTE: The function in this section does not need to be changed. It uses
# features of Python not yet covered in the course.
@main
def run(*args):
"""Read in the command-line argument and calls corresponding functions."""
import argparse
parser = argparse.ArgumentParser(description="Play Hog")
parser.add_argument('--run_experiments', '-r', action='store_true',
help='Runs strategy experiments')
args = parser.parse_args()
if args.run_experiments:
run_experiments()