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

Build Your Own World

The capstone: generate worlds of rooms and hallways from a seed, connect them with a minimum spanning tree, play them with the keyboard, drive the game from input strings, save and load with Codable, and make the SwiftUI app your own.

This is CS61B’s last project, Build Your Own World, in Swift. You will write a program that turns a number into a world of rooms and hallways, lets a player explore it, and saves the game to come back to later. Unlike the earlier projects, it has no single right answer: two correct generators make completely different worlds. What the tests check are the properties every good world has.

It draws on most of the course: seeded randomness (Lesson 53), minimum spanning trees and disjoint sets (Lessons 46 and 35), breadth-first search (Lesson 43), a game model separate from its interface (Lesson 52), Codable and files (Lesson 52), and planning a program too big to write at once (Lessons 51 and 53).

What you will build

Here is a world your generator might make for seed 61, at 40 by 18 tiles:

             #######
 #####       #.....# #####
 #...# #######.....# #...#####
 #...###.....#.....###...#...#
 #...........###.##..........#     #####
 #...###.....# #.#...#...#...#######...#
 ##.######.#####.#...#...###.##........#
 #.....###.##...........###...#...##...#
 #.....#....#....#...#### #...#...######
 #.....#....#....##.##    #.......###
 ###.###............#     #...#.....#
   #.# #....#....####    ###.##.....#
   #.####.###....#       #....#.....#
   #.##.....##############....#.....#
   #..........................#.....#
   ####.....##############....#######
      #.....#            #....#
      #######            ######

Floors are ., walls #, and the spaces are nothing. The rooms are joined by hallways one tile wide, every floor can be reached from every other, and walls close everything in. Your worlds will look different, and that is fine.

Getting started

Work in the byow folder of the swift-projects repository:

cd swift-projects/byow
swift test
File What it is
SplitMix64.swift Provided: the seeded generator from Lesson 53. Do not change it.
World.swift Provided: Tile, Position, and World, a grid of tiles.
SaveStore.swift Provided: the SaveStore protocol and MemoryStore, for tests.
WorldGenerator.swift Task 1: yours.
Game.swift Task 2: yours. Move is provided.
Interaction.swift Task 3: yours.
FileStore.swift Task 4: yours.
BYOWApp Provided: the SwiftUI app. Task 6 makes it yours.

Rows count from 0 at the top, columns from 0 at the left, and world[row, column] reads or writes a tile. World(rows:) builds a small world from text, which makes tests easy to write.

Task 1: Generating worlds

Write WorldGenerator.generate(seed:width:height:). Its documentation comment lists the requirements, and the provided problem(in:) function in the tests checks them:

  • The world has the requested size, at least 20 by 15.
  • The same seed and size always give the same world, and different seeds give different worlds.
  • Every floor tile can reach every other one through floor tiles, moving up, down, left, or right.
  • No floor tile is on the edge, and every tile around a floor tile, diagonals included, is a floor or a wall. Every wall is next to a floor.
  • At least a fifth of the tiles are floor.

Lesson 53 describes one approach: place random rooms that do not overlap, connect them along a minimum spanning tree of their centers with L-shaped hallways, add a few extra hallways for loops, and turn every nothing next to a floor into a wall. You may use its code as a start, or do something else entirely: caves, mazes, or round rooms. Whatever you do, keep in mind:

  • One generator. Create a SplitMix64 from the seed, and pass it as inout to every function that makes a random choice. One call without using: breaks repeatability.
  • Fixed order. Never make random choices while iterating over a Set or Dictionary, whose order changes between runs.
  • Enough floor. Small worlds fill up quickly, and some seeds leave too little room. One fix: keep placing rooms until they cover a certain fraction of the map, with a limit on attempts.

The provided tests check 50 seeds at the default size of 60 by 30. The hidden tests check hundreds of seeds at several sizes, including the smallest, 20 by 15, and long, thin worlds such as 100 by 20. Check many seeds in your own tests (Task 5).

Task 2: Moving

Write Game.init(world:seed:), which places the avatar on the first floor tile in reading order (top row first, then left to right), and apply(_:), which moves the avatar one tile unless the tile it would move to is not a floor. steps counts the moves that actually moved the avatar.

Game is a value with no idea of keys or screens: Lesson 52’s pure model. The world never changes during a game.

Task 3: Input strings

Write interact(withInput:store:), which plays a game from a string of keys, exactly as if they were typed. Its documentation comment is the specification. In short:

Input Meaning
n123s a new game in the world for seed 123
l load the saved game
w a s d move up, left, down, right
:q save and quit: the rest of the input is ignored

Keys are case-insensitive, and keys that mean nothing at that point are ignored. The s that ends a seed starts the game, and every later s is a move down. So n123sddss:q generates the world, moves right twice and down twice, and saves; then lwa loads it and moves up and left.

This function is what makes the game testable. A test is a string and an expected result, with no window and no keyboard, and the most important property is that splitting a string anywhere with a save and a load changes nothing:

interact("n123sddss:q") then interact("lwa")   ≡   interact("n123sddsswa")

Keep a small state while reading the keys: no game yet, reading a seed, or playing. The hidden tests include seeds with many digits, keys before a game starts, and : followed by something other than q.

Task 4: Saving to a file

Write FileStore.save(_:) and load(). save encodes the game as JSON with JSONEncoder and writes it to url, creating the folder first if needed (FileManager.createDirectory(at:withIntermediateDirectories:)). load returns nil if the file does not exist, and otherwise decodes it. Game, World, Tile, and Position are already Codable.

Saving the whole game, world included, is simple and makes loading instant. The other choice, saving just the seed and the keys and replaying them on load, makes files tiny. Both are fine here.

Task 5: Your own tests

Write tests in MyTests.swift. At least:

  • the world properties for a thousand seeds, at the smallest size and a large one;
  • a random string of moves, split at a random point with :q and l, gives the same game as the whole string (Task 3’s property);
  • a save and load through a FileStore in a temporary folder.

When a world fails, print the seed and the world: that one seed reproduces the bug.

Task 6: Make it yours

Run the app with swift run -c release BYOWApp. It has a menu to start a world from a seed or load a saved game, draws the world with a Canvas, moves the avatar with the keys, and shows a HUD with Liquid Glass: the tile under the pointer, the seed, and the number of steps. :q or the button saves and returns to the menu.

CS61B asks for ambition features that make the game your own. Add at least two; keep each one’s rules in BYOWCore, with tests, and only the drawing in the app. Some ideas:

  • Line of sight: show only the tiles within a few steps of the avatar, or the ones it has seen, like a torch in the dark.
  • Things to find: place items or a goal with the same seeded generator, and end the game when the avatar reaches them. Add a new Tile case.
  • Paths: press a key to show the shortest path from the avatar to the tile under the pointer, with BFS (Lesson 43) or A* (Lesson 45).
  • Replay: save the keys pressed, and animate the whole game back from the start with a task loop.
  • Variety: rooms of different shapes, doors, several themes chosen by the seed, or animated tiles with TimelineView.
  • Arrow keys, a seed shown in the window title, or a menu bar command to save, with .commands.