2. The board
Pip: Welcome back! Last time the board got its size. Today it gets 25 cells, and you get to tap them.
In chapter 1 the board was three numbers. In this chapter it becomes a type of its own. You write a Board that holds 25 cells, knows which cells a tap changes, and can tell when it’s clear. Along the way you write your first functions and variables, and you meet the compiler at its most helpful.
You will end with a Board type in the rules crate that taps exactly like the game, and eight passing tests that prove it.
A type for the board
Open core/src/board.rs. Below the three constants, add this:
/// A 5x5 board of values 0 to 3. Cell index is `row * 5 + column`.
pub struct Board {
cells: [u8; CELL_COUNT],
}
struct declares a struct, a type made of named fields. Board has one field, cells. pub makes the type visible outside the board module. A line that starts with /// documents the item below it, the way //! documents the whole crate.
[u8; CELL_COUNT] is an array, a fixed number of values of one type, stored side by side. This one holds 25 u8s, one per cell, in the row-major order from chapter 1. The length is part of the array’s type, so a Board always has exactly 25 cells. Nobody can add a 26th or lose one.
Why is cells private?
The field has no pub, so only the code in board.rs can touch it. That’s on purpose. A cell must hold 0, 1, 2 or 3. If any code anywhere could write to cells, any code could put a 7 there. With the field private, the board’s own code is the only code that changes cells, and that code is small enough to test completely.
Pip: Think of it as the board looking after its own tiles. You ask it to tap, and it does the arithmetic. You never reach in and turn a tile yourself.
How do you make a board?
A type needs a way to make one. Add this below the struct:
impl Board {
/// A clear board, where every cell is 0.
pub fn new() -> Board {
Board {
cells: [0; CELL_COUNT],
}
}
}
impl Board { ... } holds the code that belongs to Board. Inside it, fn declares a function. A function has a name, takes arguments in the brackets after its name, and can give back a value. This one is called new. It takes no arguments, and -> Board says it gives back a Board.
The body builds that board. Board { cells: ... } makes a Board by giving each field a value, and [0; CELL_COUNT] is an array of 25 zeros. There’s no return anywhere. In Rust, the last expression in a function is the value it returns, as long as no semicolon follows it.
You call it as Board::new(), because new belongs to the type Board. Naming the function that makes a fresh value new is a Rust habit, not a rule. You’ll meet Vec::new() later in this chapter.
Pip: That missing semicolon matters. I once put one after the closing brace of
Board { ... }, and the compiler stopped me right there.
error[E0308]: mismatched types
--> core/src/board.rs:12:21
|
12 | pub fn new() -> Board {
| --- ^^^^^ expected `Board`, found `()`
| |
| implicitly returns `()` as its body has no tail or `return` expression
...
15 | };
| - help: remove this semicolon to return this value
A semicolon turns the last line into a statement, and a statement gives back nothing. Rust writes nothing as (). So the function promised a Board and returned (), and the last line of the message says how to fix it.
Now let the rest of the world see the new type. In core/src/lib.rs, add Board to the pub use line:
pub use board::{Board, CELL_COUNT, MODULUS, SIZE};
Run the tests:
cargo test
Both tests from chapter 1 still pass, but first cargo makes a remark:
warning: field `cells` is never read
--> core/src/board.rs:7:5
|
6 | pub struct Board {
| ----- field in this struct
7 | cells: [u8; CELL_COUNT],
| ^^^^^
A warning isn’t an error, so everything still builds. The compiler is pointing at code that does nothing yet. The board has cells, and nothing ever looks at them. Let’s fix that.
Read a cell
Inside impl Board, below new, add this:
pub fn cell(&self, index: usize) -> u8 {
self.cells[index]
}
cell is a method, a function that works on one particular board. Its first argument, self, is the board it’s called on. You call a method with a dot. board.cell(13) gives the value in cell 13 of board. self.cells[index] looks up one value in the array, and it’s the last expression, so it’s what cell returns.
The & in &self makes it a reference. The method borrows the board to look at it, and gives it back when it returns. Nothing is copied, and the board stays where it was. A method that only reads a board takes &self.
new has no self, because there’s no board yet when you call it. That’s why new is called on the type, as Board::new(), and cell on a value, as board.cell(13).
Now a test that uses both. Add it to the tests module, below the two tests from chapter 1:
#[test]
fn a_new_board_is_clear() {
let board = Board::new();
for index in 0..CELL_COUNT {
assert_eq!(board.cell(index), 0);
}
}
let board = Board::new(); makes a variable called board and puts a new board in it. Rust works out the variable’s type from the right-hand side, so you don’t write it. A variable made with plain let can’t change. That’s Rust’s default, and you’ll see how to ask for one that can change soon.
0..CELL_COUNT counts from 0 up to 24. It stops just before 25, so the loop checks each of the 25 cells once. Run the tests:
cargo test
running 3 tests
test board::tests::a_new_board_is_clear ... ok
test board::tests::a_value_wraps_from_3_back_to_0 ... ok
test board::tests::the_board_has_25_cells ... ok
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Three tests pass, and the warning is gone, because cell reads the field.
What happens if you read past the last cell?
Try it. In the test, change 0..CELL_COUNT to 0..=CELL_COUNT. The = makes the range include 25, so the last pass asks for cell 25 of a board whose cells go up to 24. Run cargo test:
test board::tests::a_new_board_is_clear ... FAILED
...
thread 'board::tests::a_new_board_is_clear' (1126579) panicked at core/src/board.rs:19:9:
index out of bounds: the len is 25 but the index is 25
The test stopped with a panic. Rust panics when something happens that must never happen, and reading past the end of an array is one of those things. Some languages would hand back whatever happens to sit in memory after the array. Rust checks every index and stops instead, with the file and line where it happened. The number in brackets identifies the thread that ran the test, and yours will be different.
Change 0..=CELL_COUNT back to 0..CELL_COUNT before you go on.
Pip: A crash that names the exact line is a gift. The bugs that hurt are the ones that carry on quietly with a wrong number.
Which cells does a tap touch?
A tap changes the tapped cell and its neighbours above, below, left and right. On the edges there are fewer neighbours, so a tap has three possible shapes:
Let’s call the cells a tap changes its group. Add a function that works out the group of any cell. Put it inside impl Board, between new and cell:
/// The cells touched by a tap at `index`. That is the cell itself plus
/// its orthogonal neighbours, in index order. Edges do not wrap.
pub fn group(index: usize) -> Vec<usize> {
let row = index / SIZE;
let column = index % SIZE;
let mut group = Vec::new();
if row > 0 {
group.push(index - SIZE);
}
if column > 0 {
group.push(index - 1);
}
group.push(index);
if column < SIZE - 1 {
group.push(index + 1);
}
if row < SIZE - 1 {
group.push(index + SIZE);
}
group
}
Here’s what each part does:
grouphas noself, likenew. It doesn’t need a board to know which cells sit next to each other, only an index. You call it asBoard::group(12).let rowandlet columnturn the index back into a row and a column, with the division and remainder from chapter 1.Vec<usize>is a vector, a list that can grow.Vec::new()makes an empty one. A group holds 3, 4 or 5 cells, so an array, with its fixed length, won’t do.let mut groupmakes a variable that can change. This is the one I promised. Withoutmut, Rust wouldn’t letpushadd to it.- Each
ifadds one neighbour, but only if that neighbour exists.row > 0means there’s a row above, andcolumn < SIZE - 1means there’s a column to the right.pushadds an item to the end of the vector. - The last line,
group, has no semicolon, so the vector is what the function returns.
group adds the cells in index order: above, left, the cell itself, right, below. Any order would tap the same cells. A fixed order means a test can compare the whole list in one go. Add this test below a_new_board_is_clear:
#[test]
fn group_sizes_and_edges() {
assert_eq!(Board::group(0), vec![0, 1, 5]);
assert_eq!(Board::group(24), vec![19, 23, 24]);
assert_eq!(Board::group(2), vec![1, 2, 3, 7]);
assert_eq!(Board::group(14), vec![9, 13, 14, 19]);
assert_eq!(Board::group(12), vec![7, 11, 12, 13, 17]);
}
vec![0, 1, 5] is a macro that makes a vector holding those items. Each line compares a group with the list you expect. Together they check two corners, two edges and the middle. Run cargo test:
running 4 tests
test board::tests::a_value_wraps_from_3_back_to_0 ... ok
test board::tests::group_sizes_and_edges ... ok
test board::tests::the_board_has_25_cells ... ok
test board::tests::a_new_board_is_clear ... ok
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Why doesn’t the board wrap around?
In some games, walking off the right edge brings you back on the left. Not in Plus Out. Cell 9 sits on the right edge, and cell 10 starts the next row. They’re next to each other in the array, but not on the board. The check column < SIZE - 1 is what stops a tap on cell 9 from spilling into cell 10.
Go deeper: what if the top-row check is missing?
Delete the line if row > 0 { and its closing brace, so group always pushes index - SIZE. Then run cargo test:
thread 'board::tests::group_sizes_and_edges' (1126851) panicked at core/src/board.rs:24:20:
attempt to subtract with overflow
For cell 0, index - SIZE is 0 minus 5. A usize can’t be negative, so there’s no right answer, and in a test build Rust panics rather than guess. An optimised build skips that check to save time, and the number wraps around to a huge usize, an index far past the end of the board. The if checks keep every subtraction at zero or above, so neither can happen. Put the check back before you go on.
Tap
Now the tap itself. Add this method at the end of impl Board, below cell:
/// Adds 1 (mod 4) to the plus-shaped group.
pub fn tap(&mut self, index: usize) {
for i in Board::group(index) {
self.cells[i] = (self.cells[i] + 1) % MODULUS;
}
}
for i in Board::group(index) runs the body once for each cell in the group, with i holding that cell’s index. The body adds 1 to the cell and takes the remainder by MODULUS. That’s the wrap-around you tested in chapter 1.
This method takes &mut self instead of &self. &mut makes a mutable reference, which borrows the board in order to change it. Rust lets many parts of your code borrow a value to read it, or one part borrow it to change it, but never both at the same time. The compiler checks that rule before your code ever runs. It’s what stops one piece of code from changing a board while another is halfway through reading it.
To call tap, the board has to be in a variable that can change, made with let mut. You’ll see that in the tests in the next section.
How many cells are left?
You win a board when every cell is 0. Two methods answer that question. Add them inside impl Board, between cell and tap:
pub fn is_clear(&self) -> bool {
self.non_zero_count() == 0
}
pub fn non_zero_count(&self) -> usize {
let mut count = 0;
for value in self.cells {
if value != 0 {
count += 1;
}
}
count
}
non_zero_count counts the cells that aren’t 0. count starts at 0, and it’s made with let mut because it changes. for value in self.cells goes through the 25 values one by one, and count += 1 adds 1 for every value that isn’t 0. The last line returns the count.
is_clear returns a bool, which is either true or false. self.non_zero_count() == 0 is true exactly when no cell is left. A method can call another method on the same board through self.
A new board should be clear, so add one line to a_new_board_is_clear, after the loop:
assert!(board.is_clear());
assert! checks that one condition is true. It’s the simpler form of assert_eq!.
Now test the tap. Add these three tests below group_sizes_and_edges:
#[test]
fn corner_tap_changes_only_three_cells() {
let mut board = Board::new();
board.tap(0);
assert_eq!(board.non_zero_count(), 3);
assert_eq!(board.cell(0), 1);
assert_eq!(board.cell(1), 1);
assert_eq!(board.cell(5), 1);
}
#[test]
fn right_edge_does_not_wrap() {
let mut board = Board::new();
board.tap(9);
assert_eq!(board.non_zero_count(), 4);
assert_eq!(board.cell(10), 0);
}
#[test]
fn a_cell_counts_1_2_3_then_0() {
let mut board = Board::new();
let mut seen = Vec::new();
for _ in 0..5 {
board.tap(12);
seen.push(board.cell(12));
}
assert_eq!(seen, vec![1, 2, 3, 0, 1]);
}
corner_tap_changes_only_three_cellstaps cell 0 and checks that exactly three cells went up, and that they’re cells 0, 1 and 5.right_edge_does_not_wraptaps cell 9 on the right edge. Four cells change, and cell 10, at the start of the next row, stays 0.a_cell_counts_1_2_3_then_0taps the middle five times and writes down the middle cell’s value after each tap.for _ in 0..5repeats its body five times. The_stands for a value you don’t need, here the number of the round.
Run cargo test:
running 7 tests
test board::tests::a_value_wraps_from_3_back_to_0 ... ok
test board::tests::a_cell_counts_1_2_3_then_0 ... ok
test board::tests::a_new_board_is_clear ... ok
test board::tests::corner_tap_changes_only_three_cells ... ok
test board::tests::right_edge_does_not_wrap ... ok
test board::tests::the_board_has_25_cells ... ok
test board::tests::group_sizes_and_edges ... ok
test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Pip: Seven tests! Every rule of a tap from chapter 1 is now checked by code: the plus shape, the short edges and the wrap from 3 to 0.
Four taps change nothing
Pip: Here’s a fact you can use on any Plus Out board. Tap the same cell four times, and the board is back where it started. Can you see why before you read on?
Every cell in the group goes up by 4, and 4 wraps around to 0. Let’s prove it for every cell at once. Add this test at the end of the tests module:
#[test]
fn tapping_four_times_restores_board() {
let mut start = Board::new();
for index in [0, 7, 12, 12, 18, 24] {
start.tap(index);
}
for index in 0..CELL_COUNT {
let mut board = start;
for _ in 0..4 {
board.tap(index);
}
assert_eq!(board, start);
}
}
The test taps a few cells to make a board that isn’t clear, and keeps it in start. [0, 7, 12, 12, 18, 24] is an array written out in place, and the first loop taps each of those cells once, so cell 12 gets two taps. Then, for each of the 25 cells, the test copies start into board, taps that cell four times, and checks that board equals start again.
Run cargo test. This time the code doesn’t even compile:
error[E0369]: binary operation `==` cannot be applied to type `board::Board`
--> core/src/board.rs:138:13
|
138 | assert_eq!(board, start);
| ^^^^^^^^^^^^^^^^^^^^^^^^
...
help: consider annotating `board::Board` with `#[derive(PartialEq)]`
...
error[E0277]: `board::Board` doesn't implement `Debug`
...
help: consider annotating `board::Board` with `#[derive(Debug)]`
assert_eq! needs two things from the values it compares. It compares them with ==, and when they differ, it prints them. Rust doesn’t assume that a new type can do either. You have to say so.
In Rust, these abilities are traits. A trait is a set of abilities a type can have, each written as a function the type provides. PartialEq is the ability to be compared with ==. Debug is the ability to be printed for a programmer to read. You could write the code for both by hand, but for most types the obvious code is the right code, so Rust writes it for you when you ask with the attribute #[derive(...)]. The compiler’s help suggests exactly that. Add the attribute above the struct:
#[derive(Debug, PartialEq)]
pub struct Board {
Run cargo test again. One error is left, and it’s a new one:
error[E0382]: use of moved value: `start`
--> core/src/board.rs:135:29
|
130 | let mut start = Board::new();
| --------- move occurs because `start` has type `board::Board`, which does not implement the `Copy` trait
...
134 | for index in 0..CELL_COUNT {
| -------------------------- inside of this loop
135 | let mut board = start;
| ^^^^^ value moved here, in previous iteration of loop
let mut board = start; doesn’t copy the board. It moves it. After the move, the board belongs to board, and start can’t be used any more. The first pass through the loop works. The second finds nothing left in start to move, and Rust catches that before the code ever runs.
A board is just 25 small numbers, so copying one is cheap. Add two more traits to the derive. Clone is the ability to be duplicated, and Copy tells Rust to duplicate the value instead of moving it:
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Board {
Now let mut board = start; makes a fresh copy every time round the loop, and start stays as it was. Run cargo test:
running 8 tests
test board::tests::a_new_board_is_clear ... ok
test board::tests::a_value_wraps_from_3_back_to_0 ... ok
test board::tests::group_sizes_and_edges ... ok
test board::tests::right_edge_does_not_wrap ... ok
test board::tests::corner_tap_changes_only_three_cells ... ok
test board::tests::a_cell_counts_1_2_3_then_0 ... ok
test board::tests::the_board_has_25_cells ... ok
test board::tests::tapping_four_times_restores_board ... ok
test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
That last test tapped every cell of the board four times, 100 taps in all, and found no difference.
Go deeper: why doesn't Rust copy everything?
Some values own memory somewhere else. A Vec keeps its items in a block of memory it asked for, and the Vec value itself only holds where that block is, how long it is, and how much room it has. Copying those three numbers would give you two vectors pointing at one block, and both would try to give the block back when they’re done with it. So a Vec moves by default, and you call .clone() when you really want a second copy of every item.
A Board holds its 25 cells inside itself, in the array, and owns nothing anywhere else. Copying it bit for bit gives a complete, independent board, which is what makes Copy safe for it. The compiler allows Copy on a type only when every one of its fields can be copied too.
Tidy up
Run the two tools from chapter 1:
cargo fmt
cargo clippy
cargo fmt prints nothing, as before. cargo clippy has a suggestion this time:
warning: you should consider adding a `Default` implementation for `Board`
--> core/src/board.rs:13:5
|
13 | / pub fn new() -> Board {
14 | | Board {
15 | | cells: [0; CELL_COUNT],
16 | | }
17 | | }
| |_____^
|
...
help: try adding this
|
65 ~ }
66 +
67 + impl Default for Board {
68 + fn default() -> Self {
69 + Self::new()
70 + }
71 + }
Default is a trait from Rust’s standard library. A type with Default has a sensible starting value, and code that needs a fresh one of something asks for it through Default. A function called new that takes no arguments makes exactly such a value, so clippy suggests offering it as Default too.
This time you write a trait’s code by hand. Add this below impl Board, above the tests:
impl Default for Board {
fn default() -> Board {
Board::new()
}
}
impl Default for Board says that Board has the Default ability, and the block gives the trait’s one function. A board’s default is a new, clear board. Clippy’s version writes Self, which means the type the impl is for. Both mean the same thing. This series writes the type’s name, so you can always see which type a line is about.
Run cargo clippy again, and it only reports that it finished. Commit your work:
git add .
git commit -m "Give the rules crate a Board that taps"
Make it yours
Two small challenges to try on your own. Chapter 3 works the same with or without them.
- Two taps side by side. On a clear board, tap cell 12 and then cell 13. Which cells hold a 2, and how many cells aren’t 0? Work it out with the diagram first, then write a test that checks your answer.
- Chapter 1’s puzzle, in code. Chapter 1 asked how to clear a board that holds five 3s in a plus around the middle. Write a test that builds that board with taps, checks that it’s the board you meant, and clears it with a single tap.
Show the answers
-
Cells 12 and 13 hold 2, because each one is in both groups. Eight cells aren’t 0: cells 7, 11, 12, 13 and 17 from the first tap, plus cells 8, 14 and 18 from the second.
#[test] fn two_taps_side_by_side() { let mut board = Board::new(); board.tap(12); board.tap(13); assert_eq!(board.cell(12), 2); assert_eq!(board.cell(13), 2); assert_eq!(board.non_zero_count(), 8); } -
Three taps on cell 12 raise its whole group to 3, and a fourth tap wraps all five cells back to 0.
#[test] fn one_tap_clears_a_plus_of_3s() { let mut board = Board::new(); for _ in 0..3 { board.tap(12); } assert_eq!(board.non_zero_count(), 5); assert_eq!(board.cell(12), 3); board.tap(12); assert!(board.is_clear()); }It’s the four-taps fact again, seen from the other side. Three taps build the plus, and the fourth undoes all three.
Recap
Boardis a struct with one private field, an array of 25 cells. Only its own methods change them.- A function is declared with
fn, and its last expression, written without a semicolon, is the value it returns.Board::new()andBoard::group(index)belong to the type. Methods such asboard.tap(index)work on one board throughself. letmakes a variable that can’t change, andlet mutmakes one that can.&selfborrows a board to read it, and&mut selfborrows it to change it.groupreturns a vector of the cells a tap touches, with no wrapping at the edges.tapadds 1 to each of them, mod 4.- Traits are abilities.
#[derive(Clone, Copy, Debug, PartialEq)]lets the tests copy, compare and print boards, andimpl Default for Boardwrites a trait’s code by hand. - Eight tests check the corners, the edges, the wrap-around, and that four taps leave any board as it was.
The finished code for this chapter is in steps/02-the-board. If something behaves differently on your machine, compare your files with those.
Pip: That’s a real board! It taps exactly like the game, and you’ve proved it. In the next chapter it gets something worth tapping: real puzzles, each with only so many taps to clear it.