Dice Foundry Student Workbook

Appendix B — Milestone Source Listings

These listings are generated directly from the compiled reference checkpoints, so they always match the verified code. Use them to compare against your own project when something does not work. Type your own code first; come here to check it, not to copy it.

End of Chapter 4 — A Working D6 Roller

Reference folder: Reference-Checkpoints/Checkpoint-04-State-and-Random

DiceFoundry/ContentView.swift

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

import SwiftUI

struct ContentView: View {
    @State private var result: Int = 0

    var body: some View {
        VStack(spacing: 24) {
            HStack {
                Image(systemName: "dice.fill")
                    .font(.title)
                    .foregroundStyle(.orange)
                Text("Dice Foundry")
                    .font(.largeTitle)
                    .fontWeight(.bold)
            }

            Spacer()

            ZStack {
                Circle()
                    .fill(Color.orange.opacity(0.2))
                    .frame(width: 160, height: 160)
                Text("\(result)")
                    .font(.system(size: 72, weight: .bold))
            }

            Text("Rolling a D6")
                .foregroundStyle(.secondary)

            Spacer()

            Button("Roll Dice") {
                result = rollDie(sides: 6)
            }
            .font(.title2)
            .buttonStyle(.borderedProminent)
            .controlSize(.large)
            .tint(.orange)
        }
        .padding()
    }

    func rollDie(sides: Int) -> Int {
        let roll = Int.random(in: 1...sides)
        return roll
    }
}

#Preview {
    ContentView()
}

DiceFoundry/DiceFoundryApp.swift

//
//  DiceFoundryApp.swift
//  DiceFoundry
//

import SwiftUI

@main
struct DiceFoundryApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

End of Chapter 7 — Modifiers and Dice Notation

Reference folder: Reference-Checkpoints/Checkpoint-07-Modifiers-and-Notation

DiceFoundry/ContentView.swift

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

import SwiftUI

struct ContentView: View {
    @State private var selectedDie: DieType = .d6
    @State private var quantity: Int = 1
    @State private var modifier: Int = 0
    @State private var results: [Int] = []
    @State private var rolledModifier: Int = 0
    @State private var rolledNotation: String = ""

    let columns = [
        GridItem(.flexible()),
        GridItem(.flexible()),
        GridItem(.flexible())
    ]

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

    var subtotal: Int {
        sum(of: results)
    }

    var total: Int {
        subtotal + rolledModifier
    }

    var body: some View {
        VStack(spacing: 16) {
            HStack {
                Image(systemName: "dice.fill")
                    .font(.title)
                    .foregroundStyle(.orange)
                Text("Dice Foundry")
                    .font(.largeTitle)
                    .fontWeight(.bold)
            }

            LazyVGrid(columns: columns, spacing: 12) {
                ForEach(DieType.allCases) { dieType in
                    Button {
                        selectedDie = dieType
                    } label: {
                        Text(dieType.name)
                            .font(.headline)
                            .frame(maxWidth: .infinity)
                    }
                    .buttonStyle(.bordered)
                    .tint(dieType == selectedDie ? .orange : .gray)
                }
            }

            Stepper("Number of dice: \(quantity)", value: $quantity, in: 1...10)
            Stepper("Modifier: \(formattedModifier(modifier))", value: $modifier, in: -20...20)

            Spacer()

            if results.isEmpty {
                Text("Tap Roll Dice to begin")
                    .foregroundStyle(.secondary)
            } else {
                Text(rolledNotation)
                    .font(.title2)
                    .fontWeight(.semibold)

                ZStack {
                    Circle()
                        .fill(Color.orange.opacity(0.2))
                        .frame(width: 140, height: 140)
                    Text("\(total)")
                        .font(.system(size: 64, weight: .bold))
                }

                LazyVGrid(columns: resultColumns, spacing: 8) {
                    ForEach(results.indices, id: \.self) { index in
                        Text("\(results[index])")
                            .font(.title3)
                            .fontWeight(.semibold)
                            .frame(width: 44, height: 44)
                            .background(Color.orange.opacity(0.2))
                            .clipShape(RoundedRectangle(cornerRadius: 8))
                    }
                }

                if rolledModifier != 0 {
                    Text("Dice \(subtotal), modifier \(formattedModifier(rolledModifier))")
                        .foregroundStyle(.secondary)
                }
            }

            Spacer()

            Button("Roll Dice") {
                performRoll()
            }
            .font(.title2)
            .buttonStyle(.borderedProminent)
            .controlSize(.large)
            .tint(.orange)
        }
        .padding()
    }

