Tutorial outline

Unit 1

  1. 01Getting started
  2. 02Names and functions
  3. 03Control
  4. 04Higher-order functions
  5. 05Environments and closures
  6. 06Functional abstraction
  7. 07Recursion
  8. 08Tree recursion
  1. D0Getting started
  2. D1Control and environment diagrams
  3. HW1Functions and control
  4. D2Higher-order functions
  5. HW2Higher-order functions
  6. P1Hog
  7. D3Recursion
  8. D4Tree recursion
  9. HW3Recursion

Unit 2

  1. 09Sequences
  2. 10Dictionaries, sets, and tuples
  3. 11Optionals
  4. 12Structures and enumerations
  5. 13Linked lists and trees
  6. 14Mutation and value semantics
  7. 15Classes and inheritance
  8. 16Protocols and generics
  9. 17Iterators and lazy sequences
  10. 18Efficiency and memoization
  1. HW4Sequences and containers
  2. P2Cats
  3. D5Trees
  4. HW5Recursive data and mutation
  5. D6Objects and classes
  6. HW6Classes and interfaces
  7. P3Ants vs. SomeBees
  8. D7Iterators and efficiency
  9. HW7Lazy sequences and efficiency

Unit 3

  1. 19Algebraic data types and pattern matching
  2. 20Writing an interpreter
  3. 21Error handling
  4. 22Concurrency with async and await
  5. 23Testing
  6. 24Building a Swift package
  1. D8Algebraic data types
  2. HW8Pattern matching
  3. D9Interpreters
  4. HW9Interpreters and errors
  5. P4Scheme
  6. D10Concurrency
  7. D11Testing
  8. HW10Concurrency and testing

Unit 4

  1. 25References, identity, and memory
  2. 26Drawing with SwiftUI
  3. 27Testing data structures
  4. 28IntLists and SLLists
  5. 29Doubly linked lists and deques
  6. 30Arrays from scratch
  7. 31Interface and implementation inheritance
  8. 32Iteration, equality, and ordering
  9. 33Copy-on-write collections
  1. D12Swift review
  2. D13References, classes, and arrays
  3. HW11Swift warm-up
  4. P5Particle Simulator
  5. D14IntLists and SLLists
  6. HW12IntLists
  7. P6LinkedListDeque
  8. D15DLLists, default implementations, and array lists
  9. P7ArrayDeque
  10. D16Comparables and iterators
  11. HW13Review I

Unit 5

  1. 34Asymptotic analysis
  2. 35Disjoint sets
  3. 36Analyzing recursion
  4. 37Amortized analysis and the limits of big O
  5. 38Sets, maps, and binary search trees
  6. 39B-trees
  7. 40Left-leaning red-black trees
  8. 41Heaps and priority queues
  1. D17Asymptotics and disjoint sets
  2. P8Percolation
  3. D18Asymptotics II
  4. HW14Asymptotic analysis
  5. D19BSTs, B-trees, and LLRBs
  6. HW15BSTMap

Unit 6

  1. 42Data-driven apps with SwiftUI
  2. 43Tree and graph traversals
  3. 44Graph implementations
  4. 45Shortest paths: Dijkstra and A*
  5. 46Minimum spanning trees
  6. 47DAGs, topological sort, and reductions
  1. D20Tree traversals and graphs
  2. P9NGordNet
  3. D21Shortest paths and MSTs

Unit 7

  1. 48Hash tables
  2. 49Hash functions
  3. 50Tries and prefix operations
  4. 51Software engineering: managing complexity
  5. 52Games with SwiftUI
  6. 53Designing a world
  7. 54Basic sorts
  8. 55Quicksort and selection
  9. 56The limits of sorting
  10. 57Radix sorts
  11. 58Compression and complexity
  12. 59Computing, society, and what comes next
  1. D22Hashing and tries
  2. HW16Review II
  3. D23Hashing and tries, revisited
  4. P10Build Your Own World
  5. D24Sorting
  6. HW17HashMap
  7. D25Sorting II
  8. HW18LLRB set
  9. HW19Final review

Games with SwiftUI

