I know! I'll use my
Higher-order functions to
Order higher rolls.
In this project, you will develop a simulator and multiple strategies for the dice game Hog. You will need to use control and higher-order functions together, from Sections 1.1 through 1.6 of the Composing Programs online text.
In Hog, two players alternate turns trying to reach 100 points first. On each turn, the current player chooses some number of dice to roll, up to 10. Her turn score is the sum of the dice outcomes, unless any of the dice come up a 1, in which case the score for her turn is only 1 point (the Pig out rule).
To spice up the game, we will play with some special rules:
This project includes seven files, but all of your changes will be made to the first one, and it is the only one you should need to read and understand. To get started, download all of the project code as a zip archive.
A starter implementation of Hog. | |
Functions for rolling dice. | |
Utility functions for CS 61A. | |
A graphical user interface for Hog. | |
Utility functions for grading. |
The autograder also uses two files called locked_tests.pkl and unlocked_tests.pkl. If you need to download them again, make sure to download both files.
This is a two-week project. You are strongly encouraged to complete this project with a partner, although you may complete it alone.
Start early! The amount of time it takes to complete a project (or any program) is unpredictable.
You are not alone! Ask for help early and often -- the TAs, lab assistants, and your fellow students are here to help. Try attending office hours or posting on Piazza.
In the end, you and your partner will submit one project. The project is worth 20 points. 17 points are assigned for correctness, and 3 points for the overall composition of your program.
The only file that you are required to submit is hog.py
. You do
not need to modify or turn in any other files to complete the project. To submit
the project, change to the directory where hog.py
is located and
run submit proj1
. Expect a response via email whenever you
submit.
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, do not change any function signatures (names, argument order, or number of arguments).
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 finish Problem 4 (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
Once you're done with Problem 9, you can play against the final strategy that you've created!
python3 hog_gui.py -f
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.
We have provided an autograder to help you with testing your code, but there is a catch. At first, most of the test cases are locked. To unlock tests for a particular question, run the following command from your terminal:
python3 autograder.py -u q1
This command will start an interactive prompt that looks like this:
Unlocking tests for q1 ====================== At each "?", type in what you would expect the output to be if you had implemented q1 >>> counted_dice = make_test_dice(4, 1, 2) >>> roll_dice(2, make_test_dice(4, 6, 1)) ?
At the ?
, you can type what you expect the output to
be. If you get it right, the test case you answered 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. In general, it is good practice to think through your program first instead of blindly writing code.
Once you have unlocked some tests and written some code, you check the correctness of your program using the tests that you unlocked:
python3 autograder.py -q q1
This will run the autograder on all unlocked tests for question 1. For example, the following output shows an error in question 1:
Test Q1 ======= Test case failed: --------------- >>> counted_dice = make_test_dice(4, 1, 2) >>> roll_dice(2, make_test_dice(4, 6, 1)) None # Error: expected ... got None
To help with debugging, autograder.py
also provides an
interactive session with the following command:
python3 autograder.py -q q1 -i
If an error occurs, the autograder will open an interactive Python shell for you to use:
Test Q1 ======= >>> counted_dice = make_test_dice(4, 1, 2) >>> roll_dice(2, make_test_dice(4, 6, 1)) None # Error: expected ... got None # Interactive console # Type exit() to quit >>>
One last note: you might have noticed two files called
locked_tests.pkl
and unlocked_tests.pkl
that
came with the project. These two files are used to store autograder
tests, so make sure not to modify them. If you need to get a
fresh copy, you can follow these links for
locked_tests.pkl and
unlocked_tests.pkl (make sure to
download both).
In the first phase, you will develop a simulator for the game of Hog.
Problem 0 (0 pts). Before we start writing any code, let's take a look at the autograder. As mentioned in the Testing section, the autograder's test cases are initially locked. You will need to unlock test cases before you can use the autograder to test your code!
To unlock test cases for Problem 1 (see below), use the following command:
python3 autograder.py -u q1
This should display a prompt that looks like this:
Unlocking tests for Q1 ====================== At each "?", type in what you would expect the output to be if you had implemented Q1 Type exit() to quit >>> roll_dice(2, make_test_dice(4, 6, 1)) ?
As noted in the prompt, you should type in what you expect the
output to be. To do so, you need to first figure out what
roll_dice
does. Note: roll_dice
does not actually work yet, because you haven't written code for it
(that's for Problem 1); you are just filling in what you would
expect it to return.
roll_dice
function takes two arguments: the
number of dice to roll; and a dice
function. The
dice
function should be called exactly the number
of times specified by the first argument, even if a 1 is rolled.
roll_dice
should return the sum of all dice rolls if no
1's are rolled, or it should return 1 if at least one 1 was
rolled.make_test_dice
function creates a special
dice
function that is deterministic (i.e.
non-random). The outcomes of this dice
will cycle through
the inputs of make_test_dice
. In the example above, the
first roll would be 4, the second roll would be 6, the third roll
would be 1, and the fourth roll would cycle back to 4.
Note: you can exit the unlocker by typing "exit()" (without quotes). Typing Ctrl-C to exit out of the unlocker has been known to cause problems, so avoid using that to quit.
Unlock the tests for Problem 1. When you are done, you will be able to use the autograder to test your code:
python3 autograder.py -q q1
This will display the following output:
Test Q1 ======= Test case failed: ----------------- >>> roll_dice(2, make_test_dice(4, 6, 1)) None # Error: expected ... got None
Proceed to Problem 1 to start writing code!
Problem 1 (2 pt). The roll_dice
function in hog.py
returns the number of points scored by
rolling a fixed positive number of dice: either the sum of the dice or 1. To
obtain a single outcome of a dice roll, call dice()
. You should
call this function exactly num_rolls
times in your
implementation. The only rule you need to consider for this problem is Pig
out.
You should have unlocked the autograder test cases in Problem 0. To test the correctness of your implementation with your unlocked tests, use this command:
python3 autograder.py -q q1
You can also open an interactive Python shell if an error occurs by
adding a -i
option to the end:
python3 autograder.py -q q1 -i
Problem 2 (1 pt). The take_turn
function, which returns the number of points scored for the turn. You will need
to implement the Free bacon rule here. You can assume that
opponent_score
is less than 100. Your implementation should call
roll_dice
.
Unlock, implement and test your implementation before moving on:
python3 autograder.py -u q2 python3 autograder.py -q q2
As before, you can also open an interactive Python shell if an error
occurs by adding a -i
option to the end:
python3 autograder.py -q q2 -i
Problem 3 (1 pt). select_dice
is a
helper function that will simplify the implementation of play
(next
problem). The function select_dice
helps enforce the Hog
wild special rule. This function takes two arguments: the scores for the
current and opposing players.
Unlock, implement and test your implementation before moving on:
python3 autograder.py -u q3 python3 autograder.py -q q3
As before, you can also open an interactive Python shell if an error
occurs by adding a -i
option to the end:
python3 autograder.py -q q3 -i
Problem 4 (3 pt). Finally, implement the play
function, which simulates a full game of Hog. Players alternate turns, each
using the strategy originally supplied, until one of the players reaches the
goal
score. 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:
select_dice
), as well as the Swine swap special
rule here.take_turn
function that you've
already written.other
. For example, other(0)
evaluates to 1.
strategy0
and strategy1
) takes two
arguments: scores for the current player and opposing player. A strategy
function returns the number of dice that the current player wants to roll
in the turn. Don't worry about details of implementing strategies yet. You
will develop them in Phase 2.Autograder tests for this question are already unlocked for you! Test your implementation before moving on:
python3 autograder.py -q q4
Once you are finished, 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!
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 5 (2 pt). Implement the make_averaged
function. This higher-order function takes a function fn
as an
argument. It returns another function that takes the same number of arguments as
the original. 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.
Note: If the input function fn
is a non-pure function
(for instance, the random
function), then make_averaged
will also be a non-pure function.
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
Read the docstring for make_averaged
carefully to understand how
it is meant to work.
Autograder tests for this question have already been unlocked for you! Test your implementation before moving on:
python3 autograder.py -q q5
Problem 6 (2 pt). 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
. It should print out the average for each possible
number of rolls, as in the doctest for max_scoring_num_rolls
.
Note: 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.
Autograder tests for this question have already been unlocked for you! Test your implementation before moving on:
python3 autograder.py -q q6To 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 ofrun_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(5)
. You should find that it loses
more often than it wins, giving a win rate below 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 7 (1 pt). 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.
Unlock, implement and test your implementation before moving on:
python3 autograder.py -u q7 python3 autograder.py -q q7
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 8 (2 pt). A strategy can also take advantage of
the Swine swap rule. The swap_strategy
num_rolls
if rolling 0 would cause a harmful
swap that loses points.
margin
points and roll num_rolls
otherwise.
Unlock, implement and test your implementation before moving on:
python3 autograder.py -u q8 python3 autograder.py -q q8
Once you have implemented this strategy, update run_experiments
to evaluate your new strategy against the baseline. You should find that it
performs even better than bacon_strategy
, on average.
At this point, run the entire autograder to see if there are any tests that don't pass.
python3 autograder.py -a
Problem 9 (3 pt). Implement final_strategy
,
which combines these ideas and any other ideas you have to achieve a win rate
of at least 0.59 (for full credit) against the baseline always_roll(5)
strategy.
(At the very least, try to achieve a win rate above 0.54 for partial
credit.)
Some ideas:
Note: You may want to increase the number of samples to improve the approximation of your win rate. The course autograder will compute your exact average win rate (without sampling error) for you once you submit your project, and it will send it to you in an email.
You can also play against your final strategy with the graphical user interface:
python3 hog_gui.py -f
The GUI will alternate which player is controlled by you.
Congratulations, you have reached the end of your first CS 61A project!