-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhog.py
405 lines (334 loc) · 12.2 KB
/
hog.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
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
import time
from hog_contest import final_strategy
"""CS 61A Presents The Game of Hog."""
from dice import four_sided, six_sided, make_test_dice
from ucb import main, trace, log_current_line, interact
GOAL_SCORE = 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 the
number of 1's rolled.
"""
# 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
total = 0
pig_out = False
while num_rolls > 0:
roll = dice()
if pig_out:
if roll == 1:
total += 1
elif roll == 1:
pig_out = True
total = 1
else:
total += roll
num_rolls -= 1
return total
# END PROBLEM 1
def free_bacon(opponent_score):
"""Return the points scored from rolling 0 dice (Free Bacon)."""
# BEGIN PROBLEM 2
largest = 0
while opponent_score > 0:
if opponent_score % 10 > largest:
largest = opponent_score % 10
opponent_score //= 10
return largest + 1
# END PROBLEM 2
# Write your prime functions here!
def is_prime(num):
if num == 1:
return False
if num == 2:
return True
if not num % 2:
return False
for x in range(3, int(num**.5)+1, 2):
if not num % x:
return False
return True
def next_prime(num):
if num == 2:
return 3
prime = num + 2
while True:
if is_prime(prime):
return prime
prime += 2
def take_turn(num_rolls, opponent_score, dice=six_sided):
"""Simulate a turn rolling NUM_ROLLS dice, which may be 0 (Free Bacon).
Return the points scored for the turn by the current player. Also
implements the Hogtimus Prime and When Pigs Fly rules.
num_rolls: The number of dice rolls that will be made.
opponent_score: The total score of the opponent.
dice: A function of no args that returns an integer 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.'
assert opponent_score < 100, 'The game should be over.'
# BEGIN PROBLEM 2
if num_rolls == 0:
score = free_bacon(opponent_score)
else:
score = roll_dice(num_rolls, dice)
if is_prime(score):
score = next_prime(score)
if score > 25 - num_rolls:
return 25 - num_rolls
else:
return score
# END PROBLEM 2
def reroll(dice):
"""Return dice that return even outcomes and re-roll odd outcomes of DICE."""
def rerolled():
# BEGIN PROBLEM 3
roll = dice()
if roll % 2 != 0:
return dice()
else:
return roll
# END PROBLEM 3
return rerolled
def select_dice(score, opponent_score, dice_swapped):
"""Return the dice used for a turn, which may be re-rolled (Hog Wild) and/or
swapped for four-sided dice (Pork Chop).
DICE_SWAPPED is True if and only if four-sided dice are being used.
"""
# BEGIN PROBLEM 4
if dice_swapped:
dice = four_sided
else:
dice = six_sided # Replace this statement
# END PROBLEM 4
if (score + opponent_score) % 7 == 0:
dice = reroll(dice)
return dice
def other(player):
"""Return the other player, for a player PLAYER numbered 0 or 1.
>>> other(0)
1
>>> other(1)
0
"""
return 1 - player
def play(strategy0, strategy1, score0=0, score1=0, goal=GOAL_SCORE):
"""Simulate a game and return the final scores of both players, with
Player 0's score first, and Player 1's score second.
A 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.
strategy0: The strategy function for Player 0, who plays first
strategy1: The strategy function for Player 1, who plays second
score0 : The starting score for Player 0
score1 : The starting score for Player 1
"""
player = 0 # Which player is about to take a turn, 0 (first) or 1 (second)
dice_swapped = False # Whether 4-sided dice have been swapped for 6-sided
# BEGIN PROBLEM 5
while score0 < goal and score1 < goal:
if player == 0:
num_roll = strategy0(score0, score1)
if num_roll == -1:
dice_swapped = not dice_swapped
score0 += 1
else:
score0 += take_turn(num_roll, score1, select_dice(score0, score1, dice_swapped))
else:
#player 1
num_roll = strategy1(score1, score0)
if num_roll == -1:
dice_swapped = not dice_swapped
score1 +=1
else:
score1 += take_turn(num_roll, score0, select_dice(score1, score0, dice_swapped))
#swine swap
if score0 == 2*score1 or score1 == 2*score0:
score0, score1 = score1, score0
player = other(player)
# END PROBLEM 5
return score0, score1
#######################
# Phase 2: Strategies #
#######################
def always_roll(n):
"""Return a strategy that always rolls N dice.
A 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(5)
>>> strategy(0, 0)
5
>>> strategy(99, 99)
5
"""
def strategy(score, opponent_score):
return n
return strategy
def check_strategy_roll(score, opponent_score, num_rolls):
"""Raises an error with a helpful message if NUM_ROLLS is an invalid
strategy output. All strategy outputs must be integers from -1 to 10.
>>> check_strategy_roll(10, 20, num_rolls=100)
Traceback (most recent call last):
...
AssertionError: strategy(10, 20) returned 100 (invalid number of rolls)
>>> check_strategy_roll(20, 10, num_rolls=0.1)
Traceback (most recent call last):
...
AssertionError: strategy(20, 10) returned 0.1 (not an integer)
>>> check_strategy_roll(0, 0, num_rolls=None)
Traceback (most recent call last):
...
AssertionError: strategy(0, 0) returned None (not an integer)
"""
msg = 'strategy({}, {}) returned {}'.format(
score, opponent_score, num_rolls)
assert type(num_rolls) == int, msg + ' (not an integer)'
assert -1 <= num_rolls <= 10, msg + ' (invalid number of rolls)'
def check_strategy(strategy, goal=GOAL_SCORE):
"""Checks the strategy with all valid inputs and verifies that the
strategy returns a valid input. Use `check_strategy_roll` to raise
an error with a helpful message if the strategy returns an invalid
output.
>>> def fail_15_20(score, opponent_score):
... if score != 15 or opponent_score != 20:
... return 5
...
>>> check_strategy(fail_15_20)
Traceback (most recent call last):
...
AssertionError: strategy(15, 20) returned None (not an integer)
>>> def fail_102_115(score, opponent_score):
... if score == 102 and opponent_score == 115:
... return 100
... return 5
...
>>> check_strategy(fail_102_115)
>>> fail_102_115 == check_strategy(fail_102_115, 120)
Traceback (most recent call last):
...
AssertionError: strategy(102, 115) returned 100 (invalid number of rolls)
"""
# BEGIN PROBLEM 6
for x in range (-1,goal):
for y in range (-1,goal):
check_strategy_roll(x,y,strategy(x,y))
# END PROBLEM 6
# Experiments
def make_averaged(fn, num_samples=10000):
"""Return a function that returns the average_value of FN when called.
To implement this function, you will have to use *args syntax, a new Python
feature introduced in this project. See the project description.
>>> dice = make_test_dice(3, 1, 5, 6)
>>> averaged_dice = make_averaged(dice, 1000)
>>> averaged_dice()
3.75
"""
# BEGIN PROBLEM 7
def average_func(*args):
trials = num_samples
total = 0
while trials > 0:
total += fn(*args)
trials -= 1
return total / num_samples
return average_func
# END PROBLEM 7
def max_scoring_num_rolls(dice=six_sided, num_samples=10000):
"""Return the number of dice (1 to 10) that gives the highest average turn
score by calling roll_dice with the provided DICE over NUM_SAMPLES times.
Assume that the dice always return positive outcomes.
>>> dice = make_test_dice(3)
>>> max_scoring_num_rolls(dice)
10
"""
# BEGIN PROBLEM 8
roll_doer = make_averaged(roll_dice, num_samples)
num_dice, best_roll = 0, 0
for x in range(1,11):
trial = roll_doer(x, dice)
if trial > best_roll:
num_dice, best_roll = x, trial
return num_dice
# END PROBLEM 8
def winner(strategy0, strategy1):
"""Return 0 if strategy0 wins against strategy1, and 1 otherwise."""
score0, score1 = play(strategy0, strategy1)
if score0 > score1:
return 0
else:
return 1
def average_win_rate(strategy, baseline=always_roll(4)):
"""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():
if False:
print('my strategy WR:', average_win_rate(final_strategy))
# Strategies
def bacon_strategy(score, opponent_score, margin=8, num_rolls=4):
"""This strategy rolls 0 dice if that gives at least MARGIN points,
and rolls NUM_ROLLS otherwise.
"""
# BEGIN PROBLEM 9
points = free_bacon(opponent_score)
if is_prime(points):
points = next_prime(points)
if points >= margin:
return 0
else:
return num_rolls
# END PROBLEM 9
check_strategy(bacon_strategy)
def swap_strategy(score, opponent_score, margin=8, num_rolls=4):
"""This strategy rolls 0 dice when it triggers a beneficial swap. It also
rolls 0 dice if it gives at least MARGIN points. Otherwise, it rolls
NUM_ROLLS.
"""
# BEGIN PROBLEM 10
points = free_bacon(opponent_score)
if is_prime(points):
points = next_prime(points)
if points >= margin or score + points == 2*opponent_score:
return 0
else:
return num_rolls
# END PROBLEM 10
check_strategy(swap_strategy)
##########################
# Command Line Interface #
##########################
# NOTE: Functions in this section do not need to be changed. They use features
# of Python not yet covered in the course.
@main
def run(*args):
"""Read in the command-line argument and calls corresponding functions.
This function uses Python syntax/techniques not yet covered in this course.
"""
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()
start = time.time()
check_strategy(final_strategy)
#print('my strategy WR:', average_win_rate(final_strategy))
print("check strat time is:", time.time()-start,"secs")
#print('my strategy WR:', average_win_rate(final_strategy))
#should we ask denero how fast the computer is thats running the contest?
#xeon 22 core =D
#I'll ask privately on piazza like I did with the starting order OKIE
# we dont have to fit into the 10 sec time constraint
# just have 10000 lines that we printed out somewhere else using a lot of time