    func rollDie(sides: Int) -> Int {
        let roll = Int.random(in: 1...sides)
        return roll
    }

    func rollDice(count: Int, sides: Int) -> [Int] {
        var rolls: [Int] = []
        for _ in 1...count {
            rolls.append(rollDie(sides: sides))
        }
        return rolls
    }

    func sum(of values: [Int]) -> Int {
        values.reduce(0, +)
    }

    func isValidQuantity(_ value: Int) -> Bool {
        value >= 1 && value <= 10
    }

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

    func notation(quantity: Int, dieType: DieType, modifier: Int) -> String {
        let dice = "\(quantity)\(dieType.name)"
        if modifier > 0 {
            return "\(dice) + \(modifier)"
        } else if modifier < 0 {
            return "\(dice) - \(abs(modifier))"
        } else {
            return dice
        }
    }

    func performRoll() {
        if isValidQuantity(quantity) {
            results = rollDice(count: quantity, sides: selectedDie.sides)
            rolledModifier = modifier
            rolledNotation = notation(quantity: quantity, dieType: selectedDie, modifier: modifier)
        } else {
            print("Invalid quantity: \(quantity)")
        }
    }
}

#Preview {
    ContentView()
}

DiceFoundry/DiceFoundryApp.swift

//
//  DiceFoundryApp.swift
//  DiceFoundry
//

import SwiftUI

@main
struct DiceFoundryApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

DiceFoundry/DieType.swift

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

import Foundation

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

    var id: Int {
        rawValue
    }

    var sides: Int {
        rawValue
    }

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

End of Chapter 9 — Persistent Roll History

Reference folder: Reference-Checkpoints/Checkpoint-09-Persistence

DiceFoundry/ContentView.swift

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

import SwiftUI

struct ContentView: View {
    @State private var selectedDie: DieType = .d6
    @State private var quantity: Int = 1
    @State private var modifier: Int = 0
    @State private var latestRoll: RollResult?
    @State private var history: [RollResult] = []

    let store = HistoryStore()

    let columns = [
        GridItem(.flexible()),
        GridItem(.flexible()),
        GridItem(.flexible())
    ]

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

    var body: some View {
        ScrollView {
            VStack(spacing: 20) {
                HStack {
                    Image(systemName: "dice.fill")
                        .font(.title)
                        .foregroundStyle(.orange)
                    Text("Dice Foundry")
                        .font(.largeTitle)
                        .fontWeight(.bold)
                }

                LazyVGrid(columns: columns, spacing: 12) {
                    ForEach(DieType.allCases) { dieType in
                        Button {
                            selectedDie = dieType
                        } label: {
                            Text(dieType.name)
                                .font(.headline)
                                .frame(maxWidth: .infinity)
                        }
                        .buttonStyle(.bordered)
                        .tint(dieType == selectedDie ? .orange : .gray)
                    }
                }

                Stepper("Number of dice: \(quantity)", value: $quantity, in: 1...10)
                Stepper("Modifier: \(formattedModifier(modifier))", value: $modifier, in: -20...20)

                if let roll = latestRoll {
                    Text(roll.notation)
                        .font(.title2)
                        .fontWeight(.semibold)

                    ZStack {
                        Circle()
                            .fill(Color.orange.opacity(0.2))
                            .frame(width: 140, height: 140)
                        Text("\(roll.total)")
                            .font(.system(size: 64, weight: .bold))
                    }

                    LazyVGrid(columns: resultColumns, spacing: 8) {
                        ForEach(roll.values.indices, id: \.self) { index in
                            Text("\(roll.values[index])")
                                .font(.title3)
                                .fontWeight(.semibold)
                                .frame(width: 44, height: 44)
                                .background(Color.orange.opacity(0.2))
                                .clipShape(RoundedRectangle(cornerRadius: 8))
                        }
                    }

                    if roll.modifier != 0 {
                        Text("Dice \(roll.subtotal), modifier \(formattedModifier(roll.modifier))")
                            .foregroundStyle(.secondary)
                    }
                } else {
                    Text("Tap Roll Dice to begin")
                        .foregroundStyle(.secondary)
                        .frame(height: 140)
                }

                Button("Roll Dice") {
                    performRoll()
                }
                .font(.title2)
                .buttonStyle(.borderedProminent)
                .controlSize(.large)
                .tint(.orange)

                VStack(alignment: .leading, spacing: 12) {
                    HStack {
                        Text("History")
                            .font(.title2)
                            .fontWeight(.bold)
                        Spacer()
                        Button("Clear") {
                            clearHistory()
                        }
                        .disabled(history.isEmpty)
                    }

                    if history.isEmpty {
                        Text("No rolls yet")
                            .foregroundStyle(.secondary)
                    }

                    ForEach(history) { roll in
                        HStack {
                            VStack(alignment: .leading) {
                                Text(roll.notation)
                                    .font(.headline)
                                Text(roll.valuesDescription)
                                    .font(.caption)
                                    .foregroundStyle(.secondary)
                            }
                            Spacer()
                            VStack(alignment: .trailing) {
                                Text("\(roll.total)")
                                    .font(.title2)
                                    .fontWeight(.bold)
                                Text(roll.date.formatted(date: .omitted, time: .shortened))
                                    .font(.caption2)
                                    .foregroundStyle(.secondary)
                            }
                        }
                        Divider()
                    }
                }
            }
            .padding()
        }
        .onAppear {
            loadHistory()
        }
    }

