Dice Foundry Solutions and Answer Key

Appendix — Final Project Solution Source

These are the files that Chapter 14 changes from Checkpoint 13 (D100, maximum/minimum indicator, history filter). Every other file in the project is identical to Checkpoint 13. The full project is in 03-Solutions-and-Answer-Key/Final-Project-Solution.

DiceFoundry/ContentView.swift

//
//  ContentView.swift
//  DiceFoundry
//

import SwiftUI

struct ContentView: View {
    @State private var viewModel = RollViewModel()

    @AppStorage("hapticsEnabled") private var hapticsEnabled = true

    var body: some View {
        ScrollView {
            VStack(spacing: Theme.spacing) {
                header

                DiePicker(selection: $viewModel.selectedDie)
                    .cardStyle()

                RollOptionsView(quantity: $viewModel.quantity, modifier: $viewModel.modifier)
                    .cardStyle()

                ResultView(roll: viewModel.latestRoll, rollCount: viewModel.rollCount)
                    .cardStyle()

                historySection
                    .cardStyle()

                settingsSection
                    .cardStyle()
            }
            .padding()
        }
        .background(Theme.backgroundGradient.ignoresSafeArea())
        .tint(Theme.brass)
        .safeAreaInset(edge: .bottom) {
            rollButton
                .padding(.horizontal)
                .padding(.vertical, 8)
                .background(.ultraThinMaterial)
        }
        .sensoryFeedback(.impact(weight: .medium), trigger: viewModel.rollCount) { _, _ in
            hapticsEnabled
        }
        .onAppear {
            viewModel.loadHistory()
        }
    }

    private var header: some View {
        VStack(spacing: 4) {
            HStack {
                Image(systemName: "dice.fill")
                    .font(.title)
                    .foregroundStyle(Theme.brass)
                    .accessibilityHidden(true)
                Text("Dice Foundry")
                    .font(.largeTitle)
                    .fontWeight(.bold)
                    .fontDesign(.serif)
            }
            Text("The Black Well Foundry")
                .font(.caption)
                .textCase(.uppercase)
                .tracking(2)
                .foregroundStyle(.secondary)
        }
        .accessibilityElement(children: .combine)
        .accessibilityAddTraits(.isHeader)
    }

    private var rollButton: some View {
        Button {
            viewModel.roll()
        } label: {
            Label("Roll Dice", systemImage: "dice.fill")
                .font(.title2)
                .fontWeight(.bold)
                .frame(maxWidth: .infinity)
                .padding(.vertical, 16)
                .foregroundStyle(Theme.onBrass)
                .background(Theme.brassGradient, in: RoundedRectangle(cornerRadius: Theme.cornerRadius))
        }
        .buttonStyle(.plain)
        .accessibilityHint("Rolls the selected dice and adds the result to your history.")
    }

    private var historySection: some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack {
                Text("History")
                    .font(.title2)
                    .fontWeight(.bold)
                    .accessibilityAddTraits(.isHeader)
                Spacer()
                Picker("Filter", selection: $viewModel.historyFilter) {
                    Text("All dice").tag(DieType?.none)
                    ForEach(DieType.allCases) { dieType in
                        Text(dieType.name).tag(DieType?.some(dieType))
                    }
                }
                .pickerStyle(.menu)
                .accessibilityLabel("Filter history by die")
                Button("Clear") {
                    viewModel.clearHistory()
                }
                .disabled(viewModel.history.isEmpty)
                .accessibilityLabel("Clear history")
            }

            if viewModel.history.isEmpty {
                Text("No rolls yet")
                    .foregroundStyle(.secondary)
            } else if viewModel.filteredHistory.isEmpty {
                Text("No rolls match this filter")
                    .foregroundStyle(.secondary)
            }

            ForEach(viewModel.filteredHistory) { roll in
                HistoryRow(roll: roll)
                Divider()
            }
        }
    }

    private var settingsSection: some View {
        Toggle(isOn: $hapticsEnabled) {
            Label("Haptic feedback", systemImage: "iphone.radiowaves.left.and.right")
        }
    }
}

