Starting from:

$25

cs61a - Project 1 -The Game of Hog - Solved

hog.zip (hog.zip)

Order higher rolls.



Rules
In Hog, two players alternate turns trying to be the rst 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. 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.

 

•   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 Sow Sad did not occur, they score 12 points for the turn.

In a normal game of Hog, those are all the rules. To spice up the game, we'll include some special rules:

•   Piggy Points. A player who chooses to roll zero dice scores k + 4 points, where k is the absolute value of the tens digit minus the ones digit in the opponent's

score. If the opponent's score is only one digit, assume the tens digit is 0. You may not assume that the score is under 100 .

 

•   Example 1: The current player rolls zero dice and the opponent has a score of 14.

|1 - 4| = 3 , so the current player will receive 3 + 4 = 7 points.

•   Example 2: The current player rolls zero dice and the opponent has a score of 50.

|5 - 0| = 5 , so the current player will receive 5 + 4 = 9 points.

•   Example 3: The current player rolls zero dice and the opponent has a score of 9.

|0 - 9| = 9 , so the current player will receive 9 + 4 = 13 points.

•   Example 4: The current player rolls zero dice and the opponent has a score of 156. |5 - 6| = 1 , so the current player will receive 1 + 4 = 5 points.

•   More Boar. After the points for the turn are added to the current player’s score, the current player takes an extra turn if the minimum digit of the current player's score is strictly smaller than the minimum digit of the opponent's score and the maximum digit of the current player's score is strictly larger than the maximum digit of the opponent's score. You may not assume that the scores are under 100 . The More Boar calculation should be done on the current player's score after the points from the current turn are added. More Boar can be activated multiple times in a row for the same player (see Example 4).

 

•   Example 1: After the points are added, the current player has a score of 25 and the opponent has a score of 43. Since 2 < 3 , and 5 > 4 , the current player takes an extra turn.

•   Example 2: After the points are added, the current player has a score of 32 and the opponent has a score of 33. Since the current player's maximum digit (3) is not strictly larger than the opponent's maximum digit ( 3 = 3 ), the current player does not take an extra turn.

•   Example 3: After the points are added, the current player has a score of 7 and the opponent has a score of 10. Since the current player's score only has one digit, 7 is both the maximum and minimum digit of the current player's score, and 0 is the minimum digit of the opponent’s score. Since 7 >= 0 , the current player does

not take an extra turn.

•   Example 4: After the points are added, the current player has a score of 25 and the opponent has a score of 43. Like in Example 1, the current player takes an extra turn. If the current player then rolls a 1 and now has a score of 26, More Boar activates again and the current player takes yet another extra turn.