    func rollDie(sides: Int) -> Int {
        let roll = Int.random(in: 1...sides)
        return roll
    }

    func rollDice(count: Int, sides: Int) -> [Int] {
        var rolls: [Int] = []
        for _ in 1...count {
            rolls.append(rollDie(sides: sides))
        }
        return rolls
    }

    func isValidQuantity(_ value: Int) -> Bool {
        value >= 1 && value <= 10
    }

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

    func performRoll() {
        if isValidQuantity(quantity) {
            let values = rollDice(count: quantity, sides: selectedDie.sides)
            let roll = RollResult(dieType: selectedDie, values: values, modifier: modifier)
            latestRoll = roll
            history.insert(roll, at: 0)
            if history.count > HistoryStore.maximumCount {
                history.removeLast()
            }
            saveHistory()
        } else {
            print("Invalid quantity: \(quantity)")
        }
    }

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

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

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

#Preview {
    ContentView()
}

DiceFoundry/DiceFoundryApp.swift

//
//  DiceFoundryApp.swift
//  DiceFoundry
//

import SwiftUI

@main
struct DiceFoundryApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

DiceFoundry/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

    var id: Int {
        rawValue
    }

    var sides: Int {
        rawValue
    }

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

DiceFoundry/HistoryStore.swift

//
//  HistoryStore.swift
//  DiceFoundry
//

import Foundation

struct HistoryStore {
    static let maximumCount = 50

    let fileURL: URL

    init(fileURL: URL = URL.documentsDirectory.appending(path: "roll-history.json")) {
        self.fileURL = fileURL
    }

    func load() throws -> [RollResult] {
        if !FileManager.default.fileExists(atPath: fileURL.path(percentEncoded: false)) {
            return []
        }
        let data = try Data(contentsOf: fileURL)
        let history = try JSONDecoder().decode([RollResult].self, from: data)
        return history
    }

    func save(_ history: [RollResult]) throws {
        let data = try JSONEncoder().encode(history)
        try data.write(to: fileURL, options: .atomic)
    }
}

DiceFoundry/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: ", ")
    }
}

End of Chapter 11 — Styled, Animated and Accessible

Reference folder: Reference-Checkpoints/Checkpoint-11-Styling-Animation-Accessibility

DiceFoundry/ContentView.swift

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

import SwiftUI

struct ContentView: View {
    @State private var selectedDie: DieType = .d6
    @State private var quantity: Int = 1
    @State private var modifier: Int = 0
    @State private var latestRoll: RollResult?
    @State private var history: [RollResult] = []
    @State private var rollCount: Int = 0

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

    private let store = HistoryStore()

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

                DiePicker(selection: $selectedDie)
                    .cardStyle()

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

                ResultView(roll: latestRoll, rollCount: 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: rollCount) { _, _ in
            hapticsEnabled
        }
        .onAppear {
            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 {
            performRoll()
        } 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()
                Button("Clear") {
                    clearHistory()
                }
                .disabled(history.isEmpty)
                .accessibilityLabel("Clear history")
            }

            if history.isEmpty {
                Text("No rolls yet")
                    .foregroundStyle(.secondary)
            }

