-
Notifications
You must be signed in to change notification settings - Fork 0
/
hog.py
393 lines (330 loc) · 13.6 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
"""The Game of Hog."""
#Name: Arjun Mehta
#Email: [email protected]
#Partner's name: Manav Goyal
#Partner's email: [email protected]
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 #
######################
# Taking turns
def roll_dice(num_rolls, dice=six_sided):
"""Roll DICE for NUM_ROLLS times. Return either the sum of the outcomes,
or 1 if a 1 is rolled (Pig out). This calls DICE exactly NUM_ROLLS times.
num_rolls: The number of dice rolls that will be made; at least 1.
dice: A zero-argument function that returns an integer 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.'
"*** YOUR CODE HERE ***"
counter, sum_rolls ,dice_roll, current_roll= 1, 0, False, 0
while(counter<=num_rolls):
current_roll = dice()
if(current_roll==1):
dice_roll = True
sum_rolls = sum_rolls + current_roll
counter = counter + 1
if dice_roll == True:
dice_roll = False
return 1
else:
return sum_rolls
def take_turn(num_rolls, opponent_score, dice=six_sided):
"""Simulate a turn rolling NUM_ROLLS dice, which may be 0 (Free bacon).
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.
"""
assert type(num_rolls) == int, 'num_rolls must be an integer.'
assert num_rolls >= 0, 'Cannot roll a negative number of dice.'
assert num_rolls <= 10, 'Cannot roll more than 10 dice.'
assert opponent_score < 100, 'The game should be over.'
"*** YOUR CODE HERE ***"
if num_rolls > 0:
return roll_dice(num_rolls, dice)
return max(opponent_score%10, opponent_score//10) + 1
# Playing a game
def select_dice(score, opponent_score):
"""Select six-sided dice unless the sum of SCORE and OPPONENT_SCORE is a
multiple of 7, in which case select four-sided dice (Hog wild).
>>> select_dice(4, 24) == four_sided
True
>>> select_dice(16, 64) == six_sided
True
>>> select_dice(0, 0) == four_sided
True
"""
"*** YOUR CODE HERE ***"
total_score = score + opponent_score
if total_score % 7 == 0:
return four_sided
return six_sided
def other(who):
"""Return the other player, for a player WHO numbered 0 or 1.
>>> other(0)
1
>>> other(1)
0
"""
return 1 - who
def play(strategy0, strategy1, 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.
"""
who = 0 # Which player is about to take a turn, 0 (first) or 1 (second)
score, opponent_score = 0, 0
"*** YOUR CODE HERE ***"
while(score<GOAL_SCORE and opponent_score<GOAL_SCORE):
if other(who) == 1:
score += take_turn(strategy0(score, opponent_score), opponent_score, select_dice(score, opponent_score))
who = 1
else:
opponent_score += take_turn(strategy1(opponent_score, score), score, select_dice(score, opponent_score))
who = 0
if score * 2 == opponent_score or opponent_score *2 == score:
score, opponent_score = opponent_score, score
return score, opponent_score
#######################
# Phase 2: Strategies #
#######################
# Basic Strategy
BASELINE_NUM_ROLLS = 5
BACON_MARGIN = 8
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
# 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
>>> make_averaged(roll_dice, 1000)(2, dice)
6.0
In this last example, two different turn scenarios are averaged.
- In the first, the player rolls a 3 then a 1, receiving a score of 1.
- In the other, the player rolls a 5 and 6, scoring 11.
Thus, the average value is 6.0.
"""
"*** YOUR CODE HERE ***"
def average(*args):
i = 0
sum_avg = 0
while(i<num_samples):
sum_avg = sum_avg + fn(*args)
i += 1
return sum_avg/num_samples
return average
def max_scoring_num_rolls(dice=six_sided):
"""Return the number of dice (1 to 10) that gives the highest average turn
score by calling roll_dice with the provided DICE. Print all averages as in
the doctest below. Assume that dice always returns positive outcomes.
>>> dice = make_test_dice(3)
>>> max_scoring_num_rolls(dice)
1 dice scores 3.0 on average
2 dice scores 6.0 on average
3 dice scores 9.0 on average
4 dice scores 12.0 on average
5 dice scores 15.0 on average
6 dice scores 18.0 on average
7 dice scores 21.0 on average
8 dice scores 24.0 on average
9 dice scores 27.0 on average
10 dice scores 30.0 on average
10
"""
"*** YOUR CODE HERE ***"
counter, max_avg, tracker = 1, 0, 1
while(counter<=10):
avg = make_averaged(roll_dice)(counter, dice)
print(counter, "dice scores", avg , "on average")
if avg > max_avg:
max_avg = avg
tracker = counter
counter += 1
return tracker
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(BASELINE_NUM_ROLLS)):
"""Return the average win rate (0 to 1) of STRATEGY against BASELINE."""
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 # Average results
def run_experiments():
"""Run a series of strategy experiments and report results."""
if False: # Change to False when done finding max_scoring_num_rolls
six_sided_max = max_scoring_num_rolls(six_sided)
print('Max scoring num rolls for six-sided dice:', six_sided_max)
four_sided_max = max_scoring_num_rolls(four_sided)
print('Max scoring num rolls for four-sided dice:', four_sided_max)
if False: # Change to True to test always_roll(8)
print('always_roll(8) win rate:', average_win_rate(always_roll(8)))
if False: # Change to True to test bacon_strategy
print('bacon_strategy win rate:', average_win_rate(bacon_strategy))
if False: # Change to True to test swap_strategy
print('swap_strategy win rate:', average_win_rate(swap_strategy))
if True: # Change to True to test final_strategy
print('final_strategy win rate:', average_win_rate(final_strategy))
"*** You may add additional experiments as you wish ***"
# Strategies
def bacon_strategy(score, opponent_score):
"""This strategy rolls 0 dice if that gives at least BACON_MARGIN points,
and rolls BASELINE_NUM_ROLLS otherwise.
>>> bacon_strategy(0, 0)
5
>>> bacon_strategy(70, 50)
5
>>> bacon_strategy(50, 70)
0
"""
"*** YOUR CODE HERE ***"
if take_turn(0, opponent_score)>=BACON_MARGIN:
return 0
else:
return BASELINE_NUM_ROLLS
def swap_strategy(score, opponent_score):
"""This strategy rolls 0 dice when it would result in a beneficial swap and
rolls BASELINE_NUM_ROLLS if it would result in a harmful swap. It also rolls
0 dice if that gives at least BACON_MARGIN points and rolls
BASELINE_NUM_ROLLS otherwise.
>>> swap_strategy(23, 60) # 23 + (1 + max(6, 0)) = 30: Beneficial swap
0
>>> swap_strategy(27, 18) # 27 + (1 + max(1, 8)) = 36: Harmful swap
5
>>> swap_strategy(50, 80) # (1 + max(8, 0)) = 9: Lots of free bacon
0
>>> swap_strategy(12, 12) # Baseline
5
"""
"*** YOUR CODE HERE ***"
compare = score + 1 + max(opponent_score % 10, opponent_score // 10)
if compare * 2 == opponent_score:
return 0
elif opponent_score * 2 == compare:
return BASELINE_NUM_ROLLS
else:
return bacon_strategy(score, opponent_score)
def final_strategy(score, opponent_score):
"""Write a brief description of your final strategy.
*** YOUR DESCRIPTION HERE ***
Special cases and strategy used in final startegy :
1. To increase chances of forcing opponent to roll a four-sided dice
2. To check for beneficial and harmful swaps, and try to cause a beneficial
swap (by rolling either 0 or rolling 10 to force a 1) and prevent harmful swap.
3. To roll 0 in cases where winning the game is possible instead of rolling dice.
4. To take less risks in terms of num_rolls if score is more than opponent or
if rolling a four sided dice.
5. To take more risks in terms of num_rolls if score is less than opponent or if rolling
a six sided dice.
"""
"*** YOUR CODE HERE ***"
current_dice = select_dice(score, opponent_score)
bacon_number = 1 + max(opponent_score % 10, opponent_score // 10)
if (score + bacon_number + opponent_score) % 7 == 0 and opponent_score * 2 != (score+ bacon_number):
return 0
elif (score + bacon_number) * 2 == opponent_score:
return 0
if opponent_score * 2 != (score + bacon_number) and (score + bacon_number >= 100):
return 0
if (score + 1) * 2 == opponent_score:
return 10
if score > opponent_score or current_dice == four_sided:
if max(opponent_score%10, opponent_score//10) >= BACON_MARGIN:
return 0
return 4
elif opponent_score > score or current_dice == six_sided:
return 6
##########################
# 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.
def get_int(prompt, min):
"""Return an integer greater than or equal to MIN, given by the user."""
choice = input(prompt)
while not choice.isnumeric() or int(choice) < min:
print('Please enter an integer greater than or equal to', min)
choice = input(prompt)
return int(choice)
def interactive_dice():
"""A dice where the outcomes are provided by the user."""
return get_int('Result of dice roll: ', 1)
def make_interactive_strategy(player):
"""Return a strategy for which the user provides the number of rolls."""
prompt = 'Number of rolls for Player {0}: '.format(player)
def interactive_strategy(score, opp_score):
if player == 1:
score, opp_score = opp_score, score
print(score, 'vs.', opp_score)
choice = get_int(prompt, 0)
return choice
return interactive_strategy
def roll_dice_interactive():
"""Interactively call roll_dice."""
num_rolls = get_int('Number of rolls: ', 1)
turn_total = roll_dice(num_rolls, interactive_dice)
print('Turn total:', turn_total)
def take_turn_interactive():
"""Interactively call take_turn."""
num_rolls = get_int('Number of rolls: ', 0)
opp_score = get_int('Opponent score: ', 0)
turn_total = take_turn(num_rolls, opp_score, interactive_dice)
print('Turn total:', turn_total)
def play_interactive():
"""Interactively call play."""
strategy0 = make_interactive_strategy(0)
strategy1 = make_interactive_strategy(1)
score0, score1 = play(strategy0, strategy1)
print('Final scores:', score0, 'to', score1)
@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('--interactive', '-i', type=str,
help='Run interactive tests for the specified question')
parser.add_argument('--run_experiments', '-r', action='store_true',
help='Runs strategy experiments')
args = parser.parse_args()
if args.interactive:
test = args.interactive + '_interactive'
if test not in globals():
print('To use the -i option, please choose one of these:')
print('\troll_dice', '\ttake_turn', '\tplay', sep='\n')
exit(1)
try:
globals()[test]()
except (KeyboardInterrupt, EOFError):
print('\nQuitting interactive test')
exit(0)
elif args.run_experiments:
run_experiments()