#Preview("Light") {
    ContentView()
}

#Preview("Dark") {
    ContentView()
        .preferredColorScheme(.dark)
}

DiceFoundry/Models/DieType.swift

//
//  DieType.swift
//  DiceFoundry
//

import Foundation

enum DieType: Int, CaseIterable, Identifiable, Codable {
    case d4 = 4
    case d6 = 6
    case d8 = 8
    case d10 = 10
    case d12 = 12
    case d20 = 20
    case d100 = 100

    var id: Int {
        rawValue
    }

    var sides: Int {
        rawValue
    }

    var name: String {
        "D\(rawValue)"
    }

    var accessibilityName: String {
        "\(sides)-sided die"
    }

    var symbolName: String {
        switch self {
        case .d4:
            return "triangle"
        case .d6:
            return "square"
        case .d8:
            return "diamond"
        case .d10:
            return "pentagon"
        case .d12:
            return "hexagon"
        case .d20:
            return "octagon"
        case .d100:
            return "percent"
        }
    }
}

DiceFoundry/Models/RollResult.swift

//
//  RollResult.swift
//  DiceFoundry
//

import Foundation

struct RollResult: Identifiable, Codable {
    let id: UUID
    let dieType: DieType
    let values: [Int]
    let modifier: Int
    let date: Date

    init(dieType: DieType, values: [Int], modifier: Int, id: UUID = UUID(), date: Date = Date()) {
        self.id = id
        self.dieType = dieType
        self.values = values
        self.modifier = modifier
        self.date = date
    }

    var subtotal: Int {
        values.reduce(0, +)
    }

    var total: Int {
        subtotal + modifier
    }

    var notation: String {
        let dice = "\(values.count)\(dieType.name)"
        if modifier > 0 {
            return "\(dice) + \(modifier)"
        } else if modifier < 0 {
            return "\(dice) - \(abs(modifier))"
        } else {
            return dice
        }
    }

    var valuesDescription: String {
        values.map { String($0) }.joined(separator: ", ")
    }

    func isMaximum(_ value: Int) -> Bool {
        value == dieType.sides
    }

    func isMinimum(_ value: Int) -> Bool {
        value == 1
    }

    static func formatModifier(_ value: Int) -> String {
        switch value {
        case 0:
            return "0"
        case 1...:
            return "+\(value)"
        default:
            return "\(value)"
        }
    }
}

DiceFoundry/ViewModels/RollViewModel.swift

//
//  RollViewModel.swift
//  DiceFoundry
//

import Foundation
import Observation

@Observable
final class RollViewModel {
    // Choices the user is making
    var selectedDie: DieType = .d6
    var quantity: Int = 1
    var modifier: Int = 0

    // Results. Views can read these but only this class can change them.
    private(set) var latestRoll: RollResult?
    private(set) var history: [RollResult] = []
    private(set) var rollCount: Int = 0

    // nil means "show every die type"
    var historyFilter: DieType?

    var filteredHistory: [RollResult] {
        if let historyFilter {
            return history.filter { $0.dieType == historyFilter }
        } else {
            return history
        }
    }

    // Dependencies
    private let roller: DiceRoller
    private let store: HistoryStore

    init(roller: DiceRoller = DiceRoller(), store: HistoryStore = HistoryStore()) {
        self.roller = roller
        self.store = store
    }

    func roll() {
        let roll = roller.roll(selectedDie, quantity: quantity, modifier: modifier)
        latestRoll = roll
        rollCount += 1
        history.insert(roll, at: 0)
        if history.count > HistoryStore.maximumCount {
            history.removeLast()
        }
        saveHistory()
    }

    func clearHistory() {
        history.removeAll()
        saveHistory()
    }

    func loadHistory() {
        do {
            history = try store.load()
            latestRoll = history.first
        } catch {
            print("Could not load roll history: \(error)")
        }
    }

    private func saveHistory() {
        do {
            try store.save(history)
        } catch {
            print("Could not save roll history: \(error)")
        }
    }
}

DiceFoundry/Views/ResultView.swift

