Note: We recommend starting and finishing Phase 1 as soon as possible to give yourself adequate time to complete Phase 2, which is harder and more timeconsuming. You do not have to wait until after the checkpoint date to start Phase 2.
This project will require everything you have learned so far: functions, boolean expressions, conditional statements, while/for loops, and HOFs (HOFs will be taught in week 6)!
Submitting
 Phase 1 should be done independently
 You may work on 2 with your entire group
 Only 1 person from each group is required to submit the successful test screenshots
The Game
In Hog, two players alternate turns trying to be the first to end a turn with at least 100 total points. 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.
To spice up the game, we will play with some special rules:
 Pig Out. If any of the dice outcomes is a 1, the current player’s score for the turn is 1.
 Example 1: The current player rolls 7 dice, 5 of which are 1’s. They score 1 point for the turn.
 Example 2: The current player rolls 4 dice, all of which are 3’s. Since Pig Out did not occur, they score 12 points for the turn.
 Free Bacon. A player who chooses to roll zero dice scores the one more than the last digit of the product of the digits in the opponent’s score.
 Example 1: The opponent has 46 points, and the current player chooses to roll zero dice. 4 * 6 = 24; the last digit is a 4, so the current player gains 4 + 1 = 5 points.
 Example 2: The opponent has 28 points, and the current player chooses to roll zero dice. 2 * 8 = 16; the last digit is a 6, so the current player gains 6 + 1 = 7 points.
 Example 3: The opponent has 5 points, and the current player chooses to roll zero dice. 0 * 5 = 0; the last digit is a 0, so the current player gains 0 + 1 = 1 point.
 Swine Swap. After points for the turn are added to the current player’s score, if the ones digit of the current player’s score is the same as the tens digit of the opponent’s score, the two scores are swapped.
 Example 1: The current player has a total score of 41 and the opponent has 92. The current player rolls two dice that total 8. The player’s new score is 49, and the opponent’s score is 92. The ones and tens digits are the same (49 and 92), so the scores are swapped! The current player now has 92 points and the opponent has 49. The turn ends.
 Example 2: The current player has a total score of 34 and the opponent has 5. The current player rolls three dice that total 6. The player’s new score is 40, and the ones digit is the same as the opponent’s tens digit (40 and 05), so the scores are swapped. The current player now has 5 points and the opponent has 40.
 Example 3: The current player has a total score of 91 and the opponent has 12. The current player rolls five dice that total 20. The player’s new score is 111, and the ones digit is the same as the opponent’s tens digit (111 and 12), so the scores are swapped. The opponent ends the turn with 111 points and wins the game.
Download starter files
To get started, download all of the project code as a zip archive. You only have to make changes to hog.py
.
hog.py
: A starter implementation of Hogdice.py
: Functions for rolling dicehog_gui.py
: A graphical user interface for Hogop_resources.py
: A directory of tests used byop
op
: CSS autograderhog_log.txt
: Resources used by theop
autograderucb.py
: Utility functions for runninghog_gui.py
images
: A directory of images used byhog_gui.py
Logistics
You will have until Sunday, October 13 to finish the entire project. It is divided into two phases:
 Submit with Phase 1 complete by Sunday, October 6th (11:59PM)
 Submit with Phase 2 complete by Sunday, October 13th (11:59PM)