            ForEach(history) { roll in
                HistoryRow(roll: roll)
                Divider()
            }
        }
    }

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

    private func rollDie(sides: Int) -> Int {
        let roll = Int.random(in: 1...sides)
        return roll
    }

    private func rollDice(count: Int, sides: Int) -> [Int] {
        var rolls: [Int] = []
        for _ in 1...count {
            rolls.append(rollDie(sides: sides))
        }
        return rolls
    }

    private func isValidQuantity(_ value: Int) -> Bool {
        value >= 1 && value <= 10
    }

    private func performRoll() {
        if isValidQuantity(quantity) {
            let values = rollDice(count: quantity, sides: selectedDie.sides)
            let roll = RollResult(dieType: selectedDie, values: values, modifier: modifier)
            latestRoll = roll
            rollCount += 1
            history.insert(roll, at: 0)
            if history.count > HistoryStore.maximumCount {
                history.removeLast()
            }
            saveHistory()
        } else {
            print("Invalid quantity: \(quantity)")
        }
    }

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

    private 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)")
        }
    }
}

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

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

DiceFoundry/DiceFoundryApp.swift

//
//  DiceFoundryApp.swift
//  DiceFoundry
//

import SwiftUI

@main
struct DiceFoundryApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

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

    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"
        }
    }
}

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: ", ")
    }

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

DiceFoundry/Persistence/HistoryStore.swift

//
//  HistoryStore.swift
//  DiceFoundry
//

import Foundation

struct HistoryStore {
    static let maximumCount = 50

    let fileURL: URL

    init(fileURL: URL = URL.documentsDirectory.appending(path: "roll-history.json")) {
        self.fileURL = fileURL
    }

    func load() throws -> [RollResult] {
        if !FileManager.default.fileExists(atPath: fileURL.path(percentEncoded: false)) {
            return []
        }
        let data = try Data(contentsOf: fileURL)
        let history = try JSONDecoder().decode([RollResult].self, from: data)
        return history
    }

    func save(_ history: [RollResult]) throws {
        let data = try JSONEncoder().encode(history)
        try data.write(to: fileURL, options: .atomic)
    }
}

DiceFoundry/Theme/Theme.swift

//
//  Theme.swift
//  DiceFoundry
//

import SwiftUI

enum Theme {
    // Colors come from the asset catalog, so each one has a light and a dark version.
    static let background = Color(.backgroundPrimary)
    static let backgroundSecondary = Color(.backgroundSecondary)
    static let card = Color(.cardBackground)
    static let brass = Color(.brass)
    static let gold = Color(.gold)
    static let onBrass = Color(.onBrass)

    static let cornerRadius: CGFloat = 16
    static let spacing: CGFloat = 20

    static let backgroundGradient = LinearGradient(
        colors: [background, backgroundSecondary],
        startPoint: .top,
        endPoint: .bottom
    )

    static let brassGradient = LinearGradient(
        colors: [gold, brass],
        startPoint: .top,
        endPoint: .bottom
    )
}

extension View {
    func cardStyle() -> some View {
        self
            .padding()
            .frame(maxWidth: .infinity)
            .background(Theme.card, in: RoundedRectangle(cornerRadius: Theme.cornerRadius))
            .overlay(
                RoundedRectangle(cornerRadius: Theme.cornerRadius)
                    .stroke(Theme.brass.opacity(0.35), lineWidth: 1)
            )
            .shadow(color: .black.opacity(0.12), radius: 8, y: 4)
    }
}

DiceFoundry/Views/DieButton.swift

//
//  DieButton.swift
//  DiceFoundry
//

import SwiftUI

struct DieButton: View {
    let dieType: DieType
    let isSelected: Bool
    let action: () -> Void

    var body: some View {
        Button(action: action) {
            VStack(spacing: 6) {
                Image(systemName: dieType.symbolName)
                    .font(.title2)
                Text(dieType.name)
                    .font(.headline)
            }
            .frame(maxWidth: .infinity)
            .padding(.vertical, 12)
            .foregroundStyle(isSelected ? Theme.onBrass : Color.primary)
            .background(
                RoundedRectangle(cornerRadius: 12)
                    .fill(isSelected ? Theme.brass : Theme.backgroundSecondary)
            )
            .overlay(
                RoundedRectangle(cornerRadius: 12)
                    .stroke(isSelected ? Theme.gold : Color.clear, lineWidth: 2)
            )
        }
        .buttonStyle(.plain)
        .accessibilityLabel(dieType.accessibilityName)
        .accessibilityAddTraits(isSelected ? .isSelected : [])
    }
}

#Preview {
    HStack {
        DieButton(dieType: .d6, isSelected: true) {}
        DieButton(dieType: .d20, isSelected: false) {}
    }
    .padding()
}

DiceFoundry/Views/DiePicker.swift

//
//  DiePicker.swift
//  DiceFoundry
//

import SwiftUI

struct DiePicker: View {
    @Binding var selection: DieType

