Hog
Build a two-player dice game in Swift, then use higher-order functions to write, test, and compare strategies that play it.
Hog is the first project in CS61A, and this is a Swift version of it. You will build a two-player dice game one function at a time, then write strategies, which are functions that decide how to play, and pass them to the game as values. By the end, your own strategy should beat a simple opponent most of the time.
The project uses everything in Unit 1 through Lesson 6: functions, conditionals and loops, higher-order functions, closures, and abstraction. It does not need recursion.
Getting started
Download the starter file, hog.swift, and put it in a folder of its own. It is one file with three parts: provided code at the top, the ten problems in the middle, and a test runner at the bottom.
Run the tests for everything, or for one problem:
swift hog.swift test
swift hog.swift test 3
At the start almost every check fails. After each problem, run its tests
until they pass, then move on. When all ten are done, swift hog.swift test
ends with All tests passed., and you can play against your own strategy:
swift hog.swift play
Write code only between the BEGIN PROBLEM and END PROBLEM lines, and do not
change anything below // MARK: - Tests. The starter compiles as given, with
a few warnings about unused variables in the unfinished play function; they
disappear once you write it.
The rules
Two players take turns trying to be the first to reach 100 points. On each turn, the current player chooses to roll between zero and ten dice. The turn’s points are added to that player’s score.
- Sow Sad. If any of the dice comes up 1, the turn scores exactly 1 point, no matter what the other dice show.
- Boar Brawl. Rolling zero dice scores three times the absolute difference between the tens digit of the opponent’s score and the ones digit of the current player’s score, or 1 point if that is smaller. With a score of 21 against 46, that is 3 × |4 − 1| = 9.
- Sus Fuss. After a turn, if a player’s score has exactly 3 or 4 positive factors, it increases to the next prime number. For example, 21 has the factors 1, 3, 7, and 21, so a score of 21 becomes 23.
The provided code
Read the top of the file before starting. Four definitions matter throughout:
typealias Dice = () -> Int: a die is a function that returns the next roll each time it is called. Real dice and test dice are both just functions with this type.makeFairDice(sides:seed:)returns dice driven by a seeded pseudo-random generator, so the same seed replays the same game.makeTestDice(4, 6, 1)returns dice that roll 4, 6, 1, 4, 6, 1, … forever, which the tests use.typealias Strategy = (Int, Int) -> Inttakes your score and then the opponent’s, and returns how many dice to roll.typealias Update = (Int, Int, Int, Dice) -> Inttakes the number of dice, your score, the opponent’s score, and the dice, and returns your score after the turn.simpleUpdateis provided; you will writesusUpdate.
Phase 1: Simulating a turn
Problem 1: rollDice
Implement rollDice(_:dice:). Call dice() exactly numRolls times, even
after a 1 appears, because the dice function keeps its own state and the
next turn must start from the right place. Return the sum of the outcomes,
or 1 if any outcome was 1.
Problem 2: boarBrawl
Implement boarBrawl(player:opponent:) using / and % to take digits
apart. A score of 100 has tens digit 0; a score below 10 has tens digit 0.
Problem 3: takeTurn
Implement takeTurn(_:player:opponent:dice:), which returns the points for
one turn: Boar Brawl for zero dice, and rollDice otherwise. Rolling zero
dice must not call dice at all.
Problem 4: Sus Fuss
Implement numFactors(_:), isPrime(_:), susPoints(_:), and
susUpdate(_:_:_:_:). susUpdate is simpleUpdate followed by
susPoints. Counting factors only needs to try divisors up to √n: every
divisor k below √n comes with a partner n / k above it.
Phase 2: Playing a game
Problem 5: play
Implement play, which simulates a whole game and returns both final
scores. Player 0 goes first, and players alternate turns. On each turn, ask
the current player’s strategy how many dice to roll (passing the player’s
own score first), then use update to compute that player’s new score. The
game ends as soon as either score reaches goal; if a score already starts
at the goal, no turns are played.
play never needs to know what the rules are. It takes them as a
parameter, update, and the tests call it with both simpleUpdate and
susUpdate. That is Lesson 6’s abstraction barrier at work.
Problem 6: alwaysRoll and isAlwaysRoll
alwaysRoll(_:) returns a strategy that ignores the scores. isAlwaysRoll
checks whether a strategy gives the same answer for every pair of scores
from 0 to 99: compare every answer with the answer for (0, 0).
Phase 3: Experiments
Problem 7: makeAveraged
makeAveraged(_:samples:) takes a function with no arguments and returns a
function that calls it samples times and returns the average as a
Double. Averaging a random function estimates its expected value.
Problem 8: maxScoringNumRolls
For each number of dice from 1 to 10, estimate the average score of a turn
with makeAveraged, and return the number with the highest average. On a
tie, keep the smaller number. With fair six-sided dice, the answer is 6: more
dice score more, until the chance of rolling a 1 catches up.
Phase 4: Strategies
Problem 9: boarStrategy and susStrategy
boarStrategy rolls 0 when Boar Brawl would score at least threshold
points, and numRolls dice otherwise. susStrategy is the same, but
measures the whole gain from rolling 0, including any Sus Fuss bonus. The
easiest way to compute that gain is to call susUpdate with zero dice; since
it never rolls, any dice will do.
Problem 10: finalStrategy
Write your own strategy. The test plays 1,000 games against alwaysRoll(6),
half as each player, with Sus Fuss, and checks that yours wins at least 55%
of them. boarStrategy and susStrategy already win about two thirds, so
start from one of them and improve it. Some ideas:
- Roll zero when it would reach 100 and win outright.
- Take less risk when you are far ahead, and more when you are far behind.
- Avoid landing on a score that gives your opponent a large Boar Brawl.
Test ideas with winRate(_:games:), which is in the test section, by
calling it temporarily from your code. Then play against your strategy with
swift hog.swift play.