For the functions that we ask you to complete, there may be some initial code that we provide. If you would rather not use that code, feel free to delete it and start from scratch. You may also add new function definitions as you see fit.
However, please do not modify any other functions. Doing so may result in your code failing our autograder tests. Also, please do not change any function signatures (names, argument order, or number of arguments).
Throughout this project, you should be testing the correctness of your code. It is good practice to test often, so that it is easy to isolate any problems. However, you should not be testing too often, to allow yourself time to think through problems.
Autograder op
We have provided an autograder called op
to help you with testing your code and tracking your progress.
The primary purpose of op
is to test your implementations, but there are two things you should be aware of.
Before coding, check your understanding of the questions with WWPD. To run WWPD, run the following command from your terminal:
python3 op q [Question Number] u
This command will start an interactive prompt that looks like:
running wwpd
Type the answer in at the end of each "?"
>>> <Question here>
?
At the ?
, you can type what you expect the output to be. If you are correct, then this test case will be available the next time you run the autograder.
The idea is to understand conceptually what your program should do first, before you start writing any code.
Once you have finished WWPD and coding, you can check the correctness of your program using the tests:
python3 op q [Question #]
Most of the time, you will want to focus on a particular question. Use the q
option as directed in the problems below.
We recommend that you keep a backup after you finish each problem.
Finally, there is one last command implemented in the op
autograder. You can run the following code at the end of each Phase to check for completion:
python3 op p [Phase #]
Graphical User Interface
A graphical user interface (GUI, for short) is provided for you. At the moment, it doesn’t work because you haven’t implemented the game logic. Once you complete the play
function, you will be able to play a fully interactive version of Hog!
In order to render the graphics, make sure you have Tkinter, Python’s main graphics library, installed on your computer. Once you’ve done that, you can run the GUI from your terminal:
python3 hog_gui.py
Phase 1: Simulator
Important submission note: For full credit:
 Submit with Phase 1 complete by Sunday, October 6th (11:59PM)
All Phase 1 WWPD must be correct in order to progress forward.
In the first phase, you will develop a simulator for the game of Hog.
Problem 0
The dice.py
file represents dice using nonpure zeroargument functions. These functions are nonpure because they may have different return values each time they are called. The documentation of dice.py
describes the two different types of dice used in the project:
 Dice can be fair, meaning that they produce each possible outcome with equal probability. Example:
six_sided
.  For testing functions that use dice, deterministic test dice always cycle through a fixed sequence of values that are passed as arguments to the
make_test_dice
function.
Before we start writing any code, read over the dice.py
file and check your understanding by running the following WWPD:
python3 op q 0 u
This should display a prompt that looks like this:
running wwpd
>>> from hog import *
>>> test_dice = make_test_dice(4, 1, 2)
>>> test_dice()
?
You should type in what you expect the output to be. To do so, you need to first figure out what test_dice
will do, based on the description above.
You can exit the WWPD by typing ctrl+z
. NOT Command+z!
Problem 1
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 (Pig Out).
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 Pig Out happens in the middle of rolling. In this way, we correctly simulate rolling all the dice together.
Understand the problem:
Before writing any code, use the WWPD to verify your understanding of the question.
python3 op q 1 u
Write code and check your work:
Once you are done with WWPD, begin implementing your solution. You can check your correctness with:
python3 op q 1
Debugging your code interactively:
If the tests don’t pass, it’s time to debug. You can observe the behavior of your function using Python directly. First, start the Python interpreter and load the hog.py
file.
python3 i hog.py
Then, you can call your roll_dice
function on any number of dice you want. The roll_dice
function has a default argument value for dice
that is a random sixsided dice function. Therefore, the following call to roll_dice
simulates rolling four fair sixsided dice.
>>> roll_dice(4)
You will find that the previous expression may have a different result each time you call it, since it is simulating random dice rolls. You can also use test dice that fix the outcomes of the dice in advance. For example, rolling twice when you know that the dice will come up 3 and 4 should give a total outcome of 7.
>>> fixed_dice = make_test_dice(3, 4)
>>> roll_dice(2, dice=fixed_dice)
7
On most systems, you can evaluate the same expression again by pressing the up arrow or ControlP, then pressing enter or return.
If you find a problem, you need to change your
hog.py
file, save it, quit Python, start it again, and then start evaluating expressions. Pressing the up arrow should give you access to your previous expressions, even after restarting Python.
Continue debugging your code and running the ok
tests until they all pass. You should follow this same procedure of understanding the problem, implementing a solution, testing, and debugging for all the problems on this project.
Problem 2
Implement the free_bacon
helper function that returns the number of points scored by rolling 0 dice, based on the opponent’s current score
. You can assume that score
is less than 100. For a score less than 10, assume that the first of the two digits is 0.
Before writing any code, use the WWPD to verify your understanding of the question.
python3 op q 2 u
Once you are done with WWPD, begin implementing your solution. You can check your correctness with:
python3 op q 2
As noted above, you can also test free_bacon
interactively by entering python3 i hog.py
in the terminal and then calling free_bacon
with various inputs.
Problem 3
Implement the take_turn
function, which returns the number of points scored for a turn by rolling the given dice
num_rolls
times.
You will need to implement the Free Bacon rule based on opponent_score
, which you can assume is less than 100.
Your implementation of take_turn
should call both roll_dice
and free_bacon
when possible.
Before writing any code, use the WWPD to verify your understanding of the question.
python3 op q 3 u
Once you are done with WWPD, begin implementing your solution. You can check your correctness with:
python3 op q 3
Problem 4
Implement is_swap
, which returns whether or not the scores should be swapped because the ones digit of the current player’s score is the same as the tens digit of the opponent’s score.
The is_swap
function takes two arguments: the players’ scores. It returns a boolean value to indicate whether the Swine Swap condition is met.
Before writing any code, use the WWPD to verify your understanding of the question.
python3 op q 4 u
Once you are done with WWPD, begin implementing your solution. You can check your correctness with:
python3 op q 4
Problem 5
Implement the play
function, which simulates a full game of Hog. Players alternate turns rolling dice until one of the players reaches the goal
score.
To determine how much dice are rolled each turn, each player uses their respective strategy (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 wants to roll in the turn. Each strategy function should be called only once per turn. Don’t worry about the details of implementing strategies yet. You will develop them in Phase 2.
When the game ends, play
returns the final total scores of both players, with Player 0’s score first, and Player 1’s score second.
Here are some hints:
 You should use the functions you have already written! You will need to call
take_turn
with all three arguments.  Only call
take_turn
once per turn.  Enforce all the special rules.
 You can get the number of the other player (either 0 or 1) by calling the provided function
other
.  You can ignore the
say
argument to theplay
function for now. You will use it in Phase 2 of the project.
Before writing any code, use the WWPD to verify your understanding of the question.
python3 op q 5 u
Once you are done with WWPD, begin implementing your solution. You can check your correctness with:
python3 op q 5
The last test for Question 5 is a fuzz test, which checks that your
play
function works for a large number of different inputs. Failing this test means something is wrong, but you should look at other tests to see where the problem might be.
Once you are finished, activate the following code segment right below #END PROBLEM 5:
say = say(score0,score1)
After you have done this, you will be able to play a graphical version of the game. We have provided a file called hog_gui.py
that you can run from the terminal:
python3 hog_gui.py
If you don’t already have Tkinter (Python’s graphics library) installed, you’ll need to install it first before you can run the GUI.
The GUI relies on your implementation, so if you have any bugs in your code, they will be reflected in the GUI. This means you can also use the GUI as a debugging tool; however, it’s better to run the tests first.
Congratulations! You have finished Phase 1 of this project! You may use the following command in the terminal to verify that Phase 1 is complete:
python3 op p 1
Upload your Phase 1 screenshot here!
Upload files






Phase 2: Strategies
In the second phase, you will experiment with ways to improve upon the basic strategy of always rolling a fixed number of dice. First, you need to develop some tools to evaluate strategies.
Problem 6
Implement the make_averaged
function, which is a higherorder function that takes a function fn
as an argument. It returns another function that takes the same number of arguments as fn
(the function originally passed into make_averaged
). This returned function differs from the input function in that it returns the average value of repeatedly calling fn
on the same arguments. This function should call fn
a total of num_samples
times and return the average of the results.
To implement this function, you need a new piece of Python syntax! You must write a function that accepts an arbitrary number of arguments, then calls another function using exactly those arguments. Here’s how it works.
Instead of listing formal parameters for a function, we write
*args
. To call another function using exactly those arguments, we call it again with*args
. For example,
>>> def printed(fn):
... def print_and_return(*args):
... result = fn(*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 10
Read the docstring for make_averaged
carefully to understand how it is meant to work.
Before writing any code, use the WWPD to verify your understanding of the question.
python3 op q 6 u
Once you are done with WWPD, begin implementing your solution. You can check your correctness with:
python3 op q 6
Problem 7
Implement the max_scoring_num_rolls
function, 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.
Before writing any code, use the WWPD to verify your understanding of the question.
python3 op q 7 u
Once you are done with WWPD, begin implementing your solution. You can check your correctness with:
python3 op q 7
To run this experiment on randomized dice, call run_experiments
using the r
option:
python3 hog.py r
Running experiments For the remainder of this project, you can change the implementation of run_experiments
as you wish. By calling average_win_rate
, you can evaluate various Hog strategies. For example, change the first if False:
to if True:
in order to evaluate always_roll(8)
against the baseline strategy of always_roll(4)
. You should find that it wins slightly more often than it loses, giving a win rate around 0.5.
Some of the experiments may take up to a minute to run. You can always reduce the number of samples in make_averaged
to speed up experiments.
Problem 8
A strategy can take advantage of the Free Bacon rule by rolling 0 when it is most beneficial to do so. Implement bacon_strategy
, which returns 0 whenever rolling 0 would give at least margin
points and returns num_rolls
otherwise.
Before writing any code, use the WWPD to verify your understanding of the question.
python3 op q 8 u
Once you are done with WWPD, begin implementing your solution. You can check your correctness with:
python3 op q 8
Once you have implemented this strategy, change run_experiments
to evaluate your new strategy against the baseline. You should find that it wins more than half of the time.
Problem 9
A strategy can also take advantage of the Swine Swap rule. The swap_strategy
rolls 0 if it would cause a beneficial swap. It also returns 0 if rolling 0 would give at least margin
points, even if this would cause a nonbeneficial swap. Otherwise, the strategy rolls num_rolls
.
Before writing any code, use the WWPD to verify your understanding of the question.
python3 op q 9 u
Once you are done with WWPD, begin implementing your solution. You can check your correctness with:
python3 op q 9
Once you have implemented this strategy, update run_experiments
to evaluate your new strategy against the baseline. You should find that it gives a significant edge over always_roll(4)
Finally, you can use the following code segment to verify that Phase 2 is complete:
python3 op p 2
Congratulations, you have reached the end of your first project! If you haven’t already, relax and enjoy a few games of Hog with a friend.
Upload your screenshot for Phase 2 here!
Upload files






If you encounter any issues, please contact Leo, Eugene, or John through Wechat. Thanks!