    private let columns = [
        GridItem(.flexible()),
        GridItem(.flexible()),
        GridItem(.flexible())
    ]

    var body: some View {
        LazyVGrid(columns: columns, spacing: 12) {
            ForEach(DieType.allCases) { dieType in
                DieButton(dieType: dieType, isSelected: dieType == selection) {
                    selection = dieType
                }
            }
        }
    }
}

#Preview {
    DiePicker(selection: .constant(.d20))
        .padding()
}

DiceFoundry/Views/HistoryRow.swift

//
//  HistoryRow.swift
//  DiceFoundry
//

import SwiftUI

struct HistoryRow: View {
    let roll: RollResult

    var body: some View {
        HStack {
            Image(systemName: roll.dieType.symbolName)
                .font(.title3)
                .foregroundStyle(Theme.brass)
                .frame(width: 32)
            VStack(alignment: .leading) {
                Text(roll.notation)
                    .font(.headline)
                Text(roll.valuesDescription)
                    .font(.caption)
                    .foregroundStyle(.secondary)
            }
            Spacer()
            VStack(alignment: .trailing) {
                Text("\(roll.total)")
                    .font(.title2)
                    .fontWeight(.bold)
                Text(roll.date.formatted(date: .omitted, time: .shortened))
                    .font(.caption2)
                    .foregroundStyle(.secondary)
            }
        }
        .accessibilityElement(children: .ignore)
        .accessibilityLabel("\(roll.notation), total \(roll.total). Dice: \(roll.valuesDescription).")
    }
}

#Preview {
    HistoryRow(roll: RollResult(dieType: .d20, values: [17, 3], modifier: -4))
        .padding()
}

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
                        Text("\(roll.values[index])")
                            .font(.title3)
                            .fontWeight(.semibold)
                            .frame(minWidth: 44, minHeight: 44)
                            .background(Theme.backgroundSecondary, in: RoundedRectangle(cornerRadius: 8))
                            .overlay(
                                RoundedRectangle(cornerRadius: 8)
                                    .stroke(Theme.brass.opacity(0.5), lineWidth: 1)
                            )
                    }
                }

                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 {
            return "Rolled \(roll.notation). Total \(roll.total). Dice: \(roll.valuesDescription)."
        } else {
            return "No roll yet. Tap Roll Dice to begin."
        }
    }

    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()
}

DiceFoundry/Views/RollOptionsView.swift

//
//  RollOptionsView.swift
//  DiceFoundry
//

import SwiftUI

struct RollOptionsView: View {
    @Binding var quantity: Int
    @Binding var modifier: Int

    var body: some View {
        VStack(spacing: 12) {
            Stepper("Number of dice: \(quantity)", value: $quantity, in: 1...10)
            Divider()
            Stepper("Modifier: \(RollResult.formatModifier(modifier))", value: $modifier, in: -20...20)
        }
        .font(.body.weight(.medium))
    }
}

#Preview {
    RollOptionsView(quantity: .constant(3), modifier: .constant(2))
        .padding()
}

End of Chapter 13 — Final Guided Architecture

