
Project 1: The Game of Hog hog.zip
I know! Iâll use my
Higher-order functions to
Order higher rolls.
Introduction
Important submission note: For full credit:
- Submit with Phase 1 complete by Tuesday, Sept 6, worth 1 pt.
- Submit the complete project by Friday, Sept 9.
Try to attempt the problems in order, as some later problems will depend on earlier problems in their implementation and therefore also when running
ok
tests.You may complete the project with a partner.
You can get 1 bonus point by submitting the entire project by Thursday, Sept 8 You can receive extensions on the project deadline and checkpoint deadline, but not on the early deadline, unless youâre a DSP student with an accommodation for assignment extensions.
In this project, you will develop a simulator and multiple strategies for the dice game Hog. You will need to use control statements and higher-order functions together, as described in Sections 1.2 through 1.6 of Composing Programs, the online textbook.
When students in the past have tried to implement the functions without thoroughly reading the problem description, theyâve often run into issues. đą Read each description thoroughly before starting to code.
Rules
In Hog, two players alternate turns trying to be the first to end a turn with at least GOAL
total points, where GOAL
defaults to 100. On each turn, the current player chooses some number of dice to roll, up to 10. That playerâs score for the turn is the sum of the dice outcomes. However, a player who rolls too many dice risks:
- Sow Sad. If any of the dice outcomes is a 1, the current playerâs score for the turn is
1
.
In a normal game of Hog, those are all the rules. To spice up the game, weâll include some special rules:
Pig Tail. A player who chooses to roll zero dice scores
2 * abs(tens - ones) + 1
points; wheretens
,ones
are the tens and ones digits of the opponentâs score. The ones digit refers to the rightmost digit and the tens digit refers to the second-rightmost digit.Square Swine. After a player gains points for their turn, if the resulting score is a perfect square, then increase their score to the next higher perfect square. A perfect square is any integer
n
wheren = d * d
for some integerd
.
Phase 1: Rules of the Game
In the first phase, you will develop a simulator for the game of Hog.
Problem 1 (2 pt)
Implement the roll_dice
function in hog.py
. It takes two arguments: a positive integer called num_rolls
giving the number of dice to roll and a dice
function. It returns the number of points scored by rolling the dice that number of times in a turn: either the sum of the outcomes or 1 (Sow Sad).
- Sow Sad. If any of the dice outcomes is a 1, the current playerâs score for the turn is
1
.
Examples
To obtain a single outcome of a dice roll, call dice()
. You should call dice()
exactly num_rolls
times in the body of roll_dice
.
Remember to call dice()
exactly num_rolls
times even if Sow Sad happens in the middle of rolling. By doing so, you will correctly simulate rolling all the dice together (and the user interface will work correctly).
Note: The
roll_dice
function, and many other functions throughout the project, makes use of default argument valuesâyou can see this in the function heading:
1 def roll_dice(num_rolls, dice=six_sided): ...The argument
dice=six_sided
means that whenroll_dice
is called, thedice
argument is optional. If no value fordice
is provided, thensix_sided
is used by default.For example, calling
roll_dice(3, four_sided)
, or equivalentlyroll_dice(3, dice=four_sided)
, simulates rolling 3 four-sided dice, while callingroll_dice(3)
simulates rolling 3 six-sided dice.
1 | def roll_dice(num_rolls, dice=six_sided): |
Problem 2 (2 pt)
Implement tail_points
, which takes the playerâs opponentâs current score opponent_score
, and returns the number of points scored by Pig Tail when the player rolls 0 dice.
- Pig Tail. A player who chooses to roll zero dice scores
2 * abs(tens - ones) + 1
points; wheretens
,ones
are the tens and ones digits of the opponentâs score. The ones digit refers to the rightmost digit and the tens digit refers to the second-rightmost digit.
Examples
Donât assume that scores are below 100. Write your
tail_points
function so that it works correctly for any non-negative score.
Important: Your implementation should not use
str
, lists, or contain square brackets[
]
. The test cases will check if those have been used.
1 | def tail_points(opponent_score): |
You can also test tail_points
interactively by running python3 -i hog.py
from the terminal and calling tail_points
on various inputs.
Problem 3 (2 pt)
Implement the take_turn
function, which returns the number of points scored for a turn by rolling the given dice
num_rolls
times.
Your implementation of take_turn
should call both roll_dice
and tail_points
rather than repeating their implementations.
1 | def take_turn(num_rolls, opponent_score, dice=six_sided): |
Problem 4 (1 pt)
Add functions perfect_square
and next_perfect_square
so that square_update
returns a playerâs total score after they roll num_rolls
. You do not need to edit the body of square_update
.
- Square Swine. After a player gains points for their turn, if the resulting score is a perfect square, then increase their score to the next higher perfect square. A perfect square is any integer
n
wheren = d * d
for some integerd
.
1 | # BEGIN PROBLEM 4 |
Problem 5 (5 pt)
Implement the play
function, which simulates a full game of Hog. Players take turns rolling dice until one of the players reaches the goal
score, and the final scores of both players are returned by the function.
To determine how many dice are rolled each turn, call the current playerâs strategy function (Player 0 uses strategy0
and Player 1 uses strategy1
). A strategy is a function that, given a playerâs score and their opponentâs score, returns the number of dice that the current player will roll in the turn. An example strategy is always_roll_5
which appears above play
.
To determine the updated score for a player after they take a turn, call the update
function. An update
function 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. Two examples of update
functions are simple_update
andsquare_update
.
If a player achieves the goal score by the end of their turn, i.e. after all applicable rules have been applied, the game ends. play
will then return the final total scores of both players, with Player 0âs score first and Player 1âs score second.
Some example calls to play
are:
play(always_roll_5, always_roll_5, simple_update)
simulates two players that both always roll 5 dice each turn, playing with just the Sow Sad and Pig Tail rules.play(always_roll_5, always_roll_5, square_update)
simulates two players that both always roll 5 dice each turn, playing with the Square Swine rule in addition to the Sow Sad and Pig Tail rules (i.e. all the rules).
Important: For the user interface to work, a strategy function should be called only once per turn. Only call
strategy0
when it is Player 0âs turn and only callstrategy1
when it is Player 1âs turn.Hints:
- If
who
is the current player, the next player is1 - who
.- To call
play(always_roll_5, always_roll_5, square_update)
and print out what happens each turn, runpython3 hog_ui.py
from the terminal.
1 | def play(strategy0, strategy1, update, |
Phase 2: Strategies
In this phase, you will experiment with ways to improve upon the basic strategy of always rolling five dice. A strategy is a function that takes two arguments: the current playerâs score and their opponentâs score. It returns the number of dice the player will roll, which can be from 0 to 10 (inclusive).
Problem 6 (2 pt)
Implement always_roll
, a higher-order function that takes a number of dice n
and returns a strategy that always rolls n
dice. Thus, always_roll(5)
would be equivalent to always_roll_5
.
1 | def always_roll(n): |
Problem 7 (2 pt)
A strategy only has a fixed number of possible argument values. In a game to 100, there are 100 possible score
values (0-99) and 100 possible opponent_score
values (0-99), giving 10,000 possible argument combinations.
Implement is_always_roll
, which takes a strategy and returns whether that strategy always rolls the same number of dice for every possible argument combination.
1 | def is_always_roll(strategy, goal=GOAL): |
Problem 8 (2 pt)
Implement make_averaged
, which is a higher-order function that takes a function original_function
as an argument.
The return value of make_averaged
is a function that takes in the same number of arguments as original_function
. When we call this returned function on the arguments, it will return the average value of repeatedly calling original_function
on the arguments passed in.
Specifically, this function should call original_function
a total of total_samples
times and return the average of the results of these calls.
Important: To implement this function, you will need to use a new piece of Python syntax. We would like to write a function that accepts an arbitrary number of arguments, and then calls another function using exactly those arguments. Hereâs how it works.
Instead of listing formal parameters for a function, you can write
*args
, which represents all of the arguments that get passed into the function. We can then call another function with these same arguments by passing these*args
into this other function. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14 >>> def printed(f):
... def print_and_return(*args):
... result = f(*args)
... print('Result:', result)
... return result
... return print_and_return
>>> printed_pow = printed(pow)
>>> printed_pow(2, 8)
Result: 256
256
>>> printed_abs = printed(abs)
>>> printed_abs(-10)
Result: 10
10Here, we can pass any number of arguments into
print_and_return
via the*args
syntax. We can also use*args
inside ourprint_and_return
function to make another function call with the same arguments.
1 | def make_averaged(original_function, total_samples=1000): |
Problem 9 (2 pt)
Implement max_scoring_num_rolls
, which runs an experiment to determine the number of rolls (from 1 to 10) that gives the maximum average score for a turn. Your implementation should use make_averaged
and roll_dice
.
If two numbers of rolls are tied for the maximum average score, return the lower number. For example, if both 3 and 6 achieve a maximum average score, return 3.
You might find it useful to read the doctest and the example shown in the doctest for this problem before doing the unlocking test.
Important: In order to pass all of our tests, please make sure that you are testing dice rolls starting from 1 going up to 10, rather than from 10 to 1.
1 | def max_scoring_num_rolls(dice=six_sided, total_samples=1000): |
Problem 10 (2 pt)
A strategy can try to take advantage of the Pig Tail rule by rolling 0 when it is most beneficial to do so. Implement tail_strategy
, which returns 0 whenever rolling 0 would give at least threshold
points and returns num_rolls
otherwise. This strategy should not also take into account the Square Swine rule.
Hint: You can use the
tail_points
function you defined in Problem 2.
1 | def tail_strategy(score, opponent_score, threshold=12, num_rolls=6): |
Problem 11 (2 pt)
A better strategy will take advantage of both Pig Tail and Square Swine in combination. Even a small number of pig tail points can lead to large gains. For example, if a player has 31 points and their opponent has 42, rolling 0 would bring them to 36 which is a perfect square, and so they would end the turn with 49 points: a gain of 49 - 31 = 18!
The square_strategy
returns 0 whenever rolling 0 would result in a score that is at least threshold
points more than the playerâs score at the start of turn.
Hint: You can use the
square_update
function.
1 | def square_strategy(score, opponent_score, threshold=12, num_rolls=6): |
You should find that running python3 hog.py -r
now shows a win rate for square_strategy
close to 62%.
Optional: Problem 12 (0 pt)
Implement final_strategy
, which combines these ideas and any other ideas you have to achieve a high win rate against the baseline strategy. Some suggestions:
- If you know the goal score (by default it is 100), thereâs no benefit to scoring more than the goal. Check whether you can win by rolling 0, 1 or 2 dice. If you are in the lead, you might decide to take fewer risks.
- Instead of using a threshold, roll 0 whenever it would give you more points on average than rolling 6.
1 | def final_strategy(score, opponent_score): |