//
//  ResultView.swift
//  DiceFoundry
//

import SwiftUI

struct ResultView: View {
    let roll: RollResult?
    let rollCount: Int

    @Environment(\.accessibilityReduceMotion) private var reduceMotion
    @ScaledMetric(relativeTo: .largeTitle) private var totalSize: CGFloat = 56
    @ScaledMetric(relativeTo: .largeTitle) private var circleSize: CGFloat = 140
    @State private var rotation: Double = 0

    private let resultColumns = [
        GridItem(.adaptive(minimum: 44))
    ]

    var body: some View {
        VStack(spacing: 16) {
            if let roll {
                Text(roll.notation)
                    .font(.title2)
                    .fontWeight(.semibold)
                    .foregroundStyle(Theme.brass)

                ZStack {
                    Circle()
                        .fill(Theme.backgroundSecondary)
                    Circle()
                        .stroke(Theme.brassGradient, lineWidth: 4)
                    Text("\(roll.total)")
                        .font(.system(size: totalSize, weight: .bold, design: .rounded))
                        .contentTransition(.numericText(value: Double(roll.total)))
                        .animation(reduceMotion ? nil : .snappy, value: roll.total)
                }
                .frame(width: circleSize, height: circleSize)
                .rotationEffect(.degrees(rotation))

                LazyVGrid(columns: resultColumns, spacing: 8) {
                    ForEach(roll.values.indices, id: \.self) { index in
                        let value = roll.values[index]
                        Text("\(value)")
                            .font(.title3)
                            .fontWeight(.semibold)
                            .frame(minWidth: 44, minHeight: 44)
                            .foregroundStyle(roll.isMaximum(value) ? Theme.onBrass : Color.primary)
                            .background(chipColor(for: value, in: roll), in: RoundedRectangle(cornerRadius: 8))
                            .overlay(
                                RoundedRectangle(cornerRadius: 8)
                                    .stroke(Theme.brass.opacity(0.5), lineWidth: 1)
                            )
                            .overlay(alignment: .topTrailing) {
                                if let symbol = chipSymbol(for: value, in: roll) {
                                    Image(systemName: symbol)
                                        .font(.caption2.weight(.bold))
                                        .foregroundStyle(roll.isMaximum(value) ? Theme.onBrass : Color.primary)
                                        .padding(3)
                                }
                            }
                    }
                }

                if roll.modifier != 0 {
                    Text("Dice \(roll.subtotal), modifier \(RollResult.formatModifier(roll.modifier))")
                        .foregroundStyle(.secondary)
                }
            } else {
                VStack(spacing: 8) {
                    Image(systemName: "dice")
                        .font(.largeTitle)
                        .foregroundStyle(Theme.brass)
                    Text("Tap Roll Dice to begin")
                        .foregroundStyle(.secondary)
                }
                .frame(minHeight: circleSize)
            }
        }
        .frame(maxWidth: .infinity)
        .accessibilityElement(children: .ignore)
        .accessibilityLabel(accessibilityDescription)
        .onChange(of: rollCount) {
            spin()
        }
    }

    private var accessibilityDescription: String {
        if let roll {
            var description = "Rolled \(roll.notation). Total \(roll.total). Dice: \(roll.valuesDescription)."
            let maximumCount = roll.values.filter { roll.isMaximum($0) }.count
            let minimumCount = roll.values.filter { roll.isMinimum($0) }.count
            if maximumCount > 0 {
                description += " \(maximumCount) at maximum."
            }
            if minimumCount > 0 {
                description += " \(minimumCount) at minimum."
            }
            return description
        } else {
            return "No roll yet. Tap Roll Dice to begin."
        }
    }

    private func chipColor(for value: Int, in roll: RollResult) -> Color {
        if roll.isMaximum(value) {
            return Theme.gold
        } else if roll.isMinimum(value) {
            return Color.red.opacity(0.25)
        } else {
            return Theme.backgroundSecondary
        }
    }