Reference folder: Reference-Checkpoints/Checkpoint-13-Architecture

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()
                Button("Clear") {
                    viewModel.clearHistory()
                }
                .disabled(viewModel.history.isEmpty)
                .accessibilityLabel("Clear history")
            }

            if viewModel.history.isEmpty {
                Text("No rolls yet")
                    .foregroundStyle(.secondary)
            }

            ForEach(viewModel.history) { 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/DiceFoundryApp.swift

//
//  DiceFoundryApp.swift
//  DiceFoundry
//

import SwiftUI

@main
struct DiceFoundryApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

DiceFoundryTests/DiceRollerTests.swift

//
//  DiceRollerTests.swift
//  DiceFoundryTests
//

import Testing
@testable import DiceFoundry

@MainActor
struct DiceRollerTests {

    @Test func rollUsesInjectedValues() {
        let roller = DiceRoller(randomValue: { _ in 4 })
        let roll = roller.roll(.d6, quantity: 3, modifier: 0)
        #expect(roll.values == [4, 4, 4])
    }

    @Test func rollProducesRequestedNumberOfDice() {
        let roller = DiceRoller()
        for quantity in DiceRoller.quantityRange {
            let roll = roller.roll(.d8, quantity: quantity, modifier: 0)
            #expect(roll.values.count == quantity)
        }
    }

    @Test func quantityIsClampedToValidRange() {
        let roller = DiceRoller(randomValue: { _ in 1 })
        #expect(roller.roll(.d6, quantity: 0, modifier: 0).values.count == 1)
        #expect(roller.roll(.d6, quantity: -5, modifier: 0).values.count == 1)
        #expect(roller.roll(.d6, quantity: 99, modifier: 0).values.count == 10)
    }

    @Test func rollRequestsTheCorrectRangeForEachDie() {
        for dieType in DieType.allCases {
            var requestedRange: ClosedRange<Int>?
            let roller = DiceRoller(randomValue: { range in
                requestedRange = range
                return range.lowerBound
            })
            _ = roller.roll(dieType, quantity: 1, modifier: 0)
            #expect(requestedRange == 1...dieType.sides)
        }
    }

    @Test(arguments: DieType.allCases)
    func realRandomValuesStayInRange(dieType: DieType) {
        let roller = DiceRoller()
        for _ in 1...200 {
            let roll = roller.roll(dieType, quantity: 10, modifier: 0)
            for value in roll.values {
                #expect((1...dieType.sides).contains(value))
            }
        }
    }
}

DiceFoundryTests/HistoryStoreTests.swift

//
//  HistoryStoreTests.swift
//  DiceFoundryTests
//

import Testing
import Foundation
@testable import DiceFoundry

@MainActor
struct HistoryStoreTests {

    // Each test gets its own file in the temporary directory,
    // so tests never touch the real roll history.
    let store = HistoryStore(
        fileURL: URL.temporaryDirectory.appending(path: "history-test-\(UUID().uuidString).json")
    )

    @Test func missingFileLoadsAsEmptyHistory() throws {
        let history = try store.load()
        #expect(history.isEmpty)
    }

    @Test func savedHistoryLoadsBackUnchanged() throws {
        let first = RollResult(dieType: .d6, values: [4, 2, 6], modifier: 2)
        let second = RollResult(dieType: .d20, values: [11], modifier: -1)

        try store.save([first, second])
        let loaded = try store.load()

        #expect(loaded.count == 2)
        #expect(loaded[0].id == first.id)
        #expect(loaded[0].values == [4, 2, 6])
        #expect(loaded[0].total == 14)
        #expect(loaded[1].dieType == .d20)
        #expect(loaded[1].modifier == -1)
    }

    @Test func corruptFileThrowsAnError() throws {
        try Data("not json".utf8).write(to: store.fileURL)
        #expect(throws: (any Error).self) {
            try store.load()
        }
    }
}

DiceFoundryTests/RollResultTests.swift

//
//  RollResultTests.swift
//  DiceFoundryTests
//

import Testing
@testable import DiceFoundry

@MainActor
struct RollResultTests {

    @Test func courseExampleThreeD6PlusTwo() {
        let roll = RollResult(dieType: .d6, values: [4, 2, 6], modifier: 2)
        #expect(roll.subtotal == 12)
        #expect(roll.total == 14)
        #expect(roll.notation == "3D6 + 2")
        #expect(roll.valuesDescription == "4, 2, 6")
    }

    @Test func negativeModifier() {
        let roll = RollResult(dieType: .d20, values: [15, 3], modifier: -4)
        #expect(roll.total == 14)
        #expect(roll.notation == "2D20 - 4")
    }

    @Test func zeroModifierHasNoSuffix() {
        let roll = RollResult(dieType: .d8, values: [5], modifier: 0)
        #expect(roll.total == 5)
        #expect(roll.notation == "1D8")
    }

    @Test func modifierFormatting() {
        #expect(RollResult.formatModifier(3) == "+3")
        #expect(RollResult.formatModifier(0) == "0")
        #expect(RollResult.formatModifier(-2) == "-2")
    }
}

DiceFoundryTests/RollViewModelTests.swift

//
//  RollViewModelTests.swift
//  DiceFoundryTests
//

import Testing
import Foundation
@testable import DiceFoundry

@MainActor
struct RollViewModelTests {

    // A view model with predictable dice (always 3) and a throwaway history file.
    func makeViewModel(fileURL: URL? = nil) -> RollViewModel {
        let url = fileURL ?? URL.temporaryDirectory.appending(path: "viewmodel-test-\(UUID().uuidString).json")
        return RollViewModel(
            roller: DiceRoller(randomValue: { _ in 3 }),
            store: HistoryStore(fileURL: url)
        )
    }

    @Test func rollUsesCurrentSelections() {
        let viewModel = makeViewModel()
        viewModel.selectedDie = .d8
        viewModel.quantity = 2
        viewModel.modifier = 5

        viewModel.roll()

        #expect(viewModel.latestRoll?.notation == "2D8 + 5")
        #expect(viewModel.latestRoll?.total == 11)
        #expect(viewModel.rollCount == 1)
    }