Final Product
Our sta solution to the project can be played at hog.cs61a.org (https://hog.cs61a.org) -- try it out! When you nish the project, you'll have implemented a signicant part of this game yourself.

Download starter les
To get started, download all of the project code as a zip archive (hog.zip). Below is a list of all the les you will see in the archive. However, you only have to make changes to hog.py .

•     hog.py : A starter implementation of Hog

•     dice.py : Functions for rolling dice

•     hog_gui.py : A graphical user interface (GUI) for Hog

•     ucb.py : Utility functions for CS 61A

•     ok : CS 61A autograder

•     tests : A directory of tests used by ok

•     gui_files : A directory of various things used by the web GUI

•     calc.py : A le you can use to approximately test your nal strategy

You may notice some les other than the ones listed above too -- those are needed for making the autograder and portions of the GUI work. Please do not modify any les other than hog.py .

Logistics


You will turn in the following les:

• hog.py

You do not need to modify or turn in any other les to complete the project. To submit the project, run the following command:

 

You will be able to view your submissions on the Ok dashboard (http://ok.cs61a.org).

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 denitions as you see t.

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.

We have provided an autograder called ok to help you with testing your code and tracking your progress. The rst time you run the autograder, you will be asked to log in with your Ok account using your web browser. Please do so. Each time you run ok , it will back up your work and progress on our servers.

The primary purpose of ok is to test your implementations.


If you do not want us to record a backup of your work or information about your progress, you can run

 

With this option, no information will be sent to our course servers. If you want to test your code interactively, you can run

 

with the appropriate question number (e.g. 01 ) inserted. This will run the tests for that question until the rst one you failed, then give you a chance to test the functions you wrote interactively.

You can also use the debugging print feature in OK by writing

 

which will produce an output in your terminal without causing OK tests to fail with extra output.

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!

Once you've done that, you can run the GUI from your terminal:

 

The GUI is an open-source project hosted on Github (https://github.com/Cal-CS-61ASta/hog-gui).

Phase 1: Simulator
In the rst phase, you will develop a simulator for the game of Hog.

 Getting Started Video

Phase 1 Getting Started Videos
This video provides some helpful direction for tackling the problems on this phase of Hog.

Problem 0 (0 pt)
The dice.py le represents dice using non-pure zero-argument functions. These functions are non-pure because they may have dierent return values each time they are called. The documentation of dice.py describes the two dierent types of dice used in the project:

•   A fair dice produces each possible outcome with equal probability. Two fair dice are already dened, four_sided and six_sided , and are generated by the

make_fair_dice function.

•   A test dice is deterministic: it always cycles through a xed sequence of values that are passed as arguments. Test dice are generated by the make_test_dice function.

Before writing any code, read over the dice.py le and check your understanding by unlocking the following tests.

 

This should display a prompt that looks like this:

 

You should type in what you expect the output to be. To do so, you need to rst gure out what test_dice will do, based on the description above.

You can exit the unlocker by typing exit() . Typing Ctrl-C on Windows to exit out of the unlocker has been known to cause problems, so avoid doing so.

In general, for each of the unlocking tests, you might nd it helpful to read through the provided skeleton for that problem before attempting the unlocking test.

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).

The Sow Sad rule:
• Sow Sad. 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 Sow Sad did not occur, they score 12 points for the turn.

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. In this way, you

correctly simulate rolling all the dice together.

Understand the problem:

Before writing any code, unlock the tests to verify your understanding of the question. Note: you will not be able to test your code using OK until you unlock the test cases for the corresponding question.

 

Write code and check your work:

Once you are done unlocking, begin implementing your solution. You can check your correctness with:

 

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 le.

 

Then, you can call your roll_dice function on any number of dice you want. The roll_dice function has a default argument value (http://composingprograms.com /pages/14-designing-functions.html#default-argument-values) for dice that is a random six-sided dice function. Therefore, the following call to roll_dice simulates rolling four fair six-sided dice.

 

You will nd that the previous expression may have a dierent result each time you call it, since it is simulating random dice rolls. You can also use test dice that x 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.

 

On most systems, you can evaluate the same expression again by pressing the up arrow, then pressing enter or return. To evaluate earlier commands, press the up arrow repeatedly.

If you nd a problem, you need to change your hog.py le, save it, quit Python, start Python 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 in this project.

One more debugging tip: to start the interactive interpreter automatically upon failing an ok test, use -i . For example, python3 ok -q 01 -i will run the tests for question 1, then start an interactive interpreter with hog.py loaded if a test fails.
Problem 2 (1 pt)
Implement piggy_points , which takes the opponent's current score and returns the number of points scored by rolling 0 dice.

The Piggy Points rule:
• Piggy Points. A player who chooses to roll zero dice scores k + 4 points, where k is the absolute value of the tens digit minus the ones digit in the opponent's

score. If the opponent's score is only one digit, assume the tens digit is 0. You may not assume that the score is under 100 .

 

◦ Example 1: The current player rolls zero dice and the opponent has a score of 14. |1 - 4| = 3 , so the current player will receive 3 + 4 = 7 points.

◦ Example 2: The current player rolls zero dice and the opponent has a score of 50. |5 - 0| = 5 , so the current player will receive 5 + 4 = 9 points.

◦ Example 3: The current player rolls zero dice and the opponent has a score of 9. |0 - 9| = 9 , so the current player will receive 9 + 4 = 13 points.

◦ Example 4: The current player rolls zero dice and the opponent has a score of 156. |5 - 6| = 1 , so the current player will receive 1 + 4 = 5 points.

You are allowed to implement this function in any way you want as long as you do not use for loops or square brackets [ ] in your implementation. You don't have to follow this recommended method or use the provided starter code.

Before writing any code, unlock the tests to verify your understanding of the question.

 

Once you are done unlocking, begin implementing your solution. You can check your correctness with:

 

You can also test piggy_points interactively by entering python3 -i hog.py in the terminal and then calling piggy_points with 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 piggy_points when possible.

Before writing any code, unlock the tests to verify your understanding of the question.

 

Once you are done unlocking, begin implementing your solution. You can check your correctness with:

 

 Pair programming? (/~cs61a/su21/articles/pair-programming) Remember to alternate between driver and navigator roles! The driver controls the keyboard; the navigator watches, asks questions, and suggests ideas.

Problem 4 (2 pt)
Implement more_boar , which takes the current player and opponent scores and returns whether the current player will take another turn due to More Boar.

Hint: You might nd the Python builtin max and min functions useful.

The More Boar rule:
• More Boar. After the points for the turn are added to the current player’s score, the current player takes an extra turn if the minimum digit of the current player's score is strictly smaller than the minimum digit of the opponent's score and the maximum digit of the current player's score is strictly larger than the maximum digit of the opponent's score. You may not assume that the scores are under 100 . The More Boar calculation should be done on the current player's score after the points from the current turn are added. More Boar can be activated multiple times in a row for the same player (see Example 4).

 

◦ Example 1: After the points are added, the current player has a score of 25 and the opponent has a score of 43. Since 2 < 3 , and 5 > 4 , the current player takes an extra turn.

◦ Example 2: After the points are added, the current player has a score of 32 and the opponent has a score of 33. Since the current player's maximum digit (3) is not strictly larger than the opponent's maximum digit ( 3 = 3 ), the current player does not take an extra turn.

◦ Example 3: After the points are added, the current player has a score of 7 and the opponent has a score of 10. Since the current player's score only has one digit, 7 is both the maximum and minimum digit of the current player's score, and 0 is the minimum digit of the opponent’s score. Since 7

>= 0 , the current player does not take an extra turn.

◦ Example 4: After the points are added, the current player has a score of 25 and the opponent has a score of 43. Like in Example 1, the current player takes an extra turn. If the current player then rolls a 1 and now has a score of 26, More Boar activates again and the current player takes yet another extra turn.

Before writing any code, unlock the tests to verify your understanding of the question.

 

Once you are done unlocking, begin implementing your solution. You can check your correctness with:

 

Problem 5 (4 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.

A turn is dened as one roll of the dice, as the same player can take multiple turns in a row.

To determine how many 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 will roll in the turn. Don't worry about implementing strategies yet; you'll do that in Phase 3.

When the game ends, play returns the nal total scores of both players, with Player 0's score rst and Player 1's score second.

Note: Each strategy function should be called only once per turn. This means please only call strategy0 when it is Player 0's turn and only call strategy1 when it is Player 1's turn. Otherwise, the GUI and some ok tests will get confused.

Note: When one player achieves the goal score, the game ends immediately and the other player doesn't get to play another turn.

Hints:

•   You should call the functions you have implemented already.

•   Call take_turn with four arguments (don't forget to pass in the goal ). Only call take_turn once per turn.

•   Call more_boar to determine if the current player will take another turn due to More Boar.

•   You can get the number of the next player (either 0 or 1) by calling the provided function next_player .

•   You can ignore the say argument to the play function for now. You will use it in Phase 2 of the project.

•   For the unlocking tests, hog.always_roll refers to the always_roll function dened in hog.py .

Rules Clarication: A player can take more than two consecutive turns. For example, if the score after their rst turn is 29 vs 55, they go again due to More Boar. If they score 9 points and now the score is 38 vs 55, they go a third time again due to More Boar. If they score 10 points and now the score is 48 vs 55, they go a fourth time in a row.

Before writing any code, unlock the tests to verify your understanding of the question.

 

Once you are done unlocking, begin implementing your solution. You can check your correctness with:

 

Once you are nished, you will be able to play a graphical version of the game. We have provided a le called hog_gui.py that you can run from the terminal:

 

The GUI relies on your implementation, so if you have any bugs in your code, they will be reected in the GUI. This means you can also use the GUI as a debugging tool; however, it's better to run the tests rst.

Make sure to submit your work so far before the checkpoint deadline:

 

Check to make sure that you did all the problems in Phase 1:

 

Congratulations! You have nished Phase 1 of this project!

 Pair programming? (/~cs61a/su21/articles/pair-programming) This is a good time to switch roles! Switching roles makes sure that you both benet from the learning experience of being in each role.

Phase 2: Commentary
In the second phase, you will implement commentary functions that print remarks about the game after each turn, such as, "Player 1 has reached a new maximum point gain. 22 point(s)!"

A commentary function takes two arguments, Player 0's current score and Player 1's current score. It can print out commentary based on either or both current scores and any other information in its parent environment. Since commentary can dier from turn to turn depending on the current point situation in the game, a commentary function always returns another commentary function to be called on the next turn.

The only side eect of a commentary function should be to print.

Commentary examples
The function say_scores in hog.py is an example of a commentary function that simply announces both players' scores. Note that say_scores returns itself, meaning that the same commentary function will be called each turn.

 

The function announce_lead_changes is an example of a higher-order function that returns a commentary function that tracks lead changes. A dierent commentary function will be called each turn.

 

You should also understand the function both , which takes two commentary functions ( f and g ) and returns a new commentary function. This returned commentary function returns another commentary function which calls the functions returned by calling f and g , in that order.

 

Problem 6 (2 pt)
 Getting Started Video
Update your play function so that a commentary function is called at the end of each turn. The return value of calling a commentary function gives you the commentary function to call on the next turn.

For example, say(score0, score1) should be called at the end of the rst turn. Its return value (another commentary function) should be called at the end of the second turn. Each consecutive turn, call the function that was returned by the call to the previous turn's commentary function.

Hint: For the unlocking tests for this problem, remember that when calling print with multiple arguments, Python will put a space between each of the arguments. For example,
 

Before writing any code, unlock the tests to verify your understanding of the question.

 

Once you are done unlocking, begin implementing your solution. You can check your correctness with:

 

Problem 7 (3 pt)
 Getting Started Video
Implement the announce_highest function, which is a higher-order function that returns a commentary function. This commentary function announces whenever a particular player gains more points in a turn than ever before. For example, announce_highest(1) ignores Player 0 entirely and just prints information about Player 1. (So does its return value; another commentary function about only Player 1.)

To compute the gain, it must compare the score from last turn ( last_score ) to the score from this turn for the player of interest (designated by the who argument). This function must also keep track of the highest gain for the player so far, which is stored as running_high .

The way in which announce_highest announces is very specic, and your implementation should match the doctests provided. Don't worry about singular versus plural when announcing point gains; you should simply use "point(s)" for both cases.

Hint: The announce_lead_changes function provided to you is an example of how to keep track of information using commentary functions. If you are stuck, rst make sure you understand how announce_lead_changes works.

Hint. If you're getting a local variable [var] reference before assignment error:

This happens because in Python, you aren't normally allowed to modify variables dened in parent frames. Instead of reassigning [var] , the interpreter thinks you're trying to dene a new variable within the current frame. We'll learn about how to work around this in a future lecture, but it is not required for this problem.

To x this, you have two options:

1)       Rather than reassigning [var] to its new value, create a new variable to hold that new value. Use that new variable in future calculations.

2)       For this problem specically, avoid this issue entirely by not using assignment statements at all. Instead, pass new values in as arguments to a call to announce_highest .
Before writing any code, unlock the tests to verify your understanding of the question.

 

Once you are done unlocking, begin implementing your solution. You can check your correctness with:

 

When you are done, you will see commentary in the GUI:

 

The commentary in the GUI is generated by passing the following function as the say argument to play .

 

Great work! You just nished Phase 2 of the project!

 Pair programming? (/~cs61a/su21/articles/pair-programming) Celebrate, take a break, and switch roles!

Phase 3: Strategies
In the third phase, you will experiment with ways to improve upon the basic strategy of always rolling a xed number of dice. First, you need to develop some tools to evaluate strategies.

Problem 8 (2 pt)
 Getting Started Video
Implement the make_averaged function, which is a higher-order function that takes a function original_function as an argument. It returns another function that takes the same number of arguments as original_function (the function originally passed into

make_averaged ). This returned function diers from the input function in that it returns

the average value of repeatedly calling original_function on the same arguments. This function should call original_function a total of trials_count 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, you can write *args . To call another function using exactly those arguments, you call it again with *args . For example:

 

Read the docstring for make_averaged carefully to understand how it is meant to work.

Before writing any code, unlock the tests to verify your understanding of the question.

 

Once you are done unlocking, begin implementing your solution. You can check your correctness with:

 

Problem 9 (2 pt)
 Getting Started Video
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.

You might nd it useful to read the doctest and the example shown in the doctest for this problem before doing the unlocking test.

IMPORTANT NOTE: 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 starting from 10 to

1.
Before writing any code, unlock the tests to verify your understanding of the question.

 

Once you are done unlocking, begin implementing your solution. You can check your correctness with:

 

Running experiments:

To run this experiment on randomized dice, call run_experiments using the -r option:

 

For the remainder of this project, you can change the implementation of

run_experiments as you wish. The function includes calls to average_win_rate for

evaluating various Hog strategies, but most of the calls are currently commented out.

You can un-comment the calls to try out strategies, like to compare the win rate for

always_roll(8) to the win rate for always_roll(6) .

Some of the experiments may take up to a minute to run. You can always reduce the number of trials in your call to make_averaged to speed up experiments.

Running experiments won't aect your score on the project.

 Pair programming? (/~cs61a/su21/articles/pair-programming) We suggest switching roles now, if you haven't recently. Almost done!

Problem 10 (1 pt)
 Getting Started Video
A strategy can try to take advantage of the Piggy Points rule by rolling 0 when it is most benecial to do so. Implement piggypoints_strategy , which returns 0 whenever rolling 0 would give at least cutoff points and returns num_rolls otherwise.

Hint: You can use the function piggy_points you dened in Problem 2
Before writing any code, unlock the tests to verify your understanding of the question.

 

Once you are done unlocking, begin implementing your solution. You can check your correctness with:

 

Once you have implemented this strategy, change run_experiments to evaluate your new strategy against the baseline. Is it better than just rolling 4?

Problem 11 (2 pt)
 Getting Started Video
A strategy can also take advantage of the More Boar rules. The more boar strategy always rolls 0 if doing so triggers another turn. In other cases, it rolls 0 if rolling 0 would give at least cutoff points. Otherwise, the strategy rolls num_rolls .

Hint: You can use the function piggypoints_strategy you dened in Problem 10

Hint: Remember that the more_boar check should be done after the points from piggy_points have been added to the score.
Before writing any code, unlock the tests to verify your understanding of the question.

 

Once you are done unlocking, begin implementing your solution. You can check your correctness with:

 

Once you have implemented this strategy, update run_experiments to evaluate your new strategy against the baseline. You should nd that it gives a signicant edge over always_roll(6) .

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 always_roll(6) strategy. Some suggestions:

•     more_boar_strategy is a good default strategy to start with.

•     If you know the goal score (by default it is 100), there's no point in 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 take fewer risks.

•     Try to force another turn.

•     Choose the num_rolls and cutoff arguments carefully.

•     Take the action that is most likely to win the game.

You can check that your nal strategy is valid by running Ok.

 

You will also eventually be able to check your exact nal win rate by running

 

This should pop up a window asking for you to conrm your identity, and then it will print out a win rate for your nal strategy.

You can also play against your nal strategy with the graphical user interface:

 

The GUI will alternate which player is controlled by you.

More products