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
- Documentation
- onKeyPress(_:action:) · FocusState · Codable · JSONEncoder · FileManager
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)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.
position += key == "d" ? 1 : -1}let keys = "ddad"var position = 0for key in keys {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)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 edgeBecause 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 nothingEach 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.