Preface
This book starts where lux leaves you. You can write a program in lux, it runs, and it does what you meant. The next step is reading programs written in the languages lux was built to lead to: real programs, written by someone else, much bigger than anything you’ve written yourself.
That sounds harder than it is. A real program is made of the same pieces as yours. It has data, functions that change the data, a loop, and a way of talking to the person using it. What’s different is the spelling, the size, and a few ideas lux never needed. If you know what a program does before you open it, you can find those pieces in the code, and once you’ve found them, you understand the program, even if there are lines in it you couldn’t write yourself.
The example
The book follows one game. Vier is four in a row: two players take turns dropping discs into a board seven columns wide and six rows tall, and the first to line up four across, down or diagonally wins.
Chapter 1 writes Vier in lux, and that program is your map for the rest of the book. The chapters after it read three real versions of the same game: vier-cli, written in Go, which plays in a terminal; vier-desktop, written in Rust, which plays in a window on a computer; and vier-ios, written in Swift, which plays on an iPhone and an Apple Watch. All three play against the computer as well as against a friend, and all three are programs people use. In each one, you find the pieces you wrote in chapter 1, learn the few new ideas that program depends on, and build it and run it yourself.
Between the terminal and the window, chapter 4 goes back to lux for the biggest change in the book. Your lux game and vier-cli run their own loop: ask for a move, make it, go around again. A program with a window doesn’t. Another program runs the loop and calls yours, and that changes how a program waits and when it draws. Chapter 4 shows that change in a program you already know, so that when you meet it in Rust and Swift, you already know how it works.
What you need
You need to know lux: structs, enums, match, Option, arrays and functions.
If you need a refresher, run lux learn. You don’t need to know Go, Rust or
Swift. The book explains what you need from each when you get there.
To build the apps you need lux from anderix.com/lux, Go from go.dev, and Rust from rustup.rs. The iPhone and Watch app needs a Mac with Xcode. Without one, you can still read that part; you just can’t run the app.
The code
Chapter 1’s program is in the book’s repository,
under examples/ch01-lux:
cd examples/ch01-lux
lux run vier.lux
The three apps each have their own repository, and each part of the book says where to find it.
1. Four in a Row in Lux
Before this program can become anything else, it has to work. This chapter writes Vier in lux: two players at one keyboard, taking turns, until one of them lines up four or the board fills. It is about two hundred lines, it uses nothing lux doesn’t already give you, and every chapter after this one starts from it.
Here is the start of a game. Red drops a disc into column 4, Yellow drops one on top of it, and Red plays column 5:
$ lux run vier.lux
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
1 2 3 4 5 6 7
Red, pick a column (1-7):
4
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . R . . .
1 2 3 4 5 6 7
Yellow, pick a column (1-7):
4
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . Y . . .
. . . R . . .
1 2 3 4 5 6 7
Red, pick a column (1-7):
5
The full program is examples/ch01-lux/vier.lux. This chapter goes through it
in the order you’d write it: first the data, then the rules, then the part that
talks to the players.
1.1 What a board is
A game is mostly a board, so the first decision is what a board holds. Each of its forty-two cells is either empty or holds one player’s disc. Players are an enum with two cases:
enum Player {
red
yellow
}
and a cell is an Option<Player>: some(Player.red), some(Player.yellow), or
none. That last one is the empty cell. You could add a third case to Player
called nobody, and some programs do, but then every function that takes a
Player has to decide what to do with a player who isn’t one. opponent would
need an answer for nobody, and so would name. With Option, the type says
which values can be empty, and match makes you handle the empty case only in
the places where it can actually happen.
The board is a struct holding rows of cells:
struct Board {
cells: [[Option<Player>]]
}
Row 0 is the bottom of the board. A dropped disc lands in the lowest empty row,
so counting from the bottom makes “the lowest empty row” the first none you
find going up. Printing is the only thing that wants the top row first, and it
can count down.
The board’s size shows up in a lot of places, so it gets a name. lux has no constants, but a function that returns a number does the same job:
func columns() -> int {
return 7
}
func rows() -> int {
return 6
}
An empty board is six rows of seven nones, built with two loops:
func emptyBoard() -> Board {
var cells: [[Option<Player>]]
for row in 0..rows() {
var line: [Option<Player>]
for column in 0..columns() {
line += none
}
cells += line
}
return Board(cells: cells)
}
1.2 Dropping a disc
A move is a column. Before anything else, the program has to know whether a column can take another disc. It can if the column exists and its top cell is still empty:
func at(board: Board, column: int, row: int) -> Option<Player> {
return board.cells[row][column]
}
func canDrop(board: Board, column: int) -> bool {
if column < 0 || column >= columns() {
return false
}
return at(board, column, rows() - 1) == none
}
The range check comes first because at with a column of 9 would stop the
program with an index error. canDrop is the one place that decides what a
legal move is, so the rest of the program can ask it instead of checking indexes
itself.
The disc lands in the lowest empty cell of the column:
func landingRow(board: Board, column: int) -> int {
var row = 0
while at(board, column, row) != none {
row += 1
}
return row
}
That loop would run off the top of a full column, which is why nothing calls it
without asking canDrop first.
Then the move itself:
func dropped(board: Board, player: Player, column: int) -> Board {
var next = board
next.cells[landingRow(board, column)][column] = some(player)
return next
}
dropped doesn’t change the board it was given. It copies it, changes the copy,
and hands the copy back, because in lux var next = board makes a copy. The
caller decides what to do with the new board, and in this program the caller
keeps it: board = dropped(board, turn, column). If you forget the board =,
nothing happens to the game, and lux trace will show you a board that never
changes. Keep that copy in mind. It comes back in the next chapter, when the
program moves to a language that copies some things and not others.
1.3 Four in a line
A line is four cells in a row: across, up, or along either diagonal. There are sixty-nine of them on a seven-by-six board, and the program could look for them fresh after every move, but the lines are the same in every game. So the program works them out once, as positions, and checks those.
struct Position {
column: int
row: int
}
Every line has a starting cell and a direction. The directions are steps: one column right, one row up, one of each, or one column right and one row down. A line fits on the board if its fourth cell, three steps from the start, is still inside:
func inside(column: int, row: int) -> bool {
return column >= 0 && column < columns() && row >= 0 && row < rows()
}
func winningLines() -> [[Position]] {
let steps = [[1, 0], [0, 1], [1, 1], [1, -1]]
var all: [[Position]]
for column in 0..columns() {
for row in 0..rows() {
for step in steps {
if inside(column + step[0] * 3, row + step[1] * 3) {
var line: [Position]
for i in 0..4 {
line += Position(column: column + step[0] * i, row: row + step[1] * i)
}
all += line
}
}
}
}
return all
}
There are only four directions, not eight, because a line from left to right is the same line as the one from right to left. Counting each direction once means each line is found once.
A line belongs to a player if all four of its cells hold that player’s disc.
owner reads the first cell and then checks that the other three match it:
func owner(board: Board, line: [Position]) -> Option<Player> {
let first = at(board, line[0].column, line[0].row)
for cell in line {
if at(board, cell.column, cell.row) != first {
return none
}
}
return first
}
If the first cell is empty, first is none, and the line comes back none
whether the other three are empty or not. That’s the right answer: four empty
cells don’t belong to anyone.
winner asks every line:
func winner(board: Board, candidates: [[Position]]) -> Option<Player> {
for line in candidates {
let found = owner(board, line)
if found != none {
return found
}
}
return none
}
The parameter is called candidates rather than lines because a lux name can
belong to a function or to a variable, but not to both at once, and an earlier
draft of this program had a function called lines. The error lux gives for
that, “lines is already the name of a function”, is a fair complaint: in a
long function you’d have to stop and work out which lines a line meant.
A draw is a full board with no winner. The board is full when no column can take another disc:
func isFull(board: Board) -> bool {
for column in 0..columns() {
if canDrop(board, column) {
return false
}
}
return true
}
1.4 Talking to the players
The rest of the program is the conversation. Each player needs a name and each cell a mark:
func name(player: Player) -> string {
return match player {
red => "Red"
yellow => "Yellow"
}
}
func mark(cell: Option<Player>) -> string {
return match cell {
some(let player) => match player {
red => "R"
yellow => "Y"
}
none => "."
}
}
mark takes the cell apart twice: once to see whether there is a disc, and once
to see whose it is. A match arm in lux holds one expression, and another
match counts as one, so the nested form is how you say “look inside the
some”.
show prints the rows from the top down and the column numbers underneath, so
the players can see which number goes with which column:
func show(board: Board) {
var row = rows() - 1
while row >= 0 {
var text = ""
for column in 0..columns() {
text += " " + mark(at(board, column, row))
}
print(text)
row -= 1
}
print(" 1 2 3 4 5 6 7")
}
Reading a move is where the program meets the outside world, and the outside
world doesn’t always cooperate. A player might type 9, or four, or nothing
at all. The input might also run out, which happens when you pipe a file
of moves into the program instead of typing them. input turns the end of input
into an empty string, so a program reading moves with input would ask for a
column forever once the moves ran out. readLine keeps the difference: it
returns some(line) while there are lines and none when there aren’t.
func columnFrom(line: Option<string>) -> int {
return match line {
some(let text) => match parseInt(text) {
some(let n) => n - 1
none => -1
}
none => -1
}
}
columnFrom turns what the player typed into a column index. Players count
columns from 1, and the board counts them from 0, so it subtracts one. Anything
that isn’t a number becomes -1, which canDrop rejects like any other column
that isn’t on the board.
chosenColumn asks until it gets a column it can use, or until the input runs
out:
func chosenColumn(board: Board, player: Player) -> Option<int> {
while true {
print(name(player) + ", pick a column (1-7):")
let line = readLine()
if line == none {
return none
}
let column = columnFrom(line)
if canDrop(board, column) {
return some(column)
}
print("That column is not open.")
}
return none
}
It returns Option<int> because “the player picked column 3” and “there is no
player any more” are different answers, and the main loop needs to tell them
apart. The return none after the loop never runs. It’s there because lux
checks that every path through a function returns a value, and it doesn’t treat
while true as a loop that never ends.
1.5 The game
The main program holds the state of the game in three variables, the board, whose turn it is, and whether the game is over, and loops until it is:
let allLines = winningLines()
var board = emptyBoard()
var turn = Player.red
var done = false
while !done {
show(board)
let choice = chosenColumn(board, turn)
if choice == none {
done = true
} else {
board = match choice {
some(let column) => dropped(board, turn, column)
none => board
}
let result = winner(board, allLines)
if result != none || isFull(board) {
show(board)
print(match result {
some(let player) => name(player) + " wins!"
none => "A draw."
})
done = true
}
turn = opponent(turn)
}
}
opponent is the last piece, a match that swaps the two players.
The match choice has a none arm that can’t happen, since the if above it
already handled none. A match has to cover every case, even one the code
around it has ruled out. Chapter 2 will look at what other languages do instead.
When Red completes a line of four, the game ends:
. . . . . . .
. . . . . . .
. . . R . . .
. . . R Y . .
. . . R Y . .
. . . R Y . .
1 2 3 4 5 6 7
Red wins!
1.6 The map
The game works. Two people at one keyboard can play it to the end, and it handles every column they can type. It’s also small enough that you can hold all of it in your head, and that’s what makes it useful for the rest of this book. Every version of Vier has the same pieces, and you’ve now written each of them:
- The board. It holds a disc or nothing in each cell, and it can say which.
- The rules. They decide which moves are allowed, where a disc lands, and when the game is won or drawn.
- The turn. It says whose move it is, and it passes to the other player after each one.
- The loop. It asks for a move, makes it, checks for the end, and goes around again.
- The display. It turns the board into something a person can see.
The real apps you’ll read have more than this. They have a computer to play against, they remember a game you haven’t finished, and two of them draw the board as a picture, in a window or on a phone, instead of as text. But each of them has these five pieces at its center, under different names and in a different language. When you open one, the first job is to find them.
You’ll find that the first two pieces hardly change from one app to the next. A board is cells that hold a disc or nothing, and the rules are the same rules in every language. The last three, the turn, the loop and the display, are where the apps differ, and why they differ is what this book is about.
Before you open any of them, try one more command:
lux convert go vier.lux > vier.go
lux can translate this program into Go, and into Rust and Swift too, and the translation runs. Chapter 2 starts by reading it.
2. Into Go
The first real app in this book is written in Go. Before opening it, you can get a head start: lux will translate the game from chapter 1 into Go for you. Reading that translation is the easiest first look at Go there is, because you already know what every line of it does. You wrote it.
This chapter reads it. The point isn’t to learn Go line by line. It’s to see how much of Go you can already read, and to pick up a few rules for the parts that look new.
2.1 The translation
From the folder with vier.lux in it:
lux convert go vier.lux > vier.go
go mod init vier
go run .
The first line writes the Go version of the game into vier.go. The second sets
the folder up as a Go project, which Go calls a module and needs before it
will build anything. The third builds the program and runs it, and it’s the same
game:
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
1 2 3 4 5 6 7
Red, pick a column (1-7):
4
Open vier.go and look through it. It’s about three hundred lines, a hundred
more than the lux. Most of it will look familiar, and some of it won’t. Start
with the familiar part.
2.2 The same program
Here is landingRow in lux:
func landingRow(board: Board, column: int) -> int {
var row = 0
while at(board, column, row) != none {
row += 1
}
return row
}
and in Go:
func landingRow(board Board, column int) int {
row := 0
for at(copyBoard(board), column, row) != nil {
row += 1
}
return row
}
It’s the same function. It has the same name, takes the same two things, starts
at row 0, and counts up while the cell is taken. The differences are spelling.
Go writes the type after the name with no colon, column int rather than
column: int, and puts the type a function returns after the parentheses with
no arrow. row := 0 makes a new variable, like var row = 0. Go has no
while: it uses for for every loop, and a for with only a condition is a
while. And Go’s word for lux’s none is nil.
Ignore copyBoard for now; section 2.4 comes back to it.
Most of the program reads this way. Here is opponent:
func opponent(player Player) Player {
switch player.(type) {
case PlayerRed:
return (PlayerYellow{})
case PlayerYellow:
return (PlayerRed{})
}
panic("unreachable")
}
switch is Go’s match, and each case is an arm. Red becomes yellow and
yellow becomes red, as in chapter 1. The .(type) and the braces after
PlayerYellow are how this translation spells a lux enum, which section 2.3
covers, but you don’t need them to see what the function does.
The last line is new. A lux match that leaves out a case doesn’t run. A Go
switch that leaves one out is allowed, and the program carries on past it, so
the converter adds a line that stops the program if that ever happens. panic
is Go’s way of stopping a program with an error. You’ll see it after every
match the converter translates.
And the main loop:
func main() {
allLines := winningLines()
board := emptyBoard()
var turn Player = (PlayerRed{})
done := false
for !done {
show(board)
choice := chosenColumn(copyBoard(board), turn)
if choice == nil {
done = true
} else {
...
A lux program starts at its first line that isn’t a declaration. A Go program
starts at a function called main, so the converter moves your top-level lines
into one. Inside, it’s chapter 1’s loop: the same three variables, the same
show, the same question asked of the same player.
You don’t need to know Go to follow this. You need to know what the program does and then find it in the code, and you already know what this program does.
2.3 What Go builds differently
Two of lux’s ideas aren’t part of Go, so the converter builds them out of other parts of the language. You’ll meet both in Go programs, so it helps to know what they look like.
The first is the enum. Go has no type that is “one of these cases”, the way
Player is red or yellow. The converter makes one type for each case and a
shared name that covers them all. Go calls that shared name an interface: a
group of types that all have something in common, which here is the empty
isPlayer each case is given.
type Player interface{ isPlayer() }
type PlayerRed struct{}
func (PlayerRed) isPlayer() {}
type PlayerYellow struct{}
func (PlayerYellow) isPlayer() {}
You don’t need to know how this works to read it. When you see a group like this, read it as:
enum Player {
red
yellow
}
and read PlayerRed{} as Player.red. The switch player.(type) in
opponent is a type switch: it asks which type in the group a value is, and
that’s how this translation spells a match on an enum. Chapter 3 shows a
simpler way Go programmers usually write a list of cases like this one.
The second is Option. Go doesn’t have it. Instead, some Go values can be
nil, meaning “nothing here”, and the converter uses that where lux used
none. So an empty cell on the board is nil, and mark checks for it:
func mark(cell Player) string {
if playerOpt := cell; playerOpt != nil {
...
} else {
return "."
}
}
Read if x != nil as the some arm and the else as the none arm. What you
lose is the reminder. In lux, the type Option<Player> told you a cell might be
empty. Here the type says only Player, nothing tells you to check, and a Go
programmer has to remember.
For an Option<int>, the converter writes *int, with a star. That’s a
pointer to an int. A pointer doesn’t hold a value itself; it leads to one
that’s kept somewhere else, and chapter 3 shows what Go programmers usually
want that for. The converter wants something simpler: a pointer can be nil,
leading nowhere. So in converted code, read *int as “an int that might be
missing”, with nil as the missing case. When the converter needs to make one,
it calls ptr(column), short for pointer, which you can read as
some(column).
2.4 What lux brought with it
The top of vier.go holds functions that aren’t in your lux program at all:
luxCheck, luxIndex, luxEqual, copySlice, copyBoard, readLine and
parseInt. These are lux itself, written in Go. lux makes you some promises,
and when your program leaves lux, the converter brings code along to keep them.
luxIndex keeps the promise about indexes. Go stops a program on a bad index
too, but with a shorter message, so the converter sends every index through
luxIndex to keep lux’s explanation. That’s why at became:
func at(board Board, column int, row int) Player {
return luxIndex(luxIndex(board.cells, row), column)
}
Read luxIndex(xs, i) as xs[i], and this is board.cells[row][column].
copyBoard keeps the promise from chapter 1. In lux, passing a board to a
function hands over a copy, so nothing the function does can change your board.
Go copies some kinds of values and shares others, and a board built the way lux
builds one is a kind Go would share. So the converter copies the board itself,
every time it’s passed anywhere, to be sure. Read copyBoard(board) as board.
The rest work the same way. readLine and parseInt are the lux functions you
called, built from Go’s own, and luxEqual is lux’s ==. When you read
converted code, skip these and read the program underneath.
2.5 Reading Go you didn’t write
The translation has shown you most of what you need to read Go, and very little of it was a new idea. Most of it was new spelling for ideas you already had. Here are this chapter’s rules in one place:
| In Go | Read it as |
|---|---|
name type, as in column int | name: type |
func f(x int) int | func f(x: int) -> int |
x := 5 | var x = 5 |
for condition { … } | while condition { … } |
for { … } | while true { … } |
switch … { case …: } | match and its arms |
nil | none |
if x != nil { … } else { … } | the some and none arms |
*int, a pointer, in converted code | Option<int> |
switch x.(type), a type switch | match on an enum |
func main() { … } | the lines at the top level of a lux file |
panic("…") | the program stopping with an error |
A longer list of lux and Go side by side is Appendix B of Programming in Go, when you want it.
The translation is lux’s program in Go’s spelling. It does everything the way lux does it, and it brings lux’s helpers along to make sure. A Go programmer writing the same game would make different choices, because Go has its own ways of saying the same things. Chapter 3 opens a Go program written that way, vier-cli, and finds chapter 1’s game inside it.
3. vier-cli
vier-cli is the Go version of Vier, written by hand the way a Go programmer writes Go. It plays in a terminal against the computer or a friend, it remembers a game you haven’t finished, and it has tests that check it works. It’s about fifteen hundred lines counting its tests, and nine hundred without them, between four and five times the size of your lux game.
You won’t read all of them. This chapter gets the program running, finds the five pieces from chapter 1 inside it, and then follows one move from the moment you type it to the moment the computer answers. Along the way you’ll meet the few Go ideas the program is built on. By the end you’ll know how vier-cli works, even though you’ve skipped most of its lines.
3.1 Running it
Get the code and run it:
git clone https://github.com/anderix/vier-cli
cd vier-cli
go run .
git clone copies the program’s repository onto your computer, and go run .
builds it and starts it. You play Red against the computer, and it answers each
move. It plays some of its moves at random, so your game won’t match this one:
A new game against the easy computer.
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
1 2 3 4 5 6 7
Red> 4
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . R . . .
1 2 3 4 5 6 7
The computer plays 2.
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. Y . R . . .
1 2 3 4 5 6 7
Red> 9
There is no column 9. The columns are 1 to 7.
Red> hello
I don't know "hello". Type help for the commands.
Red>
Type help to see what else it understands: friend starts a game for two
players, easy, medium and hard change how well the computer plays, and
quit leaves. If you quit halfway through a game and start it again, it picks
up where you left off.
go build makes a program file you can run without Go, called vier-cli, and
go test runs the tests. Section 3.9 comes back to those.
3.2 Finding the pieces
Here are the files, with the tests left out:
board.go the board, the players, the rules
game.go one game: the board, whose turn it is, and how it ended
session.go the conversation: commands, the computer's turn, saving
engine.go how the computer picks a move
rng.go random numbers for the computer
memory.go the saved game and the choices you made, kept in a file
options.go options you can give when you start it, like --level hard
version.go the version number it prints
main.go where it starts
A Go program can be spread across as many files as the author likes, and every file in the folder is part of the same program. The files are there for you, the reader, so you can find things.
Now match them to the map from chapter 1:
| Piece | lux | vier-cli |
|---|---|---|
| The board | Board, Option<Player> cells | Board in board.go |
| The rules | canDrop, dropped, winner, isFull | CanDrop, Drop, Winner, Full in board.go |
| The turn | the turn variable | Turn in game.go |
| The loop | the while !done loop | Serve in session.go |
| The display | show | String in board.go |
Everything else is what vier-cli has that your game doesn’t: a computer opponent, saving, and options. The computer and saving each get a section later. You could skip all three and still understand the game.
3.3 The board
Open board.go. Near the top:
const (
Columns = 7
Rows = 6
)
Go has constants, so columns() and rows() become Columns and Rows.
type Player int
const (
Nobody Player = iota
Red
Yellow
)
This is the simpler way to write a list of cases that chapter 2 promised. Each
player is a number with a name: Nobody is 0, Red is 1 and Yellow is 2.
iota is Go’s way of counting them off, so you don’t have to write the numbers.
Read it as an enum with three cases.
Three, not two. vier-cli has a player called Nobody, and an empty cell holds
Nobody. Chapter 1 turned that idea down, because every function that takes a
Player would have to decide what to do with one who isn’t a player. Go makes a
different trade, because of an idea lux doesn’t have: every Go value starts out
as zero until you give it something else. Go calls that starting value the
type’s zero value. A number’s is 0, a string’s is empty, and a board’s has
every cell at 0, which is Nobody. So this is an empty board:
var board Board
What Go gives up is the reminder you had in lux, where the type
Option<Player> told you a cell could be empty. What it gets is a board that’s
ready to use the moment it exists.
The board itself:
type Board struct {
cells [Rows][Columns]Player
}
It’s the same struct as yours: rows of cells. The sizes in the brackets make it
an array of exactly six rows of seven, which is also why it behaves like a lux
board. Hand it to a function and the function gets a copy, so chapter 2’s
copyBoard isn’t needed here.
3.4 Methods
The rules are in board.go too, but they look a little different from functions:
func (b Board) CanDrop(column int) bool {
return column >= 0 && column < Columns && b.cells[Rows-1][column] == Nobody
}
This is a method: a function that belongs to a type. The board goes in the parentheses before the name instead of in the list after it, and Go calls it the method’s receiver. You call a method with the receiver first:
board.CanDrop(3)
Read that as canDrop(board, 3), and read the method as:
func canDrop(b: Board, column: int) -> bool
It’s the same function as yours, on one line instead of four. Most of the functions in vier-cli are methods, and the reading rule is always the same: the receiver, the value before the dot, is the first thing passed in.
Some names start with a capital letter, like CanDrop, and some don’t, like
at. A capitalized name is exported, which in a larger Go project means other
parts of the project can use it. In a program this size it doesn’t change
anything, and you can read past it.
3.5 Changing the original
Here is how a disc is dropped:
func (b *Board) Drop(column int, p Player) (int, error) {
if column < 0 || column >= Columns {
return 0, ErrNoSuchColumn
}
for row := range Rows {
if b.cells[row][column] == Nobody {
b.cells[row][column] = p
return row, nil
}
}
return 0, ErrColumnFull
}
There are two new things here. The first is the star in *Board, which makes
it a pointer to a board.
In lux, dropped couldn’t change your board, because it got a copy. So it
changed the copy and handed it back, and you kept it:
board = dropped(board, turn, column)
Go can do it that way too, but it has another option. A pointer doesn’t hold a board of its own. It leads to one that’s kept somewhere else: here, the board you called the method on. A method whose receiver is a pointer, which Go calls a pointer receiver, works on that board itself instead of a copy, and what it changes stays changed. So vier-cli drops a disc like this:
board.Drop(column, player)
and afterwards, board has the new disc in it. Same job, two ways of doing it.
When you’re reading Go, read a star in front of a type as “the original, not a
copy”. A method with a pointer receiver changes the value you call it on. A
method without one, like CanDrop, only looks at it.
That’s also the pointer you saw in chapter 2. A pointer leads to one value kept
somewhere else, and it can also be nil, leading nowhere. The converter used
that second part for “an int that might be missing”. vier-cli uses the first
part, to change the board in place.
3.6 Two answers at once
The second new thing in Drop is (int, error). A Go function can hand back
more than one value, and this one hands back two: the row the disc landed in,
and an error, which says what went wrong.
You’ve met this idea before, as Result. A lux function that might fail
returns ok(value) or err(problem). Go returns both every time, and one of
them means “nothing”:
| Go | lux |
|---|---|
return row, nil | return ok(row) |
return 0, ErrColumnFull | return err("column is full") |
When it works, the error is nil. When it fails, the row is 0, which means
nothing, and the error says why. The code that calls Drop checks the error
first:
if _, err := g.Board.Drop(column, g.Turn); err != nil {
return err
}
Read if err != nil as the err arm of a match. The _, which Go calls the
blank identifier, means “I don’t need this value”, which here is the row. You’ll see if err != nil all through Go
code. It’s how Go programs handle a step that can fail, and like nil itself,
nothing makes you write it; Go programmers write it out of habit.
3.7 The game and the turn
In chapter 1, the state of the game was three variables at the top of the main loop: the board, whose turn it was, and whether the game was over. vier-cli gathers them into a struct in game.go:
type Game struct {
Board Board
Turn Player
Winner Player
Over bool
}
The body of your main loop, the part that makes a move and checks for the end, became a method:
func (g *Game) Play(column int) error {
if g.Over {
return ErrGameOver
}
if _, err := g.Board.Drop(column, g.Turn); err != nil {
return err
}
g.Winner = g.Board.Winner()
g.Over = g.Winner != Nobody || g.Board.Full()
if !g.Over {
g.Turn = g.Turn.opponent()
}
return nil
}
Read it next to your loop. It drops the disc, asks for a winner, decides whether the game is over, and passes the turn. Every step is one you wrote. The only difference is that when the game ends, vier-cli doesn’t pass the turn, so the winner is still the one whose turn it is.
3.8 The loop, and one move through it
The loop is Serve, in session.go:
func (s *Session) Serve(in io.Reader) {
lines := bufio.NewScanner(in)
for {
fmt.Fprint(s.out, s.prompt())
if !lines.Scan() {
fmt.Fprintln(s.out)
return
}
command := strings.ToLower(strings.TrimSpace(lines.Text()))
switch command {
case "":
case "quit":
return
case "help":
fmt.Fprint(s.out, help)
...
default:
s.play(command)
}
}
}
It’s chapter 1’s loop with more to say. It prints a prompt, reads a line, and
stops if there are no more lines, as your readLine returning none did. Then
it looks at what you typed. A command it knows gets an answer. Anything else
goes to play, which tries it as a column.
A Session is everything that lasts from one game to the next: the game in
progress, the level you chose, and where to save. s is the session, and
s.out is where it prints, which is normally the screen. The rest of this
section follows 4 from the keyboard to the computer’s reply.
Serve reads 4, doesn’t recognize it as a command, and calls play:
func (s *Session) play(command string) {
number, err := strconv.Atoi(command)
if err != nil {
fmt.Fprintf(s.out, "I don't know %q. Type help for the commands.\n", command)
return
}
if err := s.game.Play(number - 1); err != nil {
fmt.Fprintln(s.out, refusal(err, number))
return
}
fmt.Fprint(s.out, s.game.Board)
s.announce()
s.computerTurn()
s.save()
}
strconv.Atoi is Go’s parseInt, and it answers with two values too: the
number, or an error if what you typed wasn’t one. hello stops here. 4
doesn’t, and becomes column 3, counted from 0 as in chapter 1.
s.game.Play(3) is the method from section 3.7. It drops the disc, checks for a
winner, and passes the turn to Yellow. If the column was full or doesn’t exist,
it returns an error instead, and refusal turns the error into a sentence like
“There is no column 9.”
fmt.Fprint(s.out, s.game.Board) prints the board. That works because Board
has a method called String, and Go’s printing functions look for one on
anything they’re asked to print. A type with a String method is called a
Stringer. String in board.go is your show, building the same lines from
the top row down.
announce prints the result if the game just ended. computerTurn gives the
computer its move, which section 3.10 opens up. save writes the game to a file,
which is section 3.11.
A move’s route, then, is Serve → play → Game.Play →
Board.Drop → back up to print the board → computerTurn → save. If you
know that route, you know how vier-cli works. Everything else in the program
hangs off it.
3.9 How you know it works
Your lux game was tested by playing it. vier-cli has tests, in the files ending
in _test.go, and go test runs them. With -v, it lists each one by name:
$ go test -v
=== RUN TestDiscsStackFromTheBottom
--- PASS: TestDiscsStackFromTheBottom (0.00s)
=== RUN TestAFullColumnRefusesADisc
--- PASS: TestAFullColumnRefusesADisc (0.00s)
=== RUN TestOnlySevenColumnsExist
--- PASS: TestOnlySevenColumnsExist (0.00s)
=== RUN TestPlayersTakeTurns
--- PASS: TestPlayersTakeTurns (0.00s)
=== RUN TestThereAre69WinningLines
--- PASS: TestThereAre69WinningLines (0.00s)
=== RUN TestFourInALineWins
--- PASS: TestFourInALineWins (0.00s)
...
The names read like the rules of the game. When you open a program you don’t know, the test names are one of the best places to start: they’re a list of what the program promises, written by the person who made it.
A test is a small program that plays part of the game and checks the result. This one plays a few short games and checks who won each:
func TestFourInALineWins(t *testing.T) {
for _, game := range []struct {
name string
columns []int
winner Player
}{
{"across", []int{1, 1, 2, 2, 3, 3, 4}, Red},
{"up", []int{1, 2, 1, 2, 1, 2, 7, 2}, Yellow},
{"rising diagonal", []int{1, 2, 2, 3, 3, 4, 3, 4, 4, 1, 4}, Red},
{"falling diagonal", []int{7, 6, 6, 5, 5, 4, 5, 4, 4, 7, 4}, Red},
{"three is not four", []int{1, 1, 2, 2, 3, 3}, Nobody},
} {
if got := played(t, game.columns...).Winner(); got != game.winner {
t.Errorf("%s: got %s, want %s", game.name, got, game.winner)
}
}
}
You don’t need every detail to read it. It’s a list of games, each with a name,
the columns played in order, and who should win, and a loop that plays each one
and complains if the winner is wrong. []int is a slice of ints, Go’s list
that can grow, like lux’s [int]. Without a size in the brackets it’s a slice;
with one, as in the board, it’s a fixed-size array.
try: in board.go, change
markto return"X"for Red instead of"R", and rungo test. Read which tests fail and what each one says. Every failure is about what the board looks like on the screen, because that’s all you changed. Change it back when you’re done.
3.10 The computer
The computer’s move comes from BestMove in engine.go. You can understand what
it does without following how, and that’s enough to read the rest of the
program. It works through four questions, in order:
- Can I win with this move? Then play it.
- Can my opponent win with their next move? Then block it, unless I’m the easy computer.
- Should I play a random column instead of thinking? The easy computer does that about two times in three, the medium one about half the time, and the hard one never.
- Otherwise, look ahead.
Looking ahead means trying every column, then every reply the opponent could
make to it, then every answer to that, and so on: one move deep for the easy
computer, two for medium, and four for hard. When it stops looking, it scores
each board it reached with evaluate, which counts things that tend to win:
discs in the middle column, and three or two in a line with room to finish
them. Then it picks the column that leads to the best score, assuming the
opponent always picks their best reply too.
Trying a move means dropping a disc on a copy of the board, and here your lux habit pays off:
next := board
row, err := next.Drop(column, player)
next := board copies the board, because a Go array is copied when you assign
it, just as lux copies. The computer changes next and leaves the real board
alone.
3.11 Remembering
After every move, save writes the game to a file. On Linux it’s
~/.local/state/vier-cli/state.json:
{
"mode": "computer",
"difficulty": "easy",
"nextStarter": "yellow",
"savedGame": {
"board": [
".......",
".......",
".......",
"...Y...",
"...R...",
".Y.R..."
],
"turn": "red"
}
}
This format is called JSON, and many programs use it to keep data in a file
that people can read as well. You can see the board in it, top row first, the
way the game prints it. The letters look like the screen’s, but they’re kept
separately, in memory.go, so a change to how the discs are drawn can’t make a
saved game unreadable. That’s the exercise from section 3.9 again: change
mark, and the saving tests still pass. When vier-cli starts, it reads this file back, and if
there’s an unfinished game, it says “Picking up where you left off.” The code
that turns the board into those six lines and back is in memory.go.
3.12 What you found
You opened a Go program of fifteen hundred lines and found your game inside it.
The board is a struct of cells, and the rules are methods on it. The turn lives
in Game, the loop is Serve, and the display is String. A move travels
through a handful of functions you can name. The parts you skipped, the search,
the saving and the options, each do one job, and you know which job.
The Go ideas you needed were few. Methods put their receiver before the dot. A
pointer, written with a star, leads to the original instead of a copy. Two
return values, with if err != nil, do the job of Result. And every value
starts at its zero value. With those and the
reading table from chapter 2, you can open most small Go programs and find your
way around.
One thing about vier-cli is the same as your lux game, and it’s about to stop
being true. vier-cli runs the loop itself: Serve reads a line, answers it, and
goes around again, and nothing happens unless Serve makes it happen. The next
two apps don’t work that way. In a window or on a phone, something else runs
the loop, and your code waits to be called. Chapter 4 shows what that means, in
lux.
4. Who Runs the Loop
Your lux game and vier-cli share one habit. Each runs its own loop: show the board, wait for a line, make the move, go around again. While the program waits for that line, nothing else happens, and nothing needs to. A terminal is patient.
A window isn’t. While you decide where to play, the window still has to answer the mouse, draw the column you’re pointing at, and repaint itself when another window moves off it. If the program stopped to wait for your click the way vier-cli stops to wait for a line, the window would freeze. So programs with windows hand the loop to someone else, and both of the remaining apps in this book are built that way. This chapter shows what that means, in lux, before you meet it in Rust.
4.1 A program someone else runs
lux has a lesson on this. Run lux learn host. It describes a program run by
another program, called a host. The host loads your file, and then it calls
your functions whenever it needs them, hands them values, and keeps what they
hand back. Your file holds only declarations, structs, enums and functions,
with no lines at the top level, because the host decides when anything runs.
The host for a program with a window is usually a framework: a library that runs the loop and calls code you wrote at the right moments. vier-desktop’s framework is called eframe, and vier-ios’s is SwiftUI. The loop a framework runs is called the event loop. An event is something that happened, like a click, a key or the mouse moving, and each time around, the loop collects the events, lets your code respond to them, and draws the window again. One pass around the loop is a frame, the same word as one picture in a film, because that’s what each pass produces.
So the question this chapter asks of Vier is: if you can’t write the loop, what do you write instead?
4.2 Vier for a host
The game shaped for a host is in examples/ch04-host/vier.lux. The board and
the rules are chapter 1’s, unchanged: emptyBoard, canDrop, dropped,
winner and isFull are copied over line for line. Rules don’t care who runs
the loop.
What goes is everything that talked to the terminal. chosenColumn and
readLine are gone, because the host does the reading. The while !done loop
is gone, because the host does the looping. And show, which printed the
board, becomes picture, which builds the same text and returns it, because
the host does the drawing too.
What’s left is four functions the host calls:
func fresh() -> Game
func clicked(game: Game, column: int, now: float) -> Game
func tick(game: Game, now: float) -> Game
func draw(game: Game) -> string
fresh makes a new game. clicked is called when you click a column. tick
is called on every frame, whether anything happened or not. draw is called
on every frame too, and what it returns goes on the screen. Each one takes the
game and, except for draw, hands back a new game, the way dropped takes a
board and hands back a new one. The host keeps the game between calls. Your
code never holds on to anything.
A function you write for someone else to call is often called a callback, because the host calls back into your code. These four are the game’s callbacks.
4.3 The game can’t wait
The game in this chapter has a computer opponent, a simple one that takes the
first open column it finds counting out from the middle. In vier-cli, the
computer moved inside play: you typed a column, your disc dropped, the
computer picked its column, and its disc dropped, all before play returned.
In a window you’d want something between those steps. Your disc should land,
the computer should seem to think for a moment, and then its disc should land.
In vier-cli, a pause would be easy: wait half a second, then move. Under a
host it’s impossible. While your function runs, the host is waiting for it, so
it can’t draw a frame or answer the mouse. A pause inside clicked would
freeze the window for as long as the pause lasted.
So the game can’t wait. It writes down what it’s waiting for, returns, and
checks again on the next frame. That’s what the Phase enum is for:
enum Phase {
yourTurn
computerThinking(column: int, dueAt: float)
finished(message: string)
}
struct Game {
board: Board
phase: Phase
}
Phase replaces chapter 1’s turn and done. The game is either waiting for
your click, or waiting for the computer’s move, or over. The middle case
carries the computer’s column, chosen already, and the time it’s due. Time has
become part of the game’s data, the same as the board.
An enum like this, with a case for each situation the program can be in and rules for moving from one case to the next, is called a state machine. Most programs with windows have one, even when nobody gives it that name.
Here is how a click moves the game from one case to the next:
func clicked(game: Game, column: int, now: float) -> Game {
let waiting = match game.phase {
yourTurn => true
_ => false
}
if !waiting || !canDrop(game.board, column) {
return game
}
let board = dropped(game.board, Player.red, column)
let thinking = Phase.computerThinking(column: computerColumn(board), dueAt: now + 0.5)
return afterDrop(board, thinking)
}
A click only counts if it’s your turn and the column is open. Otherwise the
game comes back unchanged. A counted click drops your disc and sets the
computer thinking, due half a second from now. afterDrop checks whether
that disc won or filled the board, and if it did, the game is finished
instead.
now is the time, in seconds, and the host passes it in. Your code has no
clock of its own, for the same reason it has no readLine: anything from the
outside world comes from the host.
Then each frame, tick checks whether the computer’s time has come:
func tick(game: Game, now: float) -> Game {
return match game.phase {
computerThinking(let column, let dueAt) => computerMove(game, column, dueAt, now)
_ => game
}
}
func computerMove(game: Game, column: int, dueAt: float, now: float) -> Game {
if now < dueAt {
return game
}
return afterDrop(dropped(game.board, Player.yellow, column), Phase.yourTurn)
}
On most frames, nothing has changed, and tick hands the game back as it was.
On the first frame at or after dueAt, the computer’s disc drops and it’s your
turn again. The second function is there because a match arm in lux holds a
single expression, and the time check needs an if.
4.4 Drawing from the game
draw builds the whole screen from the game, every time:
func draw(game: Game) -> string {
let status = match game.phase {
yourTurn => "Your turn."
computerThinking(let _, let _) => "The computer is thinking..."
finished(let message) => message
}
return picture(game.board) + "\n" + status
}
It doesn’t remember what it drew last time, and it doesn’t change anything. It
reads the game and describes it. If the screen is wrong, the game is wrong, or
draw is, and there’s nowhere else to look. That habit, building the screen
fresh from the state on every frame, is how both of the next two apps draw.
4.5 Being the host
With no host, nothing calls these functions. Delete the last lines of the file
and run it, and it prints nothing, which is the shape lux learn host
describes. With the last lines in, you’re the host:
var game = fresh()
var shown = ""
for frame in 0..30 {
let now = float(frame) / 10.0
if frame == 2 {
game = clicked(game, 3, now)
}
if frame == 12 {
game = clicked(game, 4, now)
}
game = tick(game, now)
let screen = draw(game)
if screen != shown {
print("frame", frame)
print(screen)
shown = screen
}
}
This is an event loop. It runs thirty frames, ten to a second, so now goes
from 0.0 to 2.9. A real host would get clicks from the mouse; this one makes
two up, a click on column 4 at frame 2 and on column 5 at frame 12. Every frame
it calls tick and draw, and to keep the output short, it prints the screen
only when it changed:
$ lux run vier.lux
frame 0
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
1 2 3 4 5 6 7
Your turn.
frame 2
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . R . . .
1 2 3 4 5 6 7
The computer is thinking...
frame 7
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . Y . . .
. . . R . . .
1 2 3 4 5 6 7
Your turn.
frame 12
...
The click at frame 2 drops your disc and sets the computer’s move due at 0.7.
Frames 3 to 6 call tick and draw and get the same screen back, so nothing
prints. At frame 7, tick finds the time has come, and the computer’s disc
appears. Frame 12 does it all again.
Nothing in the game ever waited. Every call returned at once, and the half second passed in the host, between calls.
try: change
now + 0.5tonow + 2.0and run it again. The computer now answers at frame 22, and your click at frame 12 does nothing, because it came while the computer was still thinking.clickedlooked at the phase, saw it wasn’t your turn, and handed the game back unchanged. Change it back when you’re done.
A real host doesn’t always draw at a steady ten frames a second. Some draw as
often as the screen can show a new picture, sixty times a second or more. Some
draw a frame only when something happens, a click or a mouse move, and a
program waiting on a time like dueAt can ask to be called again when it
arrives. vier-desktop’s host works that second way. Your functions are the same
either way: they take the game and the time, and hand back a game.
4.6 The map, under a host
Here are chapter 1’s five pieces again, as they are in this version:
| Piece | Chapter 1 | Under a host |
|---|---|---|
| The board | Board | Board, unchanged |
| The rules | canDrop, dropped, winner, isFull | unchanged |
| The turn | turn and done | Phase, which also holds what the game is waiting for |
| The loop | while !done | the host’s; you write clicked and tick |
| The display | show, which prints | draw, which returns the screen for the host to show |
The board and the rules came through untouched. The turn grew into a state machine with time in it, the loop moved out of your program, and the display stopped printing and started describing.
That’s the shape of vier-desktop. Its framework calls a function named ui on
every frame. ui passes the time to the game, which checks for a step whose
time has come, as tick does. Then it draws the board from the game, and if
you clicked a column, the click goes to the game, as clicked does. There’s
more of it, in a different language, but it’s the program you just ran.
Chapter 5 opens it.
5. vier-desktop
vier-desktop is Vier in a window, written in Rust. You point at a column and a red disc hovers over it, you click and the disc falls, and the computer slides its yellow disc across and drops it. It plays against the computer or a second person, and like vier-cli, it picks up a game you didn’t finish. It’s about seventeen hundred lines counting its tests, and fourteen hundred without them.
This chapter and the next read it. This one gets it running, finds the pieces, and reads the board and the rules, which are the parts that look most like your lux game. Chapter 6 reads the parts chapter 4 prepared you for: the frame, the phases, and one click followed all the way through.
5.1 Running it
git clone https://github.com/anderix/vier-desktop
cd vier-desktop
cargo run
Cargo is Rust’s build tool, the way go is Go’s. cargo run builds the
program and starts it. The first time, it also downloads and builds the
libraries the game uses, which takes a few minutes; after that, it’s quick.
Rust calls a library a crate, and the crates a program needs are listed in
Cargo.toml:
[dependencies]
eframe = "0.36"
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"
eframe is the framework from chapter 4, the host that runs the loop and puts
the window on the screen. serde and serde_json save the game to a file.
vier-cli used only what comes with Go. vier-desktop needs more, because a
window takes a framework, and neither Rust nor Go comes with one.
It runs on Linux, on a Mac and on Windows. A window opens on a home screen, with a Play button and a choice between playing the computer at Easy, Medium or Hard, or a second player. Play a game:
Notice the things vier-cli couldn’t do: the disc follows your mouse before you click, falls instead of appearing, and the computer’s disc hovers for a moment before it drops. Each of those takes time on the screen, and chapter 4 showed why a program under a host has to keep track of that time itself. Press Escape to go back to the home screen, and the game waits there.
5.2 Finding the pieces
The files, in src:
board.rs the board, the players, the rules
engine.rs how the computer picks a move
rng.rs random numbers for the computer
game.rs one game: whose turn it is, its phase, its timing, saving
board_view.rs drawing the board and reading the mouse
palette.rs the colours
main.rs where it starts: the window, the screens, the keys
That’s close to vier-cli’s list, and it’s not a coincidence. vier-cli’s
computer opponent was translated from this program’s engine.rs, and both
programs split the game the same way: a board with rules, a game that holds the
turn, and something that talks to the person. What’s new is board_view.rs,
because a window has to be drawn, and the absence of anything like Serve.
| Piece | lux | vier-desktop |
|---|---|---|
| The board | Board, Option<Player> cells | Board in board.rs |
| The rules | canDrop, dropped, winner, isFull | can_drop, drop, winner, is_full in board.rs |
| The turn | turn and done | turn and phase in Game, in game.rs |
| The loop | while !done | eframe’s; it calls ui in main.rs every frame |
| The display | show | board_view.rs |
Rust writes names in lowercase with underscores between the words, so
canDrop becomes can_drop. Otherwise the first two rows could be your
program’s.
5.3 Shapes you know
Open board.rs. A little way down:
#![allow(unused)]
fn main() {
pub enum Player {
Red,
Yellow,
}
impl Player {
pub fn opponent(self) -> Player {
match self {
Player::Red => Player::Yellow,
Player::Yellow => Player::Red,
}
}
}
}
After chapters 2 and 3, this should be a relief. It’s a lux enum and a lux
match, with the same arrows and the same rule that every case has an arm.
Rust writes Player::Red where lux writes Player.red, puts commas after the
arms, and starts the case names with capitals. There’s no interface to read
around and no number standing in for a player.
The same goes for Option. Rust has it, spelled Option, with Some and
None, and the board uses it the way yours did:
#![allow(unused)]
fn main() {
pub struct Board {
cells: [[Option<Player>; COLUMNS]; ROWS],
}
}
That’s chapter 1’s board: rows of cells, and each cell a player or nothing.
The numbers after the semicolons make each row exactly seven cells and the
board exactly six rows, like the fixed-size array in vier-cli. COLUMNS and
ROWS are constants, declared near the top of the file with const.
No Nobody here. Rust keeps lux’s answer to the empty cell: a cell that might
be empty says so in its type, and match makes you deal with it.
5.4 Reading past the decorations
Above Board is a line like this:
#![allow(unused)]
fn main() {
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
}
A line starting with #[ is an attribute: a note to Rust about the thing
below it. derive asks Rust to write some standard methods for the type so the
author doesn’t have to. Clone lets a board be copied, PartialEq and Eq
let two boards be compared with ==, Default makes an empty one, and
Serialize and Deserialize let serde save it to a file and read it back.
lux gives every struct a copy and an == for free. Rust gives them when you
ask, and derive is the asking. When you’re reading for the big picture, read
past these lines.
pub is short for public, and does what a capital letter does in Go: a pub
name can be used from other files. cells has no pub, so only board.rs can
reach into a board’s cells. Everyone else has to go through its methods.
Those methods are inside impl Board { … }. An impl block is where Rust
puts a type’s methods, all together. vier-cli wrote each method on its own,
with the receiver in front of the name. Rust gathers them under the type and
writes the receiver first in the list, as self.
5.5 Borrowing
Here are two of the board’s methods:
#![allow(unused)]
fn main() {
pub fn can_drop(&self, column: usize) -> bool {
column < COLUMNS && self.cells[ROWS - 1][column].is_none()
}
pub fn drop(&mut self, player: Player, column: usize) -> Option<Position> {
if !self.can_drop(column) {
return None;
}
let row = (0..ROWS).find(|&row| self.cells[row][column].is_none())?;
self.cells[row][column] = Some(player);
Some(Position { column, row })
}
}
Look at what comes before self. can_drop takes &self, and drop takes
&mut self.
The & makes a reference. Like a pointer in Go, a reference leads to a
value kept somewhere else instead of holding a copy. &self is a reference
the method can only look through, and &mut self, a mutable reference, is
one it can change things through. So this is the same choice as in vier-cli,
where CanDrop had a plain receiver and Drop had a pointer receiver: one
method looks at the board, the other changes it in place.
Rust calls handing over a reference borrowing. drop borrows the board,
changes it, and gives it back when it returns. Rust adds one rule Go doesn’t
have: while something has borrowed a value to change it, nothing else can use
that value at all, not even to look. The part of Rust that enforces the rule is
called the borrow checker, and it checks before the program ever runs, so a
program that breaks the rule doesn’t build. Chapter 1 kept you safe from two
pieces of code changing one board at once by handing out copies. Rust allows
the sharing and checks it instead.
For reading, the rule is short. & in front of a type means “looks at it”.
&mut means “may change it”. A method with &mut self changes the value you
call it on.
5.6 The rules, in Rust’s shorthand
The rest of drop uses three things lux doesn’t have.
usize is the type Rust uses for counting and indexing. It’s a whole number
that can’t be negative, so can_drop checks only that the column isn’t too
big. Chapter 1 had to check for below zero as well, because columnFrom used
-1 for “not a column”. In Rust, -1 can’t be a column at all.
|&row| self.cells[row][column].is_none() is a closure: a small function
with no name, written right where it’s used. The part between the bars is its
parameter, row (read past the &), and the rest is what it returns. lux has no closures, so read this
one by turning it into a loop. (0..ROWS).find(…) tries each row from 0 up and
stops at the first one where the closure says yes, which is chapter 1’s
landingRow:
var row = 0
while at(board, column, row) != none {
row += 1
}
You’ll see closures all through Rust, with find, any, all, map and
filter. Each of them is a loop you’ve written before. is_full is one more:
#![allow(unused)]
fn main() {
pub fn is_full(&self) -> bool {
!(0..COLUMNS).any(|column| self.can_drop(column))
}
}
“The board is full if no column can take a disc.” That’s your isFull, with
the loop folded into a word.
The ? at the end of the find line is the question mark operator. find
returns an Option: the row it found, or None if it didn’t find one. The
? says: if this is None, return None from the method now;
otherwise, take the value out and carry on. In lux you’d write that as a
match with a none arm that returns. Rust puts it in one character, and
you’ll see it often.
drop itself returns Option<Position>: where the disc landed, or None if
it couldn’t go in. vier-cli’s Drop answered with a row and an error. Same
question, and each language’s usual way of answering it.
5.7 How you know it works
$ cargo test
running 19 tests
test board::tests::discs_stack_from_the_bottom ... ok
test board::tests::four_across_wins ... ok
test board::tests::a_full_column_refuses_a_disc ... ok
test board::tests::there_are_69_winning_lines ... ok
test game::tests::a_drop_lands_then_passes_the_turn ... ok
test game::tests::input_is_ignored_while_a_disc_falls ... ok
test engine::tests::medium_and_hard_block_an_immediate_win ... ok
...
test result: ok. 19 passed; 0 failed
Some of these names should look familiar. vier-cli has
TestDiscsStackFromTheBottom and TestThereAre69WinningLines; this program
has discs_stack_from_the_bottom and there_are_69_winning_lines. They’re the
same rules, promised in two languages. The tests sit at the bottom of each
file, under #[cfg(test)], an attribute that says “only build this when
testing”. Two of the game tests are about time: a disc that’s falling ignores
clicks, and a drop finishes before the turn passes. Those are chapter 4’s
phases, tested.
5.8 The computer
engine.rs is the program vier-cli’s engine was translated from, and the four
questions from chapter 3 are all here, in the same order, in best_move. You
already know what it does.
One difference shows how each language likes to work. When vier-cli tried a
move, it copied the board, next := board, and dropped a disc on the copy.
vier-desktop makes one copy at the start of the search and then borrows it:
#![allow(unused)]
fn main() {
fn immediate_win(board: &Board, player: Player) -> Option<usize> {
let mut search = board.clone();
SEARCH_ORDER.into_iter().find(|&column| {
let Some(position) = search.drop(player, column) else {
return false;
};
let wins = search.completes_four(position);
search.remove(position);
wins
})
}
}
For each column, it drops a disc, checks whether that disc won, and takes the
disc back out with remove. The deep search does the same, thousands of times,
on one board. Copying is simpler to get right; dropping and removing on one
board does less work. Go’s version chose the first and Rust’s the second, and
the borrow checker is what makes the second safe to write: nothing else can
touch search while the engine is changing it.
let Some(position) = … else { return false; }; is another way Rust writes a
match on an Option. If the value is Some, its contents get a name and the
code carries on; if not, the else runs, and it has to leave. Read it as a
match whose none arm returns.
5.9 What you found
The board, the rules and the computer are in front of you, and they’re the
parts of vier-desktop that would make sense with no window at all. The tests
run them with no window. On the surface, Rust looks more like lux than Go
does, with real enums, Option and match, and it asks you to learn a few
ideas of its own: references and borrowing, closures, and the ?.
Here are this chapter’s rules in one place:
| In Rust | Read it as |
|---|---|
fn f(x: usize) -> bool | func f(x: int) -> bool, with usize an int that can’t be negative |
let x = 5 and let mut x = 5 | let x = 5 and var x = 5 |
Player::Red | Player.red |
Some(x), None | some(x), none |
[T; N] and Vec<T> | [T], fixed size and growable |
impl Board { … } | the functions that take a Board first |
&self, &mut self | looks at the value; may change it |
|x| … | a small function with no name, often a loop folded up |
value? | if it’s none, return none now |
let Some(x) = value else { … } | a match whose none arm leaves |
#[derive(…)] | standard methods written for you; read past it |
pub | usable from other files |
What you haven’t seen is the game: whose turn it is, the time things take, and how a click gets in. That’s game.rs and main.rs, and it’s where vier-desktop stops looking like vier-cli and starts looking like chapter 4. Chapter 6 reads it.
6. The Frame
Chapter 5 read the parts of vier-desktop that would make sense with no window. This chapter reads the rest: how the program starts, what it does on every frame, and what happens between your click and the computer’s answer. You’ve seen all of it before, in chapter 4, in about a hundred lines of lux. Here it’s in Rust, with more going on, but the shape is the same: something else runs the loop, the game keeps track of time, and the screen is drawn from the game.
6.1 Where it starts
A Rust program starts at main, like a Go program. vier-desktop’s is in
main.rs:
fn main() -> eframe::Result {
let viewport = egui::ViewportBuilder::default()
.with_app_id(APP_ID)
.with_title("Vier")
.with_inner_size([520.0, 640.0])
.with_min_inner_size([320.0, 420.0]);
let options = eframe::NativeOptions {
viewport,
..Default::default()
};
eframe::run_native(
"Vier",
options,
Box::new(|creation| Ok(Box::new(Vier::new(&creation.egui_ctx)))),
)
}
The first half describes the window: its title and its size. The last line is
the one that matters. eframe::run_native opens the window and runs the event
loop, and it doesn’t return until the window closes. Everything after this
happens because eframe calls into the program.
Its last argument is a closure, the small nameless function from chapter 5.
eframe calls it once, when the window is ready, and it makes a Vier, the
value that holds the program’s state from then on. Box::new is how Rust
hands eframe a value to keep for as long as it runs; read past it. In
chapter 4’s terms, this line is the host loading your file and calling
fresh().
6.2 What the host asks for
How does eframe know what to call? Further down main.rs:
#![allow(unused)]
fn main() {
impl eframe::App for Vier {
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
...
}
}
}
eframe::App is a trait: a set of methods a type promises to have. It’s
the same idea as Go’s interface from chapter 2, a name for every type that can
do certain things. eframe will run any value whose type has the App trait,
and impl eframe::App for Vier is where Vier keeps the promise, by writing
the method the trait asks for. Here that’s ui, which eframe calls on every
frame.
A trait is how a framework writes down its side of the deal. In chapter 4, the
host expected fresh, clicked, tick and draw, and nothing checked that
you’d written them. Here, if Vier didn’t have a ui method, the program
wouldn’t build.
6.3 One frame
Here is all of ui:
#![allow(unused)]
fn main() {
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
let now = ui.input(|input| input.time);
self.game.advance(now);
if ui.input(|input| input.viewport().close_requested()) {
self.game.save();
}
egui::CentralPanel::default().show(ui, |ui| match self.screen {
Screen::Home => self.home(ui, now),
Screen::Playing => self.playing(ui, now),
});
if let Some(deadline) = self.game.next_deadline() {
ui.ctx()
.request_repaint_after_secs((deadline - now).max(0.0) as f32);
}
}
}
Put it next to chapter 4’s host loop and the lines match up. First it gets
now, the time in seconds, from eframe, because the game has no clock of its
own. Then self.game.advance(now) is chapter 4’s tick: it lets the game
catch up on anything whose time has come. If the window is closing, the game
saves. Then it draws whichever screen you’re on, home or playing, which is
chapter 4’s draw, and as you’ll see in section 6.6, drawing is also where
clicks come in.
The last three lines are the part chapter 4 mentioned at the end. eframe
doesn’t draw at a steady rate. It draws a frame when something happens, like a
click or the mouse moving, and otherwise it waits. That saves work, but it
means that if the computer’s move is due in 0.4 seconds and you don’t touch
the mouse, there might not be another frame to notice. So ui asks the game
when its next step is due and asks eframe to draw another frame by then.
6.4 The game
The game is in game.rs, and its state is a struct. Here are the fields this chapter needs:
#![allow(unused)]
fn main() {
pub struct Game {
board: Board,
turn: Player,
phase: Phase,
last_drop: Option<(Position, f64)>,
computer_column: Option<usize>,
pending: Option<(f64, Step)>,
...
}
}
board and turn are chapter 1’s. phase is chapter 4’s idea, with one more
case:
#![allow(unused)]
fn main() {
pub enum Phase {
PlayerTurn,
AnimatingDrop,
ComputerThinking,
Finished(Outcome),
}
}
AnimatingDrop is the time a disc spends falling. Chapter 4’s discs appeared
at once; vier-desktop’s take a moment, and while they fall, the game doesn’t
accept a click.
(f64, Step) is a tuple: two values held together without a struct to name
them. f64 is Rust’s float. So pending is either None, nothing
scheduled, or Some of a time and a step to take at that time. The steps are
another enum:
#![allow(unused)]
fn main() {
enum Step {
FinishDrop,
RevealComputerColumn(usize),
ComputerDrop(usize),
}
}
In chapter 4, computerThinking(column, dueAt) held both what the game was
doing and what it was waiting for. vier-desktop splits those apart. phase
says what the screen should show: your turn, a disc falling, the computer
thinking, or the end. pending says what happens next and when. There are
three kinds of next thing: a falling disc lands, the computer’s disc moves
over the column it chose, and the computer’s disc drops.
last_drop remembers which disc fell most recently and when, which is how the
screen knows where to draw a falling disc. computer_column is where the
computer’s disc hovers before it drops.
6.5 Catching up
advance is called on every frame:
#![allow(unused)]
fn main() {
pub fn advance(&mut self, now: f64) {
while let Some((at, step)) = self.pending {
if at > now {
return;
}
self.pending = None;
match step {
Step::FinishDrop => self.finish_drop(at),
Step::RevealComputerColumn(column) => {
self.computer_column = Some(column);
self.pending = Some((at + HOVER_SECONDS, Step::ComputerDrop(column)));
}
Step::ComputerDrop(column) => {
self.computer_column = None;
self.drop(column, at);
}
}
}
}
}
while let is a loop that keeps going as long as the value matches the
pattern. Read it as: while there’s a pending step, take it apart into at and
step. If the step isn’t due yet, return; this is chapter 4’s
if now < dueAt { return game }. If it is due, clear it and take it, with a
match on which step it is. Taking a step often schedules the next one.
Why a loop, when chapter 4’s tick took at most one step? Because frames
don’t come at a steady rate. If nothing drew a frame for a second, two or
three steps might be overdue at once, and the loop takes them all, in order,
before the screen is drawn. Notice too that each step is given at, the time
it was due, not now, the time it happened to get noticed. The next step is
scheduled from when this one should have happened, so a late frame doesn’t
make everything after it late too.
6.6 One click, all the way through
Now follow a click. You’re Red, it’s your turn, and you click column 4.
The click arrives while drawing. The playing screen draws the board with
board_view::show, and that function hands back what the mouse did:
#![allow(unused)]
fn main() {
let board_area = ui.allocate_ui(Vec2::new(ui.available_width(), board_height), |ui| {
board_view::show(ui, &self.game, now)
});
let input = board_area.inner;
if let Some(column) = input.hovered_column {
self.game.select(column);
}
if let Some(column) = input.clicked_column {
self.game.play(column, now);
}
}
board_view::show takes &self.game, a reference it can only look through,
so drawing can’t change the game. It reports which column the mouse is over
and which was clicked, and the program passes the click to the game: chapter
4’s clicked(game, column, now), as self.game.play(3, now).
play checks, as clicked did, that it’s your turn and the column is open,
and then drops the disc:
#![allow(unused)]
fn main() {
fn drop(&mut self, column: usize, now: f64) {
let Some(position) = self.board.drop(self.turn, column) else {
return;
};
self.last_drop = Some((position, now));
self.phase = Phase::AnimatingDrop;
self.pending = Some((now + DROP_SECONDS, Step::FinishDrop));
}
}
The disc is in the board right away; board.drop is chapter 5’s method. What
waits is everything after it. The phase becomes AnimatingDrop, and the disc
will land in DROP_SECONDS, 0.3 of a second. play returns, ui returns,
and eframe draws the frame.
From here, nothing happens because of you. Each frame, advance checks the
clock, and the steps go off one after another. Counting from the click:
| Time | Step | What you see |
|---|---|---|
| 0.0 | your click: drop | your disc starts to fall |
| 0.3 | FinishDrop | it lands; the computer starts thinking |
| 0.7 | RevealComputerColumn | the yellow disc slides over its column |
| 0.95 | ComputerDrop | the yellow disc starts to fall |
| 1.25 | FinishDrop | it lands; your turn |
FinishDrop is finish_drop, which is chapter 1’s end-of-move check. It asks
the board for an outcome, and if there is one, the phase becomes Finished.
If not, the turn passes to the opponent and begin_turn starts the next one.
For a person, that means the phase becomes PlayerTurn. For the computer,
it calls play_computer_turn:
#![allow(unused)]
fn main() {
fn play_computer_turn(&mut self, now: f64) {
self.phase = Phase::ComputerThinking;
self.computer_column = Some(self.selected_column);
let column = engine::best_move(&self.board, self.turn, self.difficulty, &mut self.rng);
self.pending = Some((now + THINKING_SECONDS, Step::RevealComputerColumn(column)));
}
}
The computer picks its column right away, with best_move from chapter 5,
which takes a tiny fraction of a second. The thinking you see on the screen is
a pause the program adds afterwards, so the computer’s move doesn’t appear the
same instant yours lands. Its disc first waits over your column, then
RevealComputerColumn moves it over the chosen column, and ComputerDrop
drops it with the same drop your click used.
That’s the route: ui → board_view::show reports the click →
Game::play → drop → frames go by → advance takes FinishDrop,
RevealComputerColumn, ComputerDrop and FinishDrop as each comes due. Put
it next to vier-cli’s route from chapter 3. Every call in vier-cli happened in
one go, inside play. Here the same steps are spread over a second and a
quarter, and between them the program goes back to the host.
6.7 Drawing from the game, every frame
board_view::show draws the whole board, every frame: the blue frame, every
disc in it, and the disc hovering over the top. It keeps nothing from the frame
before. egui, the library eframe draws with, calls this immediate mode: you
don’t create a board on the screen and then update it, you describe the whole
screen again each time, and egui draws what you described. It’s chapter 4’s
draw, which built the screen fresh from the game every time it was called.
Immediate mode is why the falling disc needs no special machinery. Here’s the
part of show that works out how far a disc has fallen:
#![allow(unused)]
fn main() {
if let Some((dropped, at)) = game.last_drop()
&& dropped == position
{
let progress = (((now - at) as f32) / FALL_SECONDS).clamp(0.0, 1.0);
...
y = field_row * progress * progress;
}
}
If this disc is the one that dropped last, progress is how much of the fall
time has passed, from 0 to 1, and the disc is drawn that far down. Each frame,
now is a little later, so the disc is drawn a little lower, and it looks as if
it’s falling. Nothing moves the disc. It’s drawn from the game and the time,
like everything else.
The view also reports instead of acting. It doesn’t decide whether a click
counts; it says which column was clicked and leaves the deciding to play.
That’s why a click while a disc is falling does nothing: the view reports it,
and play sees the phase isn’t PlayerTurn and ignores it, the way
clicked did in chapter 4. One of the tests from chapter 5 checks it: input_is_ignored_while_a_disc_falls.
6.8 Remembering
finish_drop calls save after every move, and save writes a SavedGame:
#![allow(unused)]
fn main() {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
struct SavedGame {
board: Board,
turn: Player,
starter: Player,
difficulty: Difficulty,
mode: Mode,
}
}
The work of turning this into JSON is in the derive line. Serialize and
Deserialize are serde’s, and they write the code that converts a value to
text and back, for this struct and, because Board and Player derive them
too, for everything inside it. vier-cli’s memory.go spelled out how a board
becomes six lines of letters; vier-desktop lets serde decide, and a saved board
comes out as rows of "red", "yellow" and null. The file is
~/.local/state/vier/state.json on Linux and a Mac, and
%LOCALAPPDATA%\vier\state.json on Windows.
The game also saves when the window is closing, which you saw in ui. If you
close the window while a disc is still falling, the disc is already in the
board but finish_drop hasn’t run to save it, and the save on closing catches
it. vier-cli never needed that, because each of its moves finished before it
read another line. Under a host, closing the window is one more event, and the
program hears about it on a frame like any other.
6.9 What you found
| Piece | lux | vier-desktop |
|---|---|---|
| The board | Board | Board in board.rs |
| The rules | canDrop, dropped, winner, isFull | can_drop, drop, winner, outcome in board.rs |
| The turn | turn and done | turn, phase and pending in game.rs |
| The loop | while !done | eframe’s, calling ui each frame, with advance taking steps as they come due |
| The display | show | board_view::show, redrawing everything from the game and the time |
You’ve now read two real programs built around the same five pieces, one that
runs its own loop and one that’s run by a host. The new Rust ideas in this
chapter were few: a trait is a promise a type makes, a tuple holds values
together without a name, while let loops while a pattern matches, and
immediate mode draws the whole screen every frame. The rest was chapter 4.
The last app takes the idea one step further. In vier-desktop, the program still draws every frame itself, even if it draws the same thing as last time. In vier-ios, written in Swift with SwiftUI, you describe what the screen should look like for a given state of the game, and SwiftUI works out when to draw it again: whenever the game changes. Chapter 7 opens it.
7. vier-ios
vier-ios is Vier for the iPhone and the Apple Watch, written in Swift. You slide a finger across the board to move the red disc, swipe down to drop it, and the phone answers with yellow. On the watch, the Digital Crown moves the disc too. It’s the smallest of the three apps, about twelve hundred lines without its tests, and most of those lines are shared by the phone and the watch.
This chapter gets it running and reads the game: the board, the rules, and the part that keeps track of turns and time. It ends at a new idea, one that changes how waiting works, and it’s the last big idea in the book. Chapter 8 reads the screen and the watch.
7.1 Running it
Apps for the iPhone and the watch are built with Xcode, which runs only on a Mac and comes free from the Mac App Store. Get the code:
git clone https://github.com/anderix/vier-ios
cd vier-ios
open Vier.xcodeproj
open opens the project in Xcode. At the top of Xcode’s window, choose the
Vier scheme and an iPhone from the list of simulators, then press the Run
button, or ⌘R. A simulator is a pretend iPhone that runs in a window on your
Mac. Xcode builds the app, starts the simulator, and puts the app on it. The
first time, starting the simulator takes a minute.
Play a game with the mouse: drag sideways on the board to move your disc, and drag down to drop it. A tap does nothing, so a stray touch can’t play a move.
Then choose the Vier Watch App scheme and an Apple Watch simulator, and run
it again. It’s the same game on a smaller screen.
Putting the app on your own iPhone or watch needs your Apple account in Xcode, and the README says which setting to change. The simulator needs neither.
Do NOT submit it to the App Store. Not vier-ios, not a copy with a new name and new colours, and not any other four-in-a-row game built from this book. Apple’s App Review Guideline 4.3 treats copies of an existing app, and apps in a category that’s already crowded, as spam, and four in a row is one of the most crowded there is. When vier-ios was submitted, Apple flagged it under 4.3 and flagged the developer account with it, and every app sent from that account since has been flagged too. The same rules cover the Mac App Store, so they apply to vier-desktop as well. Run these apps on the simulator and on your own devices, and keep them there.
7.2 Finding the pieces
Nearly all the code is in Shared, which the phone app and the watch app both
build from:
Model/Board.swift the board and the rules
Model/Player.swift the players
Engine/AIEngine.swift how the computer picks a move
Engine/Difficulty.swift easy, medium and hard
Game/GameViewModel.swift one game: whose turn it is, its phase, saving
Views/ the screens, the board, a disc
App/VierApp.swift where it starts
Support/ colours, haptics, a small helper
The folders do the sorting this time, and you’ve seen the sorting before: board and rules, engine, game, and the part that faces the person.
| Piece | lux | vier-ios |
|---|---|---|
| The board | Board, Option<Player> cells | Board in Board.swift |
| The rules | canDrop, dropped, winner, isFull | canDrop, drop, winner, isFull in Board.swift |
| The turn | turn and done | turn and phase in GameViewModel.swift |
| The loop | while !done | SwiftUI’s, the framework that runs the app |
| The display | show | Views/ |
Swift writes names the way lux does, canDrop and isFull, so the second row
needs no translating at all.
7.3 Swift you can already read
Player.swift is the whole file:
enum Player: String, Codable, Sendable {
case red
case yellow
var opponent: Player {
self == .red ? .yellow : .red
}
}
It’s a lux enum, with case in front of each case name. The names after the
colon, String, Codable and Sendable, are protocols: Swift’s word for
what Rust calls a trait, a set of things a type promises it can do. Codable,
for one, lets a player be saved. Read past them.
opponent is new in two ways. It’s a computed property: it’s used like a
field, turn.opponent, with no parentheses, but it’s worked out each time
it’s asked for. And a ? b : c is the ternary operator: if a, then b,
otherwise c. It’s an if that produces a value, which lux doesn’t have;
it’s why chapter 4 needed a helper function for the time check. .red is
Player.red, with the type left off because Swift can tell which one you
mean.
Swift has Option too, under the name Optional, and it gets its own
spelling. Player?, with a question mark, means Option<Player>, and nil
is none. The board:
struct Board: Hashable, Codable, Sendable {
static let columns = 7
static let rows = 6
...
private(set) var cells: [Player?] = Array(repeating: nil, count: columns * rows)
static let makes a constant that belongs to the type, written
Board.columns. cells is chapter 1’s cells with one difference: instead of
six rows of seven, it’s one list of forty-two, row after row. The board turns a
column and row into a place in the list, row * columns + column, so the rest
of the program never has to:
subscript(column: Int, row: Int) -> Player? {
self[Position(column: column, row: row)]
}
A subscript lets you use square brackets on your own type. With this one,
board[3, 0] asks for column 3, row 0, the way your at(board, 3, 0) did.
7.4 The rules
func canDrop(in column: Int) -> Bool {
(0..<Self.columns).contains(column) && self[column, Self.rows - 1] == nil
}
@discardableResult
mutating func drop(_ player: Player, in column: Int) -> Position? {
guard canDrop(in: column),
let row = (0..<Self.rows).first(where: { self[column, $0] == nil })
else { return nil }
let position = Position(column: column, row: row)
cells[Self.index(of: position)] = player
return position
}
canDrop is chapter 1’s, in one line: the column is on the board and its top
cell is empty. 0..<7 is lux’s 0..7, the numbers 0 to 6. The
@discardableResult above drop lets a caller ignore the position it hands
back; read past it.
Swift’s method calls carry labels, so you call this board.drop(.red, in: 3).
The in is the label, and it’s there to make the call read like a sentence.
The _ before player means that one has no label.
mutating is Swift’s &mut self and Go’s pointer receiver: this method
changes the board you call it on. Swift needs the word because a struct in
Swift behaves the way a lux value does. Assign one or pass it to a function and
you get a copy, so a method that changes one has to say so.
guard … else { return nil } is a check that has to pass for the method to go
on. If it fails, the else runs, and it has to leave. It’s Rust’s
let … else from chapter 5. The let row = … inside it is how Swift takes a
value out of an Optional: if first(where:) found a row, it’s called row
from here on; if it found nil, the guard fails. The same let works after
if: if let x = value { … } is the some arm of a match.
{ self[column, $0] == nil } is a closure, as in Rust, and $0 is its
parameter, used without giving it a name. first(where:) tries each row and
returns the first one the closure says yes to. That’s landingRow again.
The engine shows the copying at work. To try a move, it starts with a copy of
the board, var search = board, which is a copy because Board is a struct.
Then, like vier-desktop’s, it drops a disc in the copy, checks it, and removes
it. It passes the copy along as inout Board, written &board at the call,
which is how Swift hands a value to a function that may change it.
7.5 The view model
The game is in GameViewModel.swift:
@Observable @MainActor
final class GameViewModel {
enum Phase: Equatable {
case playerTurn
case animatingDrop
case computerThinking
case finished(Outcome)
}
static let dropDuration: Duration = .milliseconds(300)
static let thinkingDelay: Duration = .milliseconds(400)
static let hoverDuration: Duration = .milliseconds(250)
private(set) var board = Board()
private(set) var turn: Player = .red
private(set) var phase: Phase = .playerTurn
...
Look at Phase. It has the same four cases as vier-desktop’s, in the same
order, and the three times are vier-desktop’s too: 0.3 seconds for a disc to
fall, 0.4 for the computer to think, and 0.25 for its disc to hover. These two
programs are the same game, built the same way.
Two words are new. A class is like a struct, with one large difference: a class value isn’t copied. Assign it or pass it along, and both names lead to the same one, the way a Go pointer does. The game is a class because the screens all need the same game. If each screen got a copy, a move on one would never show up on the others.
A view model is the name for what this class is: the game, plus what the
screen needs to know about it. Alongside the board and the turn it has
hover, where to draw the disc waiting at the top, and resultTitle, the
words to show when the game ends. The views read these and draw them. The view
model never draws anything itself.
@Observable is what connects the two, and chapter 8 is about it.
@MainActor you can read past; it keeps the game’s changes in order, all made
from the same place.
7.6 Waiting without freezing
Here is where vier-ios parts from vier-desktop. A click, or here a swipe, comes
to play, which checks it’s your turn and drops the disc:
private func drop(in column: Int) {
guard let position = board.drop(turn, in: column) else { return }
lastDrop = position
phase = .animatingDrop
(isHuman(turn) ? Haptic.playerDrop : .computerDrop).play()
turnTask = Task {
try? await Task.sleep(for: Self.dropDuration)
guard !Task.isCancelled else { return }
finishDrop()
}
}
The first lines are vier-desktop’s drop: put the disc in the board, remember
it as the last drop, set the phase to animatingDrop. The haptic is the small
tap you feel in your hand. Then, where vier-desktop scheduled a pending step
for advance to find, vier-ios does something chapter 4 said you couldn’t. It
waits: sleep for 0.3 seconds, then finish the drop.
Chapter 4’s rule was that your code can’t wait, because while it runs, the
host is stuck waiting for it. await is the way around that rule. A function
that’s allowed to wait is called asynchronous, and await marks the places
where it does. When it reaches one, the function gives control back to the
host, which goes on drawing and answering touches. When the sleep is over, the
function picks up at the next line, with all its variables as they were. This
pair is called async/await.
The waiting happens inside a task, Task { … }, a piece of work that runs
alongside everything else. drop starts the task and returns at once, so
play returns and the screen is drawn with the disc falling. Some time later,
the task wakes up and calls finishDrop.
So vier-ios writes the waiting in order, top to bottom, the way vier-cli wrote
its turn, and it behaves the way vier-desktop does. vier-desktop kept the time
and the next step in pending and checked them every frame. In vier-ios, Swift
does that bookkeeping for you: the task remembers where it stopped and what
time it’s waiting for, and the host wakes it up.
The computer’s turn shows it best:
private func playComputerTurn() {
phase = .computerThinking
computerColumn = selectedColumn
let board = board
let player = turn
let difficulty = difficulty
turnTask = Task {
let search = Task.detached(priority: .userInitiated) {
AIEngine.bestMove(on: board, for: player, difficulty: difficulty)
}
try? await Task.sleep(for: Self.thinkingDelay)
let column = await search.value
guard !Task.isCancelled else { return }
computerColumn = column
try? await Task.sleep(for: Self.hoverDuration)
guard !Task.isCancelled else { return }
computerColumn = nil
drop(in: column)
}
}
Read the task from the top. Start the search. Wait 0.4 seconds. Get the search’s
answer, waiting for it if it isn’t done. Move the yellow disc over that column.
Wait 0.25 seconds. Take the hovering disc away and drop the real one. It’s
vier-desktop’s RevealComputerColumn and ComputerDrop, written as a list of
things to do instead of steps for advance to find.
Task.detached starts a second task to run the search, so the computer thinks
during the pause instead of after it. However long the search takes, up to 0.4
seconds of it is hidden inside a pause that was going to happen anyway. The let board = board lines above it
hand the search a copy of the board, so the search and the game never share
one.
guard !Task.isCancelled is for when you leave. If you start a new game while
the computer is thinking, the game cancels the task, turnTask?.cancel(),
and each check after an await makes sure a cancelled task stops instead of
dropping a disc into the new game.
7.7 How you know it works
The tests are in Vier Watch AppTests, and ⌘U runs them with the watch scheme
chosen. Their names should feel familiar by now:
discLandsInLowestEmptyRow
fullColumnRejectsDrop
threeInARowIsNotAWin
inputIsIgnoredWhileDiscFalls
playDropsInColumnAndPassesTurn
savedGameRestoresPositionAndTurn
One of them tests the waiting directly:
@Test func playDropsInColumnAndPassesTurn() async throws {
let game = makeGame()
game.newGame(mode: .hotSeat, difficulty: .easy)
game.play(column: 5)
#expect(game.board[5, 0] == .red)
#expect(game.phase == .animatingDrop)
try await Task.sleep(for: settle)
#expect(game.phase == .playerTurn)
#expect(game.turn == .yellow)
}
It plays column 6, checks the disc is in the board and still falling, waits for
it to land, and checks the turn has passed. vier-desktop’s version of this test
called advance with a later time. This one waits.
7.8 What you found
The board, the rules, the engine and the game are in front of you, and they
look like vier-desktop’s because they’re the same design. The biggest
difference is in how they wait. vier-desktop turned every pause into data and
checked it on each frame. vier-ios writes the pause as await and lets Swift
keep track.
Here are the Swift rules from this chapter:
| In Swift | Read it as |
|---|---|
case red inside an enum | one case of a lux enum |
Player?, nil | Option<Player>, none |
a ? b : c | if a, then b, otherwise c, as one value |
0..<7 | 0..7 |
board[3, 0] | a subscript; here, at(board, 3, 0) |
drop(.red, in: 3) | drop(Player.red, 3), with a label on the second value |
mutating func | a method that changes the value, like &mut self |
guard … else { return } | a check that must pass, or the function leaves |
if let x = value | the some arm, with the value named x |
{ $0 == nil } | a closure, with $0 as its parameter |
struct and class | copied like a lux value; shared like a Go pointer |
await | wait here, and let the host run meanwhile |
@Observable, @MainActor | read past them for now |
What you haven’t seen is the screen. vier-desktop drew every frame. vier-ios
doesn’t draw at all, in the sense you’ve seen so far, and it doesn’t have a
ui method that runs every frame. Chapter 8 shows what it does instead, and
how one set of code becomes an app for both the phone and the watch.
8. The Screen from the Game
Chapter 7 read vier-ios’s game: the board, the rules, and the view model that
keeps the turn and waits with await. This chapter reads the rest, the part
you see. It’s built with SwiftUI, and it works differently from anything in
the book so far. vier-cli printed the board after each move. vier-desktop drew
it again on every frame. vier-ios describes what the screen should look like,
and SwiftUI draws it again whenever the game changes.
Then it reads the watch, which turns out to be mostly the same program, and ends the book by putting all four versions of Vier side by side.
8.1 Where it starts
VierApp.swift:
@main
struct VierApp: App {
@Environment(\.scenePhase) private var scenePhase
@State private var game = GameViewModel()
var body: some Scene {
WindowGroup {
HomeView()
.environment(game)
}
.onChange(of: scenePhase) {
if scenePhase != .active {
game.save()
}
}
}
}
@main marks where the program starts, the way main did in Go and Rust.
App is a protocol, SwiftUI’s version of eframe’s App trait: a type that
SwiftUI can run. This is chapter 4’s host again, and chapter 6’s
run_native.
The app makes one game, GameViewModel(), and keeps it. @State is how a
SwiftUI type holds on to a value of its own, and you’ll see it again in
section 8.5. .environment(game) hands that game to the home screen and to
every screen opened from it, which is why the view model is a class: they all
need the same game, not a copy each.
What’s missing is the method that runs every frame. There’s no ui here and
no advance. The game’s tasks take care of time, as chapter 7 showed, and as
you’re about to see, SwiftUI takes care of when to draw.
8.2 A view is a description
The smallest view in the app draws one disc:
struct DiscView: View {
let player: Player
let size: CGFloat
var body: some View {
Circle()
.fill(player.color)
.overlay {
if player == .yellow {
Circle()
.strokeBorder(.black.opacity(0.3), lineWidth: max(1, size * 0.08))
.padding(size * 0.2)
}
}
.frame(width: size, height: size)
}
}
A view is a struct with a body, and the body says what the view looks
like: a circle, filled with the player’s colour, with a darker ring inside it
if the disc is yellow, at this size. Each line starting with a dot is a
modifier, which takes a view and returns a changed one: filled, with
something laid over it, at a size. some View means “some kind of view”,
whichever one the body builds. The ring is there so the two colours differ by
shape as well, for anyone who can’t tell red from yellow.
Nothing in DiscView draws. It never says “put pixels here, then here”. It
describes the result, and SwiftUI works out how to draw it. Code written this
way is called declarative: it declares what should be on the screen, and
leaves the steps to the framework.
That’s chapter 4’s draw, taken one step further. draw built the screen from
the game and handed it back. A SwiftUI body does the same, and doesn’t even
choose when it runs.
8.3 When the screen changes
The playing screen is GameView.swift. Its body starts like this:
var body: some View {
VStack(spacing: 4) {
BoardView(board: game.board,
hover: game.hover,
lastDrop: game.lastDrop,
winningCells: game.winningCells,
onSelectColumn: game.select,
onSwipeDown: game.dropInSelectedColumn,
onPlayColumn: game.play(column:))
if isShowingResult, let title = game.resultTitle {
ResultPanel(title: title, onPlayAgain: playAgain, onHome: { dismiss() })
}
}
...
A VStack stacks views one above the other: the board, and under it, when the
game is over, a panel with the result. The board is given what it needs to know
from the game: the board itself, the disc hovering at the top, the last disc
dropped, and the winning four if there are any.
Now the @Observable from chapter 7 comes in. When SwiftUI runs this body, it
notices which parts of the game the body read: game.board, game.hover, and
so on. Later, when one of those changes, because a disc dropped or the phase
moved on, SwiftUI runs the body again and updates the screen to match. If
nothing the body read has changed, the body doesn’t run at all.
So here are three answers to the same question, when to draw the board:
| App | When the board is drawn |
|---|---|
| vier-cli | after each move, because play prints it |
| vier-desktop | on every frame, whatever changed |
| vier-ios | when something the view reads from the game changes |
All three draw from the game. Only the timing differs, and in vier-ios the timing is SwiftUI’s job.
8.4 Input
The last three things BoardView is given aren’t values. They’re functions:
onSelectColumn: game.select,
onSwipeDown: game.dropInSelectedColumn,
onPlayColumn: game.play(column:))
These are callbacks, the word chapter 4 gave you for a function you hand over
for someone else to call. BoardView calls onSelectColumn when you slide
across the board and onSwipeDown when you swipe down, and it doesn’t know or
care what they do. The game decides that. It’s vier-desktop’s BoardInput
from chapter 6, turned around: there, the board view reported what the mouse
did and the program passed it on to the game; here, the board view is handed
the game’s methods and calls them itself.
Inside BoardView.swift, a gesture recognises the swipe:
DragGesture(minimumDistance: 6)
.onChanged { value in
...
let column = start + Int((travel.width / cell).rounded())
onSelectColumn(column.clamped(to: 0...(Board.columns - 1)))
}
.onEnded { value in
slideStartColumn = nil
let down = max(value.translation.height, value.predictedEndTranslation.height)
if down > cell, down > abs(value.translation.width) {
onSwipeDown()
}
}
While your finger moves, onChanged works out how many columns you’ve slid
across and selects that column. When you let go, onEnded checks whether the
swipe went down further than one cell, and more down than sideways. If it did,
that’s a drop.
8.5 Animation
In vier-desktop, a falling disc was drawn a little lower on each frame, worked out from the time since it dropped. SwiftUI animates differently. You describe where a view starts and where it ends up, and SwiftUI draws the frames in between.
Each disc on the board is a PlacedDisc, and a disc that just dropped is
created with a fallDistance, how far above its cell it starts:
@State private var hasLanded: Bool
...
var body: some View {
DiscView(player: player, size: size)
...
.offset(y: hasLanded ? 0 : -fallDistance)
.onAppear {
if !hasLanded {
withAnimation(.spring(duration: 0.25, bounce: 0.2)) { hasLanded = true }
}
}
}
hasLanded is the disc’s own small piece of memory. @State keeps it from one
run of body to the next, because a view’s body can run many times and
anything it held only in a local variable would start over each time. A new
disc starts with hasLanded false, so it’s drawn fallDistance above its
cell. As soon as it appears on the screen, onAppear sets hasLanded to true
inside withAnimation, which asks SwiftUI to move the disc to its new place
over a quarter of a second, with a small bounce at the end, instead of all at
once.
The code never says where the disc is at any moment during the fall. It says “up there” and then “down here, with a spring”, and the frames between are SwiftUI’s.
8.6 One swipe, all the way through
Put chapter 7 and this chapter together and follow a move. It’s your turn and you swipe down over column 4.
The gesture’s onEnded sees a swipe down and calls onSwipeDown, which is the
game’s dropInSelectedColumn, which calls play. play checks the phase, and
drop puts the disc in the board, sets the phase to animatingDrop, and
starts a task that sleeps for 0.3 seconds.
board and phase changed, and the board view read both, so SwiftUI runs the
bodies again. There’s a new disc in the board, so a new PlacedDisc appears,
starting above its cell, and springs down. The disc that was hovering at the
top is gone, because hover is nil while a disc falls.
0.3 seconds later, the task wakes and calls finishDrop. No one has won, so
the turn passes to yellow and playComputerTurn starts. The phase becomes
computerThinking, and the computer’s disc appears at the top, over your
column. That changes what the views read, so they’re drawn again, and the dot
in the corner that shows whose turn it is turns into “…”.
0.4 seconds later, the computer’s task sets computerColumn to its choice. The
hovering disc slides over, animated by a modifier on it. 0.25 seconds after
that, it drops, and everything from the second paragraph happens again for
yellow. When that disc lands, the phase is playerTurn and your red disc is
back at the top.
It’s chapter 6’s timeline, step for step. What changed is who does what. The
waiting is written with await in the game, and the drawing happens because
the game changed. Nothing anywhere runs every frame.
8.7 The watch
The watch app builds from the same Shared folder as the phone app: the same
board, the same engine, the same view model, the same views. Where the two
need to differ, the code says so:
#if os(watchOS)
.digitalCrownRotation($crown, from: 0, through: Double(Board.columns - 1), by: 1,
sensitivity: .low, isContinuous: false, isHapticFeedbackEnabled: true)
.onChange(of: crown) {
game.select(Int(crown.clamped(to: 0...Double(Board.columns - 1)).rounded()))
}
#else
.padding(.horizontal, 12)
#endif
#if os(watchOS) is conditional compilation: the lines up to #else are
built into the watch app and left out of the phone app, and the lines after
#else the other way round. The compiler decides which, before the program
runs, so the phone app doesn’t contain the watch’s code at all.
This one is the Digital Crown, the dial on the side of the watch. Turning it
changes crown, and when crown changes, the view calls game.select with
the column the crown points at. That’s the same game.select the phone’s
slide calls. The crown is one more way in, and the game doesn’t know which one
you used.
There are only eight #if os(watchOS) blocks in the Shared folder, and
besides the crown, most of them set font sizes and spacing for a smaller
screen.
The haptics, the taps you feel, are the other difference, and they’re handled
another way. Shared has a list of the moments that get one:
enum Haptic {
case playerDrop
case computerDrop
case fullColumn
case playerWin
case computerWin
case draw
}
The game calls Haptic.playerDrop.play(), but Shared doesn’t define play.
Each app does, in its own Haptic+Play.swift, with an extension: a way to
add methods to a type from another file. The phone’s version asks the iPhone
for one kind of tap, and the watch’s version asks the watch for another. The
game names the moment, and each device decides what it feels like.
8.8 Remembering
The view model saves the game in save:
let saved = SavedGame(board: board, turn: toMove, starter: starter, difficulty: difficulty, mode: mode)
defaults.set(try? JSONEncoder().encode(saved), forKey: StorageKey.savedGame)
SavedGame is Codable, like Board and Player, so JSONEncoder can turn
it into JSON, the same idea as serde in vier-desktop. The JSON goes into
UserDefaults, a small store every Apple app gets for its settings, instead
of a file the app looks after itself. The phone and the watch each have their
own, so a game on one doesn’t appear on the other.
It saves after every move, and once more when you leave the app. That’s the
onChange(of: scenePhase) in VierApp from section 8.1: when the app stops
being the one in front, because you went to the home screen or lowered your
wrist, it saves. It’s vier-desktop’s save on closing the window. On a phone or
a watch, apps are rarely closed; they’re put away, and the system may end them
later without asking.
8.9 Three apps, one game
Here is chapter 1’s map, one last time, with every version of Vier on it:
| Piece | lux | vier-cli | vier-desktop | vier-ios |
|---|---|---|---|---|
| The board | Board | Board | Board | Board |
| The rules | canDrop, dropped, winner | CanDrop, Drop, Winner | can_drop, drop, winner | canDrop, drop, winner |
| The turn | turn, done | Turn, Over in Game | turn, phase, pending | turn, phase |
| The loop | while !done | Serve | eframe, calling ui | SwiftUI |
| The display | show | String | board_view::show | BoardView |
The top two rows hardly change. A board is cells that hold a disc or nothing, and the rules are the same rules, in four languages. The bottom three rows are where the programs differ, and they differ for the same few reasons, which are the ideas this book has been about.
The first is who runs the loop. Your lux game and vier-cli run their own, and nothing happens unless they make it happen. vier-desktop and vier-ios are run by a host, and they wait to be called.
The second is how waiting works. vier-cli waits by reading a line, which is
fine in a terminal. vier-desktop can’t wait, so it turns every pause into data,
a time and a step, and checks it on every frame. vier-ios waits with await,
and lets Swift keep the time and the step for it.
The third is when the screen is drawn. vier-cli prints when it’s done a move, vier-desktop draws every frame, and vier-ios draws when the game changes. All three draw from the game, and none of them keeps a picture of the board that could disagree with it.
Along the way you met each language’s own ideas, and they turned out to be
fewer than the lines of code suggested: Go’s zero values, pointers and
two-value returns, Rust’s borrowing, closures and traits, and Swift’s
Optionals, classes and await. Each time, you found the idea by asking what
lux idea it stood next to.
That’s how you read any program, not only these three. Find out what it does before you open it. Find the board and the rules, whatever they’re called in that program: the data, and the functions that change it. Find who runs the loop and how a click or a keypress gets in. Read the test names. Then follow one action through, from the person to the data and back to the screen, and skip whatever isn’t on that route. You won’t understand every line, and you don’t need to.
When you want to write programs like these, and not only read them, the next step is to learn one of the three languages properly. Programming in Go, Programming in Rust and Programming in Swift each have a note at the start for readers coming from lux. Whichever you choose, bring the map.