Turning input into moves: a game model that knows nothing about the screen, keyboard input with focus and onKeyPress, replaying input as a string, a tile renderer and HUD, and saving and loading with Codable and FileManager.

CS61B
For Project 5: Build Your Own World
Swift book
Protocols

Project 10 is a game: explore a generated world with the keyboard, see what is under the pointer, and quit and come back later to exactly where you were. This lesson builds the pieces: a game model that does not know it is being drawn, keyboard input, a way to replay a game from a string of keys, rendering tiles, and saving to a file with Codable. It ends with a complete small game.

The model first, again

As in Lesson 26, the game’s rules live in plain Swift. A world is a grid of tiles and an avatar position; a move is a pure function from one state to the next:

enum Tile: Character, Codable {
    case floor = "."
    case wall = "#"
    case flower = "*"
}

enum Move: Character {
    case up = "w", left = "a", down = "s", right = "d"
}

struct Game: Codable, Equatable {
    var tiles: [[Tile]]
    var row: Int
    var column: Int
    var flowersPicked = 0

    mutating func apply(_ move: Move) {
        let (dr, dc) = switch move {
        case .up: (-1, 0)
        case .down: (1, 0)
        case .left: (0, -1)
        case .right: (0, 1)
        }
        let (r, c) = (row + dr, column + dc)
        guard tiles.indices.contains(r), tiles[r].indices.contains(c), tiles[r][c] != .wall else { return }
        (row, column) = (r, c)
        if tiles[r][c] == .flower {
            tiles[r][c] = .floor
            flowersPicked += 1
        }
    }
}

var game = Game(tiles: ["#####", "#..*#", "#.#.#", "#*..#", "#####"].map { $0.map { Tile(rawValue: $0)! } },
                row: 1, column: 1)
for key in "ddssaaa" {
    if let move = Move(rawValue: key) { game.apply(move) }
}
print(game.row, game.column, game.flowersPicked)   // 3 1 2

Tile and Move use raw values: each case has a Character, so Tile(rawValue: "#") is .wall and a key press converts directly into a move. The avatar moves right twice, picking the first flower, down twice, and left twice, picking the second; the third left bumps into the wall and changes nothing.

Because the game is a value, a move produces a new state and nothing else. That makes the next idea possible.

Input as a string

CS61B’s Build Your Own World requires that a game can be driven by a string of keys, like "n123sddssaq": new world with seed 123, start, then moves, then quit. The same string must always produce the same world and the same final state. That requirement does three jobs:

  • Testing: a test is a string and an expected final state, with no window and no keyboard.
  • Saving: one way to save a game is to save the seed and the keys pressed, and replay them to load.
  • Debugging: a bug report is a string that reproduces it exactly.

It only works if the world is deterministic: every random choice must come from a seeded generator (Lessons 23 and 53), never from Int.random(in:) with the system generator.

What would Swift print?

enum Move: Character {
    case up = "w", left = "a", down = "s", right = "d"
}
let keys = "wWxdd q"
let moves = keys.compactMap { Move(rawValue: $0) }
print(moves.count, moves.last == .right)

Type Error if running it would crash. For several lines of output, put each on its own line.

Show answer and explanation

Answer3 true

Move(rawValue:) returns nil for anything that is not a move, including the capital W, x, the space, and q, and compactMap drops those. What remains is w, d, and d. A real game would treat q as quit, a separate command.

Keyboard input

A SwiftUI view receives key presses when it has focus. Mark the view as focusable, give it focus when it appears, and handle keys with .onKeyPress:

import SwiftUI

struct KeyboardDemo: View {
    @State private var log: [String] = []
    @FocusState private var focused: Bool

    var body: some View {
        VStack(alignment: .leading) {
            Text("Press w, a, s, or d")
            Text(log.suffix(5).joined(separator: " "))
                .monospaced()
        }
        .padding()
        .focusable()
        .focused($focused)
        .onAppear { focused = true }
        .onKeyPress(characters: .alphanumerics) { press in
            log.append(String(press.characters))
            return .handled
        }
    }
}