    // A shape cue, so the marking does not depend on color alone.
    private func chipSymbol(for value: Int, in roll: RollResult) -> String? {
        if roll.isMaximum(value) {
            return "arrow.up"
        } else if roll.isMinimum(value) {
            return "arrow.down"
        } else {
            return nil
        }
    }

    private func spin() {
        if reduceMotion {
            return
        }
        withAnimation(.spring(duration: 0.6, bounce: 0.3)) {
            rotation += 360
        }
    }
}

#Preview("With a roll") {
    ResultView(roll: RollResult(dieType: .d6, values: [4, 2, 6], modifier: 2), rollCount: 1)
        .padding()
}

#Preview("Empty") {
    ResultView(roll: nil, rollCount: 0)
        .padding()
}

DiceFoundryTests/FinalProjectTests.swift

//
//  FinalProjectTests.swift
//  DiceFoundryTests
//

import Testing
import Foundation
@testable import DiceFoundry

@MainActor
struct FinalProjectTests {

    @Test func percentileDieHasOneHundredSides() {
        #expect(DieType.d100.sides == 100)
        #expect(DieType.d100.name == "D100")
        #expect(DieType.allCases.count == 7)
    }

    @Test func percentileRollsStayInRange() {
        let roller = DiceRoller()
        for _ in 1...200 {
            let roll = roller.roll(.d100, quantity: 10, modifier: 0)
            #expect(roll.values.allSatisfy { (1...100).contains($0) })
        }
    }

    @Test func maximumAndMinimumDetection() {
        let roll = RollResult(dieType: .d20, values: [20, 1, 12], modifier: 0)
        #expect(roll.isMaximum(20))
        #expect(!roll.isMaximum(12))
        #expect(roll.isMinimum(1))
        #expect(!roll.isMinimum(12))
    }

    @Test func historyFilterShowsOnlyMatchingDice() {
        let viewModel = RollViewModel(
            roller: DiceRoller(randomValue: { _ in 2 }),
            store: HistoryStore(fileURL: URL.temporaryDirectory.appending(path: "filter-\(UUID().uuidString).json"))
        )
        viewModel.selectedDie = .d6
        viewModel.roll()
        viewModel.selectedDie = .d20
        viewModel.roll()
        viewModel.roll()

        viewModel.historyFilter = .d20
        #expect(viewModel.filteredHistory.count == 2)

        viewModel.historyFilter = .d4
        #expect(viewModel.filteredHistory.isEmpty)

        viewModel.historyFilter = nil
        #expect(viewModel.filteredHistory.count == 3)
    }

    @Test func oldHistoryStillDecodesAfterAddingD100() throws {
        // A history file written before D100 existed must still load.
        // This JSON is in the format JSONEncoder wrote for RollResult in
        // Checkpoints 12 and 13: dieType is the Int raw value, and date is
        // seconds since the reference date (2001-01-01).
        let oldJSON = """
        [
          {
            "id": "11111111-1111-1111-1111-111111111111",
            "dieType": 6,
            "values": [4, 2, 6],
            "modifier": 2,
            "date": 800000000
          },
          {
            "id": "22222222-2222-2222-2222-222222222222",
            "dieType": 20,
            "values": [20],
            "modifier": -1,
            "date": 800000100.5
          }
        ]
        """
        let url = URL.temporaryDirectory.appending(path: "old-\(UUID().uuidString).json")
        defer { try? FileManager.default.removeItem(at: url) }
        try Data(oldJSON.utf8).write(to: url)

        let history = try HistoryStore(fileURL: url).load()

        #expect(history.count == 2)
        #expect(history[0].id == UUID(uuidString: "11111111-1111-1111-1111-111111111111"))
        #expect(history[0].dieType == .d6)
        #expect(history[0].values == [4, 2, 6])
        #expect(history[0].modifier == 2)
        #expect(history[0].total == 14)
        #expect(history[0].date == Date(timeIntervalSinceReferenceDate: 800000000))
        #expect(history[1].dieType == .d20)
        #expect(history[1].values == [20])
        #expect(history[1].modifier == -1)
        #expect(history[1].total == 19)
    }
}