// Hog, in Swift. A project for cs.dorian.page's Swift tutorial, after the // dice game in CS61A's first project (UC Berkeley). // // Run the tests: swift hog.swift test // Run one problem: swift hog.swift test 3 // Play against your AI: swift hog.swift play // // Write your code between each `BEGIN PROBLEM` and `END PROBLEM` line. // Everything else is provided; read it, but do not change it. // MARK: - Provided: dice /// A die is a function that returns the next roll each time it is called. typealias Dice = () -> Int /// A strategy takes (your score, opponent's score) and returns how many /// dice to roll this turn, from 0 to 10. typealias Strategy = (Int, Int) -> Int /// An update rule takes (dice to roll, your score, opponent's score, dice) /// and returns your new score after the turn. typealias Update = (Int, Int, Int, Dice) -> Int let goal = 100 /// Fair dice from a seeded generator, so a game can be replayed exactly. /// (SplitMix64: a small, well-known pseudo-random number generator.) func makeFairDice(sides: Int, seed: UInt64) -> Dice { var state = seed return { state &+= 0x9E37_79B9_7F4A_7C15 var z = state z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9 z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB z ^= z >> 31 return Int(z % UInt64(sides)) + 1 } } /// Dice that return the given outcomes in order, repeating forever. func makeTestDice(_ outcomes: Int...) -> Dice { precondition(!outcomes.isEmpty, "test dice need at least one outcome") var index = 0 return { defer { index = (index + 1) % outcomes.count } return outcomes[index] } } // MARK: - Phase 1: Simulating a turn // BEGIN PROBLEM 1 /// Roll `dice` exactly `numRolls` times. Return the sum of the outcomes, /// unless any outcome is 1, in which case return 1 (Sow Sad). func rollDice(_ numRolls: Int, dice: Dice) -> Int { precondition(numRolls > 0, "must roll at least once") return 0 // Replace this line. } // END PROBLEM 1 // BEGIN PROBLEM 2 /// Points for rolling zero dice (Boar Brawl): three times the absolute /// difference between the tens digit of the opponent's score and the ones /// digit of the player's score, or 1 if that is smaller. func boarBrawl(player: Int, opponent: Int) -> Int { return 0 // Replace this line. } // END PROBLEM 2 // BEGIN PROBLEM 3 /// Points scored this turn by rolling `numRolls` dice (0 to 10). func takeTurn(_ numRolls: Int, player: Int, opponent: Int, dice: Dice) -> Int { precondition(numRolls >= 0 && numRolls <= 10, "roll between 0 and 10 dice") return 0 // Replace this line. } // END PROBLEM 3 /// The update rule without Sus Fuss: add the turn's points to the score. func simpleUpdate(_ numRolls: Int, _ player: Int, _ opponent: Int, _ dice: Dice) -> Int { player + takeTurn(numRolls, player: player, opponent: opponent, dice: dice) } // BEGIN PROBLEM 4 /// The number of positive factors of n. func numFactors(_ n: Int) -> Int { return 0 // Replace this line. } func isPrime(_ n: Int) -> Bool { return false // Replace this line. } /// If `score` has exactly 3 or 4 factors, return the next prime above it; /// otherwise return `score` unchanged (Sus Fuss). func susPoints(_ score: Int) -> Int { return score // Replace this line. } /// The update rule with Sus Fuss applied after the turn. func susUpdate(_ numRolls: Int, _ player: Int, _ opponent: Int, _ dice: Dice) -> Int { return simpleUpdate(numRolls, player, opponent, dice) // Replace this line. } // END PROBLEM 4 // MARK: - Phase 2: Playing a game // BEGIN PROBLEM 5 /// Play until one player reaches `goal`, with player 0 going first. /// Return the final scores (score0, score1). func play(_ strategy0: Strategy, _ strategy1: Strategy, update: Update, score0: Int = 0, score1: Int = 0, dice: @escaping Dice, goal: Int = goal) -> (Int, Int) { var score0 = score0 var score1 = score1 var whoseTurn = 0 // Your code here. return (score0, score1) } // END PROBLEM 5 // BEGIN PROBLEM 6 /// A strategy that always rolls `n` dice. func alwaysRoll(_ n: Int) -> Strategy { return { _, _ in 0 } // Replace this line. } /// Whether `strategy` returns the same number of dice for every pair of /// scores below `goal`. func isAlwaysRoll(_ strategy: Strategy, goal: Int = goal) -> Bool { return false // Replace this line. } // END PROBLEM 6 // MARK: - Phase 3: Experiments // BEGIN PROBLEM 7 /// A function that calls `f` `samples` times and returns the average result. func makeAveraged(_ f: @escaping () -> Int, samples: Int) -> () -> Double { return { 0 } // Replace this line. } // END PROBLEM 7 // BEGIN PROBLEM 8 /// The number of dice (1 to 10) with the highest average turn score over /// `samples` turns each. Ties go to the smaller number. func maxScoringNumRolls(dice: @escaping Dice, samples: Int = 1000) -> Int { return 1 // Replace this line. } // END PROBLEM 8 // MARK: - Phase 4: Strategies // BEGIN PROBLEM 9 /// Roll 0 when Boar Brawl would score at least `threshold`; otherwise roll /// `numRolls`. func boarStrategy(threshold: Int = 11, numRolls: Int = 6) -> Strategy { return { _, _ in numRolls } // Replace this line. } /// Like boarStrategy, but counts the whole gain from rolling 0, including /// any Sus Fuss bonus. func susStrategy(threshold: Int = 11, numRolls: Int = 6) -> Strategy { return { _, _ in numRolls } // Replace this line. } // END PROBLEM 9 // BEGIN PROBLEM 10 /// Your own strategy. The tests check that it wins at least 55% of games /// against alwaysRoll(6) with Sus Fuss. func finalStrategy(_ score: Int, _ opponent: Int) -> Int { return 6 // Replace this line. } // END PROBLEM 10 // MARK: - Tests (do not edit below this line) var onlyProblem: Int? = nil var passed = 0 var failed = 0 var failedProblems = Set() func check(_ problem: Int, _ description: String, _ actual: @autoclosure () -> T, _ expected: T) { if let only = onlyProblem, only != problem { return } let value = actual() if value == expected { passed += 1 } else { failed += 1 failedProblems.insert(problem) print("✗ Problem \(problem): \(description)") print(" expected \(expected), got \(value)") } } func winRate(_ strategy: @escaping Strategy, games: Int) -> Double { var wins = 0 for game in 0.. theirs { wins += 1 } } else { let (theirs, mine) = play(alwaysRoll(6), strategy, update: susUpdate, dice: dice) if mine > theirs { wins += 1 } } } return Double(wins) / Double(games) } func runTests() { // Problem 1: rollDice check(1, "sum of two rolls", rollDice(2, dice: makeTestDice(4, 6, 1)), 10) check(1, "a 1 means the turn scores 1", rollDice(3, dice: makeTestDice(4, 6, 1)), 1) check(1, "four rolls", rollDice(4, dice: makeTestDice(2, 2, 3)), 9) check(1, "one roll", rollDice(1, dice: makeTestDice(6)), 6) check(1, "keeps rolling after a 1", { let dice = makeTestDice(4, 1, 2, 6) return [rollDice(2, dice: dice), rollDice(3, dice: dice)] }(), [1, 12]) // Problem 2: boarBrawl check(2, "boarBrawl(player: 21, opponent: 46)", boarBrawl(player: 21, opponent: 46), 9) check(2, "equal digits score 1", boarBrawl(player: 45, opponent: 52), 1) check(2, "one-digit opponent", boarBrawl(player: 2, opponent: 5), 6) check(2, "boarBrawl(player: 0, opponent: 99)", boarBrawl(player: 0, opponent: 99), 27) check(2, "opponent at 100 has tens digit 0", boarBrawl(player: 7, opponent: 100), 21) // Problem 3: takeTurn check(3, "rolling two dice", takeTurn(2, player: 0, opponent: 0, dice: makeTestDice(4, 6)), 10) check(3, "rolling zero uses Boar Brawl", takeTurn(0, player: 21, opponent: 46, dice: makeTestDice(6)), 9) check(3, "Sow Sad", takeTurn(3, player: 0, opponent: 0, dice: makeTestDice(1, 6, 6)), 1) check(3, "rolling zero does not roll", { let dice = makeTestDice(5, 2) _ = takeTurn(0, player: 0, opponent: 0, dice: dice) return takeTurn(1, player: 0, opponent: 0, dice: dice) }(), 5) // Problem 4: Sus Fuss check(4, "numFactors of 1, 9, 12, 97, 6", [1, 9, 12, 97, 6].map(numFactors), [1, 3, 6, 2, 4]) check(4, "isPrime", [2, 9, 13, 1].map(isPrime), [true, false, true, false]) check(4, "sus numbers rise to the next prime", [9, 6, 21, 4, 49].map(susPoints), [11, 7, 23, 5, 53]) check(4, "other numbers stay", [12, 97, 1, 30].map(susPoints), [12, 97, 1, 30]) check(4, "susUpdate after rolling", susUpdate(2, 5, 0, makeTestDice(2, 2)), 11) check(4, "susUpdate after rolling zero", susUpdate(0, 21, 46, makeTestDice(6)), 30) // Problem 5: play check(5, "always roll 5 against always roll 5", { let (a, b) = play(alwaysRoll(5), alwaysRoll(5), update: simpleUpdate, dice: makeTestDice(4)) return [a, b] }(), [100, 80]) check(5, "a game with Sus Fuss and Boar Brawl", { let (a, b) = play(alwaysRoll(0), alwaysRoll(1), update: susUpdate, dice: makeTestDice(3)) return [a, b] }(), [104, 43]) check(5, "starting scores and player 1 winning", { let (a, b) = play(alwaysRoll(2), alwaysRoll(2), update: simpleUpdate, score0: 90, score1: 95, dice: makeTestDice(2, 3)) return [a, b] }(), [95, 100]) check(5, "a finished game makes no moves", { let (a, b) = play(alwaysRoll(1), alwaysRoll(1), update: simpleUpdate, score0: 100, score1: 0, dice: makeTestDice(6)) return [a, b] }(), [100, 0]) check(5, "each strategy sees its own score first", { var seen: [[Int]] = [] let recorder: Strategy = { mine, theirs in seen.append([mine, theirs]); return 1 } _ = play(alwaysRoll(1), recorder, update: simpleUpdate, dice: makeTestDice(6), goal: 13) return seen }(), [[0, 6], [6, 12]]) // Problem 6: alwaysRoll and isAlwaysRoll check(6, "alwaysRoll(7)", alwaysRoll(7)(10, 20), 7) check(6, "alwaysRoll is always roll", isAlwaysRoll(alwaysRoll(4)), true) check(6, "depends on own score", isAlwaysRoll({ mine, _ in mine > 50 ? 2 : 3 }), false) check(6, "depends on the opponent near the goal", isAlwaysRoll({ _, theirs in theirs == 99 ? 5 : 4 }), false) // Problem 7: makeAveraged check(7, "average of a constant", makeAveraged({ 3 }, samples: 5)(), 3.0) check(7, "average of 1, 2, 3", makeAveraged(makeTestDice(1, 2, 3), samples: 3)(), 2.0) check(7, "uses exactly `samples` calls", makeAveraged(makeTestDice(1, 2, 3, 4), samples: 2)(), 1.5) // Problem 8: maxScoringNumRolls check(8, "a die that always rolls 3", maxScoringNumRolls(dice: makeTestDice(3), samples: 10), 10) check(8, "a die that alternates 1 and 6", maxScoringNumRolls(dice: makeTestDice(1, 6), samples: 1000), 1) check(8, "fair dice", maxScoringNumRolls(dice: makeFairDice(sides: 6, seed: 42), samples: 1000), 6) // Problem 9: strategies check(9, "boarStrategy rolls 0 at the threshold", boarStrategy(threshold: 9, numRolls: 3)(21, 46), 0) check(9, "boarStrategy rolls below the threshold", boarStrategy(threshold: 10, numRolls: 3)(21, 46), 3) check(9, "boarStrategy ignores Sus Fuss", boarStrategy(threshold: 8)(2, 0), 6) check(9, "susStrategy counts the Sus Fuss bonus", susStrategy(threshold: 8)(2, 0), 0) check(9, "susStrategy below the threshold", susStrategy(threshold: 10, numRolls: 4)(21, 46), 4) // Problem 10: finalStrategy check(10, "always returns 0 to 10 dice", { for mine in 0..= 0.55, true) let total = passed + failed if failed == 0 && total > 0 { print("\(total) of \(total) checks passed.") print(onlyProblem.map { "Problem \($0) passed." } ?? "All tests passed.") } else { print("\(passed) of \(total) checks passed. Problems to revisit: \(failedProblems.sorted()).") } } /// Play against finalStrategy, rolling your own dice at the keyboard. func playInteractive() { let dice = makeFairDice(sides: 6, seed: UInt64.random(in: 0...UInt64.max)) var you = 0 var computer = 0 print("You are player 0. First to \(goal) wins.") while you < goal && computer < goal { print("Score: you \(you), computer \(computer). How many dice (0-10)? ", terminator: "") guard let line = readLine() else { return } guard let rolls = Int(line), (0...10).contains(rolls) else { print("Please enter a number from 0 to 10.") continue } you = susUpdate(rolls, you, computer, dice) if you >= goal { break } let choice = finalStrategy(computer, you) computer = susUpdate(choice, computer, you, dice) print("The computer rolled \(choice) and now has \(computer).") } print(you >= goal ? "You win, \(you) to \(computer)!" : "The computer wins, \(computer) to \(you).") } let arguments = Array(CommandLine.arguments.dropFirst()) switch arguments.first { case "test": onlyProblem = arguments.dropFirst().first.flatMap { Int($0) } runTests() case "play": playInteractive() default: print("Usage: swift hog.swift test [problem] | swift hog.swift play") }