@FocusState is a property wrapper that tracks which view has keyboard focus, and setting it moves focus. .onKeyPress returns .handled to say the key was used, or .ignored to let it continue to other views. Variants of .onKeyPress also match specific keys, such as the arrow keys: .onKeyPress(.upArrow) { … }.

A game loop, or not

Many games change only when the player acts: the world stays still between key presses, and there is no loop at all. The view reads the model, and each key press changes it; SwiftUI redraws. When things must move on their own, such as enemies or a day–night cycle, a task loop advances the model at a fixed rate, as in Lesson 26’s Game of Life, or TimelineView(.animation) redraws every frame and computes the state from the elapsed time.

Saving and loading

Codable is Swift’s protocol for converting values to and from external formats. A type whose stored properties are all Codable conforms automatically, as Game does, and JSONEncoder and JSONDecoder from Foundation turn it into JSON and back:

import Foundation

enum Tile: Character, Codable {
    case floor = ".", wall = "#"
}

struct Game: Codable, Equatable {
    var tiles: [[Tile]]
    var row: Int
    var column: Int
}

let game = Game(tiles: [[.wall, .floor], [.floor, .floor]], row: 1, column: 0)
let data = try JSONEncoder().encode(game)
let text = String(decoding: data, as: UTF8.self)
let loaded = try JSONDecoder().decode(Game.self, from: data)
print(loaded == game, text.contains("\"row\":1"))   // true true

let file = FileManager.default.temporaryDirectory.appendingPathComponent("save.json")
try data.write(to: file)
let reread = try JSONDecoder().decode(Game.self, from: Data(contentsOf: file))
print(reread == game)                               // true
try FileManager.default.removeItem(at: file)

An enum with raw values encodes as its raw value, so each tile is a one-character string in the JSON. Writing and reading can fail, so they throw (Lesson 21), and Data(contentsOf:) reads a whole file. For a real app, save in the Application Support directory, from FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask), rather than a temporary one that the system may clear.

Drawing tiles and a HUD

A world is drawn like Lesson 26’s grid, with a Canvas filling a square per tile. A HUD (heads-up display) shows information over the world, such as what the tile under the pointer is. .onContinuousHover reports the pointer’s position, and an overlay with a glass background, from Lesson 26, keeps it readable over any tiles:

import SwiftUI

enum Tile: Character {
    case floor = ".", wall = "#", flower = "*"

    var color: Color {
        switch self {
        case .floor: Color(white: 0.2)
        case .wall: .brown
        case .flower: .pink
        }
    }

    var name: String {
        switch self {
        case .floor: "floor"
        case .wall: "wall"
        case .flower: "flower"
        }
    }
}

struct WorldView: View {
    let tiles: [[Tile]]
    let avatar: (row: Int, column: Int)
    @State private var hovered: Tile?

    var body: some View {
        GeometryReader { geometry in
            let side = min(geometry.size.width / CGFloat(tiles[0].count), geometry.size.height / CGFloat(tiles.count))
            Canvas { context, _ in
                for (r, row) in tiles.enumerated() {
                    for (c, tile) in row.enumerated() {
                        let square = CGRect(x: CGFloat(c) * side, y: CGFloat(r) * side, width: side, height: side)
                        context.fill(Path(square), with: .color(tile.color))
                    }
                }
                let me = CGRect(x: CGFloat(avatar.column) * side, y: CGFloat(avatar.row) * side, width: side, height: side)
                context.fill(Path(ellipseIn: me.insetBy(dx: side * 0.15, dy: side * 0.15)), with: .color(.yellow))
            }
            .onContinuousHover { phase in
                if case .active(let point) = phase,
                   tiles.indices.contains(Int(point.y / side)), tiles[0].indices.contains(Int(point.x / side)) {
                    hovered = tiles[Int(point.y / side)][Int(point.x / side)]
                } else {
                    hovered = nil
                }
            }
            .overlay(alignment: .topLeading) {
                Text(hovered?.name ?? " ")
                    .padding(.horizontal, 12)
                    .padding(.vertical, 6)
                    .glassEffect(.regular, in: .capsule)
                    .padding(8)
            }
        }
    }
}