    @Test func newestRollIsFirstInHistory() {
        let viewModel = makeViewModel()
        viewModel.selectedDie = .d4
        viewModel.roll()
        viewModel.selectedDie = .d12
        viewModel.roll()

        #expect(viewModel.history.count == 2)
        #expect(viewModel.history.first?.dieType == .d12)
        #expect(viewModel.history.last?.dieType == .d4)
    }

    @Test func historyNeverExceedsMaximum() {
        let viewModel = makeViewModel()
        for _ in 1...(HistoryStore.maximumCount + 5) {
            viewModel.roll()
        }
        #expect(viewModel.history.count == HistoryStore.maximumCount)
    }

    @Test func clearHistoryEmptiesTheList() {
        let viewModel = makeViewModel()
        viewModel.roll()
        viewModel.clearHistory()
        #expect(viewModel.history.isEmpty)
    }

    @Test func historySurvivesANewViewModel() {
        let url = URL.temporaryDirectory.appending(path: "relaunch-test-\(UUID().uuidString).json")

        let firstLaunch = makeViewModel(fileURL: url)
        firstLaunch.roll()
        firstLaunch.roll()

        let secondLaunch = makeViewModel(fileURL: url)
        secondLaunch.loadHistory()

        #expect(secondLaunch.history.count == 2)
        #expect(secondLaunch.latestRoll?.id == firstLaunch.history.first?.id)
    }
}

DiceFoundry/Logic/DiceRoller.swift

//
//  DiceRoller.swift
//  DiceFoundry
//

import Foundation

struct DiceRoller {
    static let quantityRange = 1...10
    static let modifierRange = -20...20

    // The source of random numbers. The app uses Int.random(in:).
    // Tests replace it with a predictable function.
    var randomValue: (ClosedRange<Int>) -> Int = { range in
        Int.random(in: range)
    }

    func roll(_ dieType: DieType, quantity: Int, modifier: Int) -> RollResult {
        let safeQuantity = min(max(quantity, Self.quantityRange.lowerBound), Self.quantityRange.upperBound)
        var values: [Int] = []
        for _ in 1...safeQuantity {
            values.append(randomValue(1...dieType.sides))
        }
        return RollResult(dieType: dieType, values: values, modifier: modifier)
    }
}

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

    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"
        }
    }
}

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: ", ")
    }

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

DiceFoundry/Persistence/HistoryStore.swift

//
//  HistoryStore.swift
//  DiceFoundry
//

import Foundation

struct HistoryStore {
    static let maximumCount = 50

    let fileURL: URL

    init(fileURL: URL = URL.documentsDirectory.appending(path: "roll-history.json")) {
        self.fileURL = fileURL
    }

    func load() throws -> [RollResult] {
        if !FileManager.default.fileExists(atPath: fileURL.path(percentEncoded: false)) {
            return []
        }
        let data = try Data(contentsOf: fileURL)
        let history = try JSONDecoder().decode([RollResult].self, from: data)
        return history
    }

    func save(_ history: [RollResult]) throws {
        let data = try JSONEncoder().encode(history)
        try data.write(to: fileURL, options: .atomic)
    }
}

DiceFoundry/Theme/Theme.swift

//
//  Theme.swift
//  DiceFoundry
//

import SwiftUI

enum Theme {
    // Colors come from the asset catalog, so each one has a light and a dark version.
    static let background = Color(.backgroundPrimary)
    static let backgroundSecondary = Color(.backgroundSecondary)
    static let card = Color(.cardBackground)
    static let brass = Color(.brass)
    static let gold = Color(.gold)
    static let onBrass = Color(.onBrass)

    static let cornerRadius: CGFloat = 16
    static let spacing: CGFloat = 20

    static let backgroundGradient = LinearGradient(
        colors: [background, backgroundSecondary],
        startPoint: .top,
        endPoint: .bottom
    )

    static let brassGradient = LinearGradient(
        colors: [gold, brass],
        startPoint: .top,
        endPoint: .bottom
    )
}

extension View {
    func cardStyle() -> some View {
        self
            .padding()
            .frame(maxWidth: .infinity)
            .background(Theme.card, in: RoundedRectangle(cornerRadius: Theme.cornerRadius))
            .overlay(
                RoundedRectangle(cornerRadius: Theme.cornerRadius)
                    .stroke(Theme.brass.opacity(0.35), lineWidth: 1)
            )
            .shadow(color: .black.opacity(0.12), radius: 8, y: 4)
    }
}

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

    // 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/DieButton.swift

