Designing a world
Planning a program too big to hold in your head, through Project 10: pseudorandom generation from a seed, rooms and hallways, guaranteeing connectivity with graph algorithms, walls from floors, and a module design with testable properties.
- CS61B
- Software Engineering II · BYOW Warmup · Textbook Ch. 28
- Swift book
- Functions
- Documentation
- RandomNumberGenerator
Project 10, Build Your Own World, asks for a program that generates a random world of rooms and hallways from a number, lets a player explore it, and saves and loads games. CS61B spends a lecture on how to start such a project, and so does this lesson. It works through the hardest part, generating a good world, and uses it to practice Lesson 51’s ideas: deciding modules and interfaces before writing code.
Randomness you can repeat
The world must be random, so that each seed gives a different, interesting world,
and repeatable, so that the same seed always gives the same world (Lesson 52’s
replay requirement). Both come from a pseudorandom number generator: a
deterministic function that turns a seed into a long sequence of numbers that look
random. Swift’s SystemRandomNumberGenerator is not seedable, so the project uses its
own, conforming to RandomNumberGenerator, which every standard random API accepts:
struct SplitMix64: RandomNumberGenerator {
private var state: UInt64
init(seed: UInt64) {
state = seed
}
mutating func next() -> UInt64 {
state &+= 0x9E3779B97F4A7C15
var z = state
z = (z ^ (z >> 30)) &* 0xBF58476D1CE4E5B9
z = (z ^ (z >> 27)) &* 0x94D049BB133111EB
return z ^ (z >> 31)
}
}
var a = SplitMix64(seed: 42)
var b = SplitMix64(seed: 42)
let first = (0..<5).map { _ in Int.random(in: 1...6, using: &a) }
let second = (0..<5).map { _ in Int.random(in: 1...6, using: &b) }
print(first == second, [1, 2, 3, 4].shuffled(using: &a).count) // true 4
This is the SplitMix64 algorithm, which Lesson 23 used for property tests. Its
overflow operators (&+=, &*) wrap around by design. Two rules keep a world
repeatable:
- Every random choice uses the one seeded generator, passed along as
inout. A single call toInt.random(in:)withoutusing:makes worlds differ between runs. - The generator is used in the same order every time. Iterating over a
SetorDictionaryto make random choices breaks this, since their order changes between runs (Lesson 49). Sort first.
Rooms and hallways
A classic approach, and the one CS61B suggests, has three steps:
- Place rooms. Try random rectangles; keep each one that does not overlap (or touch) a room already placed; stop after enough rooms or attempts.
- Connect them. Join rooms with hallways, one tile wide, bending at most once (an L shape), so that every room can be reached from every other.
- Add walls. Every empty tile next to a floor tile becomes a wall.
Step 2 is where the algorithms of this course pay off. Connecting each room to the next one in the order they were placed works, but makes long winding paths. Better: treat rooms as vertices, distances between their centers as edge weights, and connect them along a minimum spanning tree (Lesson 46), which connects everything with the least total hallway. A few extra random hallways then add loops, so the world is not a tree.
struct Room {
let x: Int, y: Int, width: Int, height: Int
var center: (x: Int, y: Int) { (x + width / 2, y + height / 2) }
func overlaps(_ other: Room) -> Bool {
x <= other.x + other.width && other.x <= x + width &&
y <= other.y + other.height && other.y <= y + height
}
}
/// Indices of room pairs to connect: a minimum spanning tree by Kruskal’s algorithm.
func hallwayPairs(_ rooms: [Room]) -> [(Int, Int)] {
var pairs: [(Int, Int, Int)] = []
for i in rooms.indices {
for j in rooms.indices where i < j {
let d = abs(rooms[i].center.x - rooms[j].center.x) + abs(rooms[i].center.y - rooms[j].center.y)
pairs.append((i, j, d))
}
}
var parent = Array(rooms.indices)
func find(_ p: Int) -> Int {
var p = p
while parent[p] != p { p = parent[p] }
return p
}
var result: [(Int, Int)] = []
for (i, j, _) in pairs.sorted(by: { ($0.2, $0.0, $0.1) < ($1.2, $1.0, $1.1) }) {
let (a, b) = (find(i), find(j))
if a != b {
parent[a] = b
result.append((i, j))
}
}
return result
}
let rooms = [Room(x: 1, y: 1, width: 4, height: 3), Room(x: 10, y: 2, width: 3, height: 3),
Room(x: 2, y: 9, width: 5, height: 2), Room(x: 12, y: 10, width: 3, height: 4)]
print(hallwayPairs(rooms).count, rooms[0].overlaps(rooms[1])) // 3 false
Sorting by distance and then by the room indices makes the tie-breaking rule explicit.
Swift’s sort is stable, so equal distances would keep the order in which the pairs
were listed anyway; spelling out the rule means the result does not depend on how the
list was built, which matters when it is built from a Set or Dictionary.
What would Swift print?
let a = (x: 0, y: 0, width: 4, height: 4)
let b = (x: 4, y: 2, width: 3, height: 3)
let c = (x: 6, y: 6, width: 2, height: 2)
func overlaps(_ p: (x: Int, y: Int, width: Int, height: Int), _ q: (x: Int, y: Int, width: Int, height: Int)) -> Bool {
p.x <= q.x + q.width && q.x <= p.x + p.width && p.y <= q.y + q.height && q.y <= p.y + p.height
}
print(overlaps(a, b), overlaps(a, c), overlaps(b, c))Show answer and explanation
Answertrue false false
The test uses <=, so rooms that merely touch count as overlapping: a starts at
x = 0 with width 4, b at x = 4, and they touch. That keeps a gap for walls between
rooms. b covers rows 2 to 5 and c starts at row 6, so there is room between them, and
a and c are even farther apart.
Guaranteeing a good world
A generator is hard to test by looking at its output, since every seed gives a different world. Test properties that every world must have (Lesson 23):
- The same seed gives the same world, and different seeds usually different worlds.
- Every floor tile is reachable from every other: a BFS from one floor tile (Lesson 43) visits them all.
- Every floor tile is enclosed: no floor tile touches the edge of the map or an empty tile.
- The world has at least some minimum number of rooms, and a reasonable fraction of floor.
Running these checks over a thousand seeds finds the rare seeds that break a generator, which no amount of looking at screenshots will.
Designing the modules
Before code, decide what each part knows. A design for Project 10:
| Module | Knows | Does not know |
|---|---|---|
World |
the grid of tiles, what a tile is | how it was made, how it is drawn |
WorldGenerator |
rooms, hallways, the seed | the player, the screen, saving |
Game |
the world, the avatar, the rules for moving | keys, the screen, files |
InputParser |
the input string format, like n123sddssaq |
how moves are applied |
SaveFile |
the file format | what the game state means |
| the SwiftUI app | drawing, keys, the HUD | the rules of the game |
Each row can be written and tested alone. World is a plain value; the generator is a
function from a seed to a World; the game is Lesson 52’s pure model. The app is thin.
When the format of a save changes, only SaveFile changes; when rooms become caves,
only WorldGenerator does.
Put the lines in order
Put the lines in order so the program prints true.
let valid = values.allSatisfy { (0..<10).contains($0) }var first = SystemRandomNumberGenerator()print(valid)let values = (0..<3).map { _ in Int.random(in: 0..<10, using: &first) }
Show the correct program
var first = SystemRandomNumberGenerator()
let values = (0..<3).map { _ in Int.random(in: 0..<10, using: &first) }
let valid = values.allSatisfy { (0..<10).contains($0) }
print(valid)Lab 52: Designing a world
These problems build a small generator that Project 10 can grow from. Each uses the
SplitMix64 generator from the lesson.
Q0: What would Swift print?
What would Swift print?
struct Counter: RandomNumberGenerator {
var n: UInt64 = 0
mutating func next() -> UInt64 {
n += 1
return n
}
}
var g = Counter()
_ = Int.random(in: 0..<100, using: &g)
_ = Bool.random(using: &g)
print(g.n >= 2)Show answer and explanation
Answertrue
Every random function that takes using: asks the generator for at least one number.
So consuming the generator in a different order, or skipping a call, changes every
choice after it, which is why the order of random calls must be fixed.
Q1: Placing rooms
Write placeRooms(width:height:attempts:using:), which tries attempts random
rooms, 3 to 8 tiles in each dimension, inside a map with a margin of one tile, and
keeps those that do not overlap a kept room. Check that the same seed gives the same
rooms.
Show solution
struct SplitMix64: RandomNumberGenerator {
private var state: UInt64
init(seed: UInt64) { state = seed }
mutating func next() -> UInt64 {
state &+= 0x9E3779B97F4A7C15
var z = state
z = (z ^ (z >> 30)) &* 0xBF58476D1CE4E5B9
z = (z ^ (z >> 27)) &* 0x94D049BB133111EB
return z ^ (z >> 31)
}
}
struct Room: Equatable {
let x: Int, y: Int, width: Int, height: Int
func overlaps(_ o: Room) -> Bool {
x <= o.x + o.width && o.x <= x + width && y <= o.y + o.height && o.y <= y + height
}
}
func placeRooms(width: Int, height: Int, attempts: Int, using random: inout some RandomNumberGenerator) -> [Room] {
var rooms: [Room] = []
for _ in 0..<attempts {
let w = Int.random(in: 3...8, using: &random)
let h = Int.random(in: 3...8, using: &random)
let x = Int.random(in: 1...(width - w - 2), using: &random)
let y = Int.random(in: 1...(height - h - 2), using: &random)
let room = Room(x: x, y: y, width: w, height: h)
if !rooms.contains(where: room.overlaps) {
rooms.append(room)
}
}
return rooms
}
var g1 = SplitMix64(seed: 7), g2 = SplitMix64(seed: 7), g3 = SplitMix64(seed: 8)
let a = placeRooms(width: 60, height: 30, attempts: 40, using: &g1)
let b = placeRooms(width: 60, height: 30, attempts: 40, using: &g2)
let c = placeRooms(width: 60, height: 30, attempts: 40, using: &g3)
assert(a == b && a != c && a.count >= 4)
for (i, r) in a.enumerated() {
assert(r.x >= 1 && r.y >= 1 && r.x + r.width <= 58 && r.y + r.height <= 28)
for s in a[(i + 1)...] { assert(!r.overlaps(s)) }
}The random calls happen in a fixed order in every attempt, whether or not the room is kept, so the sequence of rooms depends only on the seed.
Q2: Carving and connecting
Carve the rooms and L-shaped hallways into a grid of tiles (.floor, .wall,
.nothing), connecting room centers along the pairs from the lesson’s
hallwayPairs, then turn every nothing tile next to a floor into a wall. Check that
all floor tiles are connected, with BFS, and that no floor touches nothing.
Show solution
enum Tile: Character { case nothing = " ", floor = ".", wall = "#" }
struct Room {
let x: Int, y: Int, width: Int, height: Int
var center: (x: Int, y: Int) { (x + width / 2, y + height / 2) }
}
func carve(_ rooms: [Room], pairs: [(Int, Int)], width: Int, height: Int) -> [[Tile]] {
var tiles = Array(repeating: Array(repeating: Tile.nothing, count: width), count: height)
for r in rooms {
for y in r.y..<(r.y + r.height) { for x in r.x..<(r.x + r.width) { tiles[y][x] = .floor } }
}
for (i, j) in pairs {
let (a, b) = (rooms[i].center, rooms[j].center)
for x in min(a.x, b.x)...max(a.x, b.x) { tiles[a.y][x] = .floor } // horizontal first
for y in min(a.y, b.y)...max(a.y, b.y) { tiles[y][b.x] = .floor } // then vertical
}
let floors = tiles
for y in 0..<height {
for x in 0..<width where floors[y][x] == .nothing {
let nearFloor = (-1...1).contains { dy in (-1...1).contains { dx in
let (ny, nx) = (y + dy, x + dx)
return floors.indices.contains(ny) && floors[ny].indices.contains(nx) && floors[ny][nx] == .floor
} }
if nearFloor { tiles[y][x] = .wall }
}
}
return tiles
}
let rooms = [Room(x: 1, y: 1, width: 4, height: 3), Room(x: 10, y: 2, width: 3, height: 3),
Room(x: 2, y: 9, width: 5, height: 2)]
let world = carve(rooms, pairs: [(0, 1), (0, 2)], width: 16, height: 13)
var floorTiles: [(Int, Int)] = []
for y in world.indices { for x in world[y].indices where world[y][x] == .floor { floorTiles.append((y, x)) } }
var seen: Set<Int> = [floorTiles[0].0 * 100 + floorTiles[0].1]
var queue = [floorTiles[0]]
var head = 0
while head < queue.count {
let (y, x) = queue[head]; head += 1
for (dy, dx) in [(-1, 0), (1, 0), (0, -1), (0, 1)] {
let (ny, nx) = (y + dy, x + dx)
if world[ny][nx] == .floor, seen.insert(ny * 100 + nx).inserted { queue.append((ny, nx)) }
}
}
assert(seen.count == floorTiles.count)
for (y, x) in floorTiles {
for (dy, dx) in [(-1, 0), (1, 0), (0, -1), (0, 1)] { assert(world[y + dy][x + dx] != .nothing) }
}
print(world.map { String($0.map(\.rawValue)) }.joined(separator: "\n"))Walls are computed from a copy of the floor layout, floors: deciding each tile
from the grid while changing it would let new walls affect their neighbors’ decisions.
Diagonal neighbors count, so corners are closed too. The BFS never indexes outside the
grid because every floor is surrounded by walls, which is the property the last check
confirms.
Q3: A thousand seeds
Combine Q1, the lesson’s hallwayPairs, and Q2 into generate(seed:), and check the
connectivity and enclosure properties for seeds 0 to 999.
Show solution
Using the functions above, the test is a loop:
for seed in 0..<1_000 as Range<UInt64> {
var random = SplitMix64(seed: seed)
let rooms = placeRooms(width: 60, height: 30, attempts: 40, using: &random)
let world = carve(rooms, pairs: hallwayPairs(rooms), width: 60, height: 30)
assert(isConnected(world), "seed \(seed)")
assert(isEnclosed(world), "seed \(seed)")
}isConnected and isEnclosed are the two checks from Q2 made into functions.
Including the seed in the failure message is what makes a failure reproducible: that
one seed is the whole bug report. Project 10’s tests work the same way.
What’s next
With the world designed, the rest of Unit 7 turns to sorting, starting with the basic sorts.