The HUD is ordinary view composition: an overlay whose content depends on state. The view still owns no game rules.

Put the lines in order

Put the lines in order so the program prints 2.

  1. position += key == "d" ? 1 : -1
  2. }
  3. let keys = "ddad"
  4. var position = 0
  5. for key in keys {
  6. print(position)

Show the correct program
var position = 0
let keys = "ddad"
for key in keys {
    position += key == "d" ? 1 : -1
}
print(position)

Lab 51: Games

Q0: What would Swift print?

What would Swift print?

enum Direction: String, Codable {
    case north, south
}
let raw = Direction.north.rawValue
print(raw, Direction(rawValue: "south") == .south, Direction(rawValue: "up") as Any)

Type Error if running it would crash. For several lines of output, put each on its own line.

Show answer and explanation

Answernorth true nil

A String raw-value enum gets each case’s name as its raw value unless another is given. Direction(rawValue:) returns nil for strings that are not cases, which makes it a safe parser.

Q1: Replay

Write play(_:on:), which applies a string of keys to a Game and returns the final state, ignoring unknown keys and stopping at q. Then check that playing two strings one after the other equals playing their concatenation.

Show solution
enum Tile: Character { case floor = ".", wall = "#" }
enum Move: Character { case up = "w", left = "a", down = "s", right = "d" }

struct Game: Equatable {
    var tiles: [[Tile]]
    var row: Int
    var column: Int

    mutating func apply(_ move: Move) {
        let (dr, dc) = switch move {
        case .up: (-1, 0)
        case .down: (1, 0)
        case .left: (0, -1)
        case .right: (0, 1)
        }
        let (r, c) = (row + dr, column + dc)
        guard tiles.indices.contains(r), tiles[r].indices.contains(c), tiles[r][c] != .wall else { return }
        (row, column) = (r, c)
    }
}

func play(_ keys: String, on start: Game) -> Game {
    var game = start
    for key in keys {
        if key == "q" { break }
        if let move = Move(rawValue: key) { game.apply(move) }
    }
    return game
}

let start = Game(tiles: ["....", ".##.", "...."].map { $0.map { Tile(rawValue: $0)! } }, row: 0, column: 0)
let a = "ddds", b = "sxaa"
assert(play(a + b, on: start) == play(b, on: play(a, on: start)))
assert(play("dddsq ssss", on: start) == play("ddds", on: start))
assert(play("ssss", on: start).row == 2)          // stops at the edge

Because moves are pure functions of the state, playing is composable: the state after a + b is the state after b starting from the state after a. That property is what lets a saved game be continued, and it is worth testing directly.

Q2: Save and load

Give Game Codable conformance and write save(_:to:) and load(from:) using JSON and a file URL. Test the round trip: loading what was saved gives an equal game.

Show solution
import Foundation

enum Tile: Character, Codable { case floor = ".", wall = "#", flower = "*" }

struct Game: Codable, Equatable {
    var tiles: [[Tile]]
    var row: Int
    var column: Int
    var flowersPicked: Int
}

func save(_ game: Game, to url: URL) throws {
    let encoder = JSONEncoder()
    encoder.outputFormatting = [.sortedKeys]
    try encoder.encode(game).write(to: url, options: .atomic)
}

func load(from url: URL) throws -> Game {
    try JSONDecoder().decode(Game.self, from: Data(contentsOf: url))
}

let game = Game(tiles: [[.wall, .flower], [.floor, .floor]], row: 1, column: 1, flowersPicked: 3)
let url = FileManager.default.temporaryDirectory.appendingPathComponent("lab51-save.json")
try save(game, to: url)
assert((try? load(from: url)) == game)
try FileManager.default.removeItem(at: url)

do {
    _ = try load(from: url)                    // the file is gone
    assert(false, "loading a missing file should throw")
} catch {
    // expected
}

.atomic writes to a temporary file and then renames it, so a crash in the middle of saving never leaves a half-written save file behind. .sortedKeys makes the JSON identical for identical games, which helps if saves are compared or kept in git.

Q3: The game view

Write a view that shows a Game with a tile renderer, moves the avatar with w, a, s, and d, and shows the number of flowers picked in a glass HUD. Keep all rules in the model.

Show solution
import SwiftUI

enum Tile: Character { case floor = ".", wall = "#", flower = "*" }
enum Move: Character { case up = "w", left = "a", down = "s", right = "d" }

struct Game {
    var tiles: [[Tile]]
    var row: Int
    var column: Int
    var flowersPicked = 0

    mutating func apply(_ move: Move) {
        let (dr, dc) = switch move {
        case .up: (-1, 0)
        case .down: (1, 0)
        case .left: (0, -1)
        case .right: (0, 1)
        }
        let (r, c) = (row + dr, column + dc)
        guard tiles.indices.contains(r), tiles[r].indices.contains(c), tiles[r][c] != .wall else { return }
        (row, column) = (r, c)
        if tiles[r][c] == .flower {
            tiles[r][c] = .floor
            flowersPicked += 1
        }
    }
}

struct GameView: View {
    @State private var game = Game(tiles: ["#######", "#..*..#", "#.###.#", "#*...*#", "#######"]
        .map { $0.map { Tile(rawValue: $0)! } }, row: 1, column: 1)
    @FocusState private var focused: Bool

    var body: some View {
        Canvas { context, size in
            let side = min(size.width / CGFloat(game.tiles[0].count), size.height / CGFloat(game.tiles.count))
            for (r, row) in game.tiles.enumerated() {
                for (c, tile) in row.enumerated() {
                    let color: Color = switch tile {
                    case .floor: Color(white: 0.2)
                    case .wall: .brown
                    case .flower: .pink
                    }
                    context.fill(Path(CGRect(x: CGFloat(c) * side, y: CGFloat(r) * side, width: side, height: side)),
                                 with: .color(color))
                }
            }
            let me = CGRect(x: CGFloat(game.column) * side, y: CGFloat(game.row) * side, width: side, height: side)
            context.fill(Path(ellipseIn: me.insetBy(dx: side * 0.2, dy: side * 0.2)), with: .color(.yellow))
        }
        .overlay(alignment: .top) {
            Label("\(game.flowersPicked) flowers", systemImage: "camera.macro")
                .padding(.horizontal, 14)
                .padding(.vertical, 8)
                .glassEffect(.regular, in: .capsule)
                .padding()
        }
        .focusable()
        .focused($focused)
        .onAppear { focused = true }
        .onKeyPress(characters: .letters) { press in
            guard let key = press.characters.first, let move = Move(rawValue: key) else { return .ignored }
            game.apply(move)
            return .handled
        }
        .frame(minWidth: 420, minHeight: 320)
    }
}

The view translates key presses into Moves and draws whatever the model says. It could be replaced by a terminal renderer, or by the replay function of Q1, without changing a line of the rules.

Q4 (optional): Undo

Add undo to the game: keep a history of states, and let u restore the previous one. Because Game is a value, the history is just an array (Lesson 33 explains why this is cheap).

Show solution
enum Move: Character { case up = "w", left = "a", down = "s", right = "d" }

struct Game: Equatable {
    var row = 0
    var column = 0
    mutating func apply(_ move: Move) {
        switch move {
        case .up: row -= 1
        case .down: row += 1
        case .left: column -= 1
        case .right: column += 1
        }
    }
}

struct Session {
    private(set) var game = Game()
    private var history: [Game] = []

    mutating func press(_ key: Character) {
        if key == "u" {
            if let previous = history.popLast() { game = previous }
        } else if let move = Move(rawValue: key) {
            history.append(game)
            game.apply(move)
        }
    }
}

var session = Session()
for key in "ddsuu" { session.press(key) }
assert(session.game == Game(row: 0, column: 1))
for key in "uuu" { session.press(key) }
assert(session.game == Game())                 // extra undos do nothing

Each state in the history is a complete, independent value. For a grid of tiles, copy-on-write shares the tile arrays between states until a move changes a tile, so storing every state costs far less than it looks.

What’s next

Next lesson: designing Project 10 itself, how to generate a world from a seed, and how to organize a program too big to hold in your head.