//
//  DieButton.swift
//  DiceFoundry
//

import SwiftUI

struct DieButton: View {
    let dieType: DieType
    let isSelected: Bool
    let action: () -> Void

    var body: some View {
        Button(action: action) {
            VStack(spacing: 6) {
                Image(systemName: dieType.symbolName)
                    .font(.title2)
                Text(dieType.name)
                    .font(.headline)
            }
            .frame(maxWidth: .infinity)
            .padding(.vertical, 12)
            .foregroundStyle(isSelected ? Theme.onBrass : Color.primary)
            .background(
                RoundedRectangle(cornerRadius: 12)
                    .fill(isSelected ? Theme.brass : Theme.backgroundSecondary)
            )
            .overlay(
                RoundedRectangle(cornerRadius: 12)
                    .stroke(isSelected ? Theme.gold : Color.clear, lineWidth: 2)
            )
        }
        .buttonStyle(.plain)
        .accessibilityLabel(dieType.accessibilityName)
        .accessibilityAddTraits(isSelected ? .isSelected : [])
    }
}

#Preview {
    HStack {
        DieButton(dieType: .d6, isSelected: true) {}
        DieButton(dieType: .d20, isSelected: false) {}
    }
    .padding()
}

DiceFoundry/Views/DiePicker.swift

//
//  DiePicker.swift
//  DiceFoundry
//

import SwiftUI

struct DiePicker: View {
    @Binding var selection: DieType

    private let columns = [
        GridItem(.flexible()),
        GridItem(.flexible()),
        GridItem(.flexible())
    ]

    var body: some View {
        LazyVGrid(columns: columns, spacing: 12) {
            ForEach(DieType.allCases) { dieType in
                DieButton(dieType: dieType, isSelected: dieType == selection) {
                    selection = dieType
                }
            }
        }
    }
}

#Preview {
    DiePicker(selection: .constant(.d20))
        .padding()
}

DiceFoundry/Views/HistoryRow.swift

//
//  HistoryRow.swift
//  DiceFoundry
//

import SwiftUI

struct HistoryRow: View {
    let roll: RollResult

    var body: some View {
        HStack {
            Image(systemName: roll.dieType.symbolName)
                .font(.title3)
                .foregroundStyle(Theme.brass)
                .frame(width: 32)
            VStack(alignment: .leading) {
                Text(roll.notation)
                    .font(.headline)
                Text(roll.valuesDescription)
                    .font(.caption)
                    .foregroundStyle(.secondary)
            }
            Spacer()
            VStack(alignment: .trailing) {
                Text("\(roll.total)")
                    .font(.title2)
                    .fontWeight(.bold)
                Text(roll.date.formatted(date: .omitted, time: .shortened))
                    .font(.caption2)
                    .foregroundStyle(.secondary)
            }
        }
        .accessibilityElement(children: .ignore)
        .accessibilityLabel("\(roll.notation), total \(roll.total). Dice: \(roll.valuesDescription).")
    }
}

#Preview {
    HistoryRow(roll: RollResult(dieType: .d20, values: [17, 3], modifier: -4))
        .padding()
}

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
                        Text("\(roll.values[index])")
                            .font(.title3)
                            .fontWeight(.semibold)
                            .frame(minWidth: 44, minHeight: 44)
                            .background(Theme.backgroundSecondary, in: RoundedRectangle(cornerRadius: 8))
                            .overlay(
                                RoundedRectangle(cornerRadius: 8)
                                    .stroke(Theme.brass.opacity(0.5), lineWidth: 1)
                            )
                    }
                }

                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 {
            return "Rolled \(roll.notation). Total \(roll.total). Dice: \(roll.valuesDescription)."
        } else {
            return "No roll yet. Tap Roll Dice to begin."
        }
    }

    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()
}

DiceFoundry/Views/RollOptionsView.swift

//
//  RollOptionsView.swift
//  DiceFoundry
//

import SwiftUI

struct RollOptionsView: View {
    @Binding var quantity: Int
    @Binding var modifier: Int

    var body: some View {
        VStack(spacing: 12) {
            Stepper("Number of dice: \(quantity)", value: $quantity, in: DiceRoller.quantityRange)
            Divider()
            Stepper("Modifier: \(RollResult.formatModifier(modifier))", value: $modifier, in: DiceRoller.modifierRange)
        }
        .font(.body.weight(.medium))
    }
}

#Preview {
    RollOptionsView(quantity: .constant(3), modifier: .constant(2))
        .padding()
}