diff --git a/apps/tetris/Cargo.toml b/apps/tetris/Cargo.toml
new file mode 100644
index 0000000..bd20d9f
--- /dev/null
+++ b/apps/tetris/Cargo.toml
@@ -0,0 +1,13 @@
+[package]
+name = "tetris"
+edition.workspace = true
+license.workspace = true
+version.workspace = true
+
+[dependencies]
+cmf-wp2-app.workspace = true
+cmf-wp2-ui.workspace = true
+
+[[bin]]
+name = "tetris"
+bench = false
diff --git a/apps/tetris/icon.svg b/apps/tetris/icon.svg
new file mode 100644
index 0000000..4444f9d
--- /dev/null
+++ b/apps/tetris/icon.svg
@@ -0,0 +1,29 @@
+
diff --git a/apps/tetris/shots/over.png b/apps/tetris/shots/over.png
new file mode 100644
index 0000000..f1230b9
Binary files /dev/null and b/apps/tetris/shots/over.png differ
diff --git a/apps/tetris/shots/playing.png b/apps/tetris/shots/playing.png
new file mode 100644
index 0000000..1dfd8c5
Binary files /dev/null and b/apps/tetris/shots/playing.png differ
diff --git a/apps/tetris/shots/ready.png b/apps/tetris/shots/ready.png
new file mode 100644
index 0000000..3ecb3ab
Binary files /dev/null and b/apps/tetris/shots/ready.png differ
diff --git a/apps/tetris/src/game.rs b/apps/tetris/src/game.rs
new file mode 100644
index 0000000..82a6823
--- /dev/null
+++ b/apps/tetris/src/game.rs
@@ -0,0 +1,816 @@
+// The game itself: no Api, so `cargo test` runs it on the host. Time comes in as `now` (ms, wrapping), so the game
+// never sleeps and never needs a fixed tick: `wake_in` says when something is next due, `tick` does it.
+
+/// The well: 10 columns, 20 rows. Row 0 is the top.
+pub const W: usize = 10;
+pub const H: usize = 20;
+
+/// Piece kinds, in the order of their colours: I O T S Z J L.
+pub const KINDS: u8 = 7;
+const I: u8 = 0;
+const O: u8 = 1;
+
+/// Milliseconds per row at levels 1..=20 (the last one holds from then on).
+const GRAVITY: [u32; 20] = [800, 720, 630, 550, 470, 380, 300, 220, 130, 100, 83, 83, 83, 67, 67, 67, 50, 50, 50, 33];
+/// Milliseconds per row while the finger is held on the screen.
+pub const SOFT_MS: u32 = 45;
+/// A piece that has landed can still be pushed around for this long; moving it gives the time back, 12 times at most.
+pub const LOCK_MS: u32 = 500;
+const SOFT_LOCK_MS: u32 = 120;
+const MAX_RESETS: u8 = 12;
+/// Cleared rows blink: this many steps of this many ms (odd steps are white), then they are gone.
+pub const FLASH_STEPS: u8 = 6;
+pub const FLASH_MS: u32 = 70;
+/// Rows cleared at once: 1, 2, 3, 4. Times the level.
+const LINE_POINTS: [u32; 5] = [0, 100, 300, 500, 800];
+/// A score the HUD can show.
+pub const SCORE_MAX: u32 = 999_999;
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum State {
+ /// Title screen, waiting for a tap.
+ Ready,
+ Playing,
+ /// The stack reached the top.
+ Over,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum Step {
+ Nothing,
+ /// A piece came to rest and joined the stack.
+ Locked,
+ /// A piece joined the stack and this many rows (1..=4) are going.
+ Cleared(u8),
+ Crashed,
+}
+
+/// A piece: its kind, how often it is turned clockwise (0..=3) and where the top left of its 4x4 box is. `y` can be
+/// negative: the I piece spawns with its box one row above the well.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub struct Piece {
+ pub kind: u8,
+ pub rot: u8,
+ pub x: i32,
+ pub y: i32,
+}
+
+/// The cells of each kind turned 0 times, in its box (the standard layout).
+const BASE: [[(i32, i32); 4]; 7] = [
+ [(0, 1), (1, 1), (2, 1), (3, 1)], // I
+ [(1, 0), (2, 0), (1, 1), (2, 1)], // O
+ [(1, 0), (0, 1), (1, 1), (2, 1)], // T
+ [(1, 0), (2, 0), (0, 1), (1, 1)], // S
+ [(0, 0), (1, 0), (1, 1), (2, 1)], // Z
+ [(0, 0), (0, 1), (1, 1), (2, 1)], // J
+ [(2, 0), (0, 1), (1, 1), (2, 1)], // L
+];
+
+/// The four cells of a kind turned `rot` times clockwise, relative to its box.
+pub fn shape(kind: u8, rot: u8) -> [(i32, i32); 4] {
+ let mut c = BASE[kind as usize % KINDS as usize];
+ if kind == O {
+ return c; // a square looks the same from every side
+ }
+ let n = if kind == I { 4 } else { 3 };
+ for _ in 0..rot % 4 {
+ for p in c.iter_mut() {
+ *p = (n - 1 - p.1, p.0);
+ }
+ }
+ c
+}
+
+impl Piece {
+ /// Where its cells are in the well.
+ pub fn cells(&self) -> [(i32, i32); 4] {
+ shape(self.kind, self.rot).map(|(x, y)| (self.x + x, self.y + y))
+ }
+}
+
+/// Where a turned piece may go if it does not fit where it is: sideways, then up.
+const KICKS: [(i32, i32); 8] = [(0, 0), (-1, 0), (1, 0), (-2, 0), (2, 0), (0, -1), (-1, -1), (1, -1)];
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub struct Flash {
+ /// Bit `y` is set for each full row.
+ pub rows: u32,
+ pub step: u8,
+ at: u32,
+}
+
+impl Flash {
+ /// Rows show white on odd steps.
+ pub fn lit(&self) -> bool {
+ self.step % 2 == 1
+ }
+}
+
+#[derive(Clone)]
+pub struct Game {
+ pub state: State,
+ /// 0 = empty, else the kind + 1 of the piece that left it there.
+ pub board: [[u8; W]; H],
+ /// The falling piece; `None` while rows blink.
+ pub cur: Option,
+ pub next: u8,
+ pub score: u32,
+ pub lines: u32,
+ pub flash: Option,
+ soft: bool,
+ drop_at: u32,
+ lock_at: Option,
+ resets: u8,
+ bag: [u8; 7],
+ bag_at: usize,
+ rng: u32,
+}
+
+pub fn due(now: u32, at: u32) -> bool {
+ (now.wrapping_sub(at) as i32) >= 0
+}
+
+fn until(now: u32, at: u32) -> u32 {
+ if due(now, at) { 0 } else { at.wrapping_sub(now) }
+}
+
+/// xorshift32: no random source on the watch, the app seeds it from the clock.
+fn next(rng: &mut u32) -> u32 {
+ let mut x = *rng;
+ x ^= x << 13;
+ x ^= x >> 17;
+ x ^= x << 5;
+ *rng = x;
+ x
+}
+
+impl Game {
+ pub fn new(seed: u32) -> Game {
+ Game {
+ state: State::Ready,
+ board: [[0; W]; H],
+ cur: None,
+ next: 0,
+ score: 0,
+ lines: 0,
+ flash: None,
+ soft: false,
+ drop_at: 0,
+ lock_at: None,
+ resets: 0,
+ bag: [0, 1, 2, 3, 4, 5, 6],
+ bag_at: 7,
+ rng: seed | 1,
+ }
+ }
+
+ pub fn level(&self) -> u32 {
+ (self.lines / 10).min(19)
+ }
+
+ /// Time between two falls of one row now.
+ pub fn interval(&self) -> u32 {
+ let g = GRAVITY[self.level() as usize];
+ if self.soft { g.min(SOFT_MS) } else { g }
+ }
+
+ /// The next piece of the bag; every seven draws hold each kind once.
+ fn draw(&mut self) -> u8 {
+ if self.bag_at >= 7 {
+ for i in (1..7).rev() {
+ let j = (next(&mut self.rng) % (i as u32 + 1)) as usize;
+ self.bag.swap(i, j);
+ }
+ self.bag_at = 0;
+ }
+ self.bag_at += 1;
+ self.bag[self.bag_at - 1]
+ }
+
+ /// A new game, the first piece falling.
+ pub fn start(&mut self, now: u32) {
+ self.board = [[0; W]; H];
+ self.score = 0;
+ self.lines = 0;
+ self.flash = None;
+ self.soft = false;
+ self.state = State::Playing;
+ self.bag_at = 7;
+ self.next = self.draw();
+ self.spawn(now);
+ }
+
+ pub fn fits(&self, p: &Piece) -> bool {
+ p.cells().iter().all(|&(x, y)| x >= 0 && x < W as i32 && y < H as i32 && (y < 0 || self.board[y as usize][x as usize] == 0))
+ }
+
+ /// The next piece comes in at the top. `false`: no room, the game is over.
+ fn spawn(&mut self, now: u32) -> bool {
+ let kind = self.next;
+ self.next = self.draw();
+ let p = Piece { kind, rot: 0, x: 3, y: if kind == I { -1 } else { 0 } };
+ self.cur = Some(p);
+ self.drop_at = now.wrapping_add(self.interval());
+ self.lock_at = None;
+ self.resets = 0;
+ if self.fits(&p) {
+ true
+ } else {
+ self.state = State::Over;
+ false
+ }
+ }
+
+ /// The piece can not fall further.
+ pub fn resting(&self) -> bool {
+ self.cur.is_some_and(|p| !self.fits(&Piece { y: p.y + 1, ..p }))
+ }
+
+ fn lock_delay(&self) -> u32 {
+ if self.soft { SOFT_LOCK_MS } else { LOCK_MS }
+ }
+
+ /// After the piece moved or turned (`by_hand`) or fell: start, restart or cancel the lock timer.
+ fn settle(&mut self, now: u32, by_hand: bool) {
+ let delay = self.lock_delay();
+ if !self.resting() {
+ if self.lock_at.take().is_some() {
+ self.drop_at = now.wrapping_add(self.interval()); // slid off the edge: it falls on
+ }
+ } else if self.lock_at.is_none() {
+ self.lock_at = Some(now.wrapping_add(delay));
+ } else if by_hand && self.resets < MAX_RESETS {
+ self.resets += 1;
+ self.lock_at = Some(now.wrapping_add(delay));
+ }
+ }
+
+ /// One column left (-1) or right (+1).
+ pub fn shift(&mut self, dx: i32, now: u32) -> bool {
+ let Some(p) = self.cur.filter(|_| self.state == State::Playing && self.flash.is_none()) else { return false };
+ let q = Piece { x: p.x + dx, ..p };
+ if !self.fits(&q) {
+ return false;
+ }
+ self.cur = Some(q);
+ self.settle(now, true);
+ true
+ }
+
+ /// A quarter turn clockwise, pushed aside or up if the wall or the stack is in the way.
+ pub fn turn(&mut self, now: u32) -> bool {
+ let Some(p) = self.cur.filter(|_| self.state == State::Playing && self.flash.is_none()) else { return false };
+ if p.kind == O {
+ return false;
+ }
+ for (dx, dy) in KICKS {
+ let q = Piece { rot: (p.rot + 1) % 4, x: p.x + dx, y: p.y + dy, ..p };
+ if self.fits(&q) {
+ self.cur = Some(q);
+ self.settle(now, true);
+ return true;
+ }
+ }
+ false
+ }
+
+ /// The finger is on (`true`) or off the screen: the piece falls faster while it is on.
+ pub fn set_soft(&mut self, on: bool, now: u32) {
+ if on == self.soft {
+ return;
+ }
+ self.soft = on;
+ if self.state != State::Playing || self.flash.is_some() {
+ return;
+ }
+ if on {
+ if until(now, self.drop_at) > SOFT_MS {
+ self.drop_at = now.wrapping_add(SOFT_MS); // the first row comes soon, not after the long wait
+ }
+ if let Some(l) = self.lock_at {
+ self.lock_at = Some(if until(now, l) > SOFT_LOCK_MS { now.wrapping_add(SOFT_LOCK_MS) } else { l });
+ }
+ } else {
+ self.drop_at = now.wrapping_add(self.interval());
+ }
+ }
+
+ /// Where the piece would land.
+ pub fn ghost(&self) -> Option {
+ let mut p = self.cur?;
+ while self.fits(&Piece { y: p.y + 1, ..p }) {
+ p.y += 1;
+ }
+ Some(p)
+ }
+
+ /// Milliseconds until `tick` has something to do; `None`: nothing is due, wait for input.
+ pub fn wake_in(&self, now: u32) -> Option {
+ if let Some(f) = self.flash {
+ return Some(until(now, f.at));
+ }
+ if self.state != State::Playing || self.cur.is_none() {
+ return None;
+ }
+ Some(if self.resting() { until(now, self.lock_at.unwrap_or(now)) } else { until(now, self.drop_at) })
+ }
+
+ /// After a pause: nothing is overdue, and the finger is off.
+ pub fn rebase(&mut self, now: u32) {
+ self.soft = false;
+ if let Some(f) = &mut self.flash {
+ f.at = now.wrapping_add(FLASH_MS);
+ }
+ if self.lock_at.is_some() {
+ self.lock_at = Some(now.wrapping_add(LOCK_MS));
+ }
+ self.drop_at = now.wrapping_add(self.interval());
+ }
+
+ /// Does what is due at `now`: one fall, the lock, or one blink.
+ pub fn tick(&mut self, now: u32) -> Step {
+ if let Some(mut f) = self.flash {
+ if !due(now, f.at) {
+ return Step::Nothing;
+ }
+ f.step += 1;
+ f.at = now.wrapping_add(FLASH_MS);
+ if f.step < FLASH_STEPS {
+ self.flash = Some(f);
+ return Step::Nothing;
+ }
+ self.flash = None;
+ self.remove(f.rows);
+ return if self.spawn(now) { Step::Nothing } else { Step::Crashed };
+ }
+ let Some(p) = self.cur.filter(|_| self.state == State::Playing) else { return Step::Nothing };
+ if self.resting() {
+ let at = *self.lock_at.get_or_insert(now.wrapping_add(self.lock_delay()));
+ return if due(now, at) { self.lock(now) } else { Step::Nothing };
+ }
+ if due(now, self.drop_at) {
+ self.cur = Some(Piece { y: p.y + 1, ..p });
+ if self.soft {
+ self.score = (self.score + 1).min(SCORE_MAX);
+ }
+ self.drop_at = now.wrapping_add(self.interval());
+ self.settle(now, false);
+ }
+ Step::Nothing
+ }
+
+ fn lock(&mut self, now: u32) -> Step {
+ let Some(p) = self.cur.take() else { return Step::Nothing };
+ let mut out = false;
+ for (x, y) in p.cells() {
+ if y < 0 {
+ out = true; // locked above the well
+ } else {
+ self.board[y as usize][x as usize] = p.kind + 1;
+ }
+ }
+ if out {
+ self.state = State::Over;
+ return Step::Crashed;
+ }
+ let rows = (0..H).filter(|&y| self.board[y].iter().all(|&c| c != 0)).fold(0u32, |m, y| m | 1 << y);
+ let n = rows.count_ones() as usize;
+ if n == 0 {
+ return if self.spawn(now) { Step::Locked } else { Step::Crashed };
+ }
+ self.score = (self.score + LINE_POINTS[n] * (self.level() + 1)).min(SCORE_MAX);
+ self.lines += n as u32;
+ self.flash = Some(Flash { rows, step: 0, at: now.wrapping_add(FLASH_MS) });
+ Step::Cleared(n as u8)
+ }
+
+ /// Takes the rows in `rows` out; what is above falls down.
+ fn remove(&mut self, rows: u32) {
+ let mut to = H;
+ for from in (0..H).rev() {
+ if rows >> from & 1 == 0 {
+ to -= 1;
+ self.board[to] = self.board[from];
+ }
+ }
+ for row in &mut self.board[..to] {
+ *row = [0; W];
+ }
+ }
+}
+
+pub const MAGIC: &[u8; 2] = b"T1";
+
+pub fn encode(best: u32) -> [u8; 6] {
+ let b = best.to_le_bytes();
+ [MAGIC[0], MAGIC[1], b[0], b[1], b[2], b[3]]
+}
+
+/// Anything that isn't a blob of ours is no best score yet.
+pub fn decode(blob: &[u8]) -> u32 {
+ match blob {
+ [b'T', b'1', a, b, c, d] => u32::from_le_bytes([*a, *b, *c, *d]).min(SCORE_MAX),
+ _ => 0,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn playing(seed: u32) -> Game {
+ let mut g = Game::new(seed);
+ g.start(0);
+ g
+ }
+
+ /// Runs the game's clock until `ms` have passed, in 1 ms steps like a worst case of tiny wake-ups.
+ fn run(g: &mut Game, from: u32, ms: u32) -> (u32, Vec) {
+ let mut seen = Vec::new();
+ for t in from..from + ms {
+ let s = g.tick(t);
+ if s != Step::Nothing {
+ seen.push(s);
+ }
+ }
+ (from + ms, seen)
+ }
+
+ #[test]
+ fn every_piece_has_four_cells_in_its_box_and_turns_back_after_four() {
+ for kind in 0..KINDS {
+ for rot in 0..4 {
+ let c = shape(kind, rot);
+ for (i, a) in c.iter().enumerate() {
+ assert!(a.0 >= 0 && a.0 < 4 && a.1 >= 0 && a.1 < 4, "kind {kind} rot {rot} {a:?}");
+ assert!(!c[i + 1..].contains(a), "kind {kind} rot {rot} repeats {a:?}");
+ }
+ }
+ assert_eq!(shape(kind, 4), shape(kind, 0));
+ }
+ }
+
+ #[test]
+ fn turning_keeps_the_pieces_shape() {
+ // T: three in a row and one on top, whatever the turn: one cell touches the three others
+ for rot in 0..4 {
+ let c = shape(2, rot);
+ let touching = |a: (i32, i32)| c.iter().filter(|b| (a.0 - b.0).abs() + (a.1 - b.1).abs() == 1).count();
+ assert_eq!(c.iter().map(|&a| touching(a)).max(), Some(3), "rot {rot}");
+ }
+ // I: a line of four, flat or standing
+ let flat = shape(0, 0);
+ assert!(flat.iter().all(|c| c.1 == 1));
+ let tall = shape(0, 1);
+ assert!(tall.iter().all(|c| c.0 == 2));
+ }
+
+ #[test]
+ fn the_bag_holds_each_kind_once_per_seven() {
+ let mut g = Game::new(99);
+ for _ in 0..20 {
+ let mut seen = [0; 7];
+ for _ in 0..7 {
+ seen[g.draw() as usize] += 1;
+ }
+ assert_eq!(seen, [1; 7]);
+ }
+ }
+
+ #[test]
+ fn every_kind_spawns_inside_the_well_and_fits() {
+ for kind in 0..KINDS {
+ let g = playing(5);
+ let p = Piece { kind, rot: 0, x: 3, y: if kind == I { -1 } else { 0 } };
+ assert!(g.fits(&p), "kind {kind}");
+ let top = p.cells().iter().map(|c| c.1).min().unwrap();
+ assert_eq!(top, 0, "kind {kind} shows from the first row");
+ }
+ }
+
+ #[test]
+ fn a_piece_falls_one_row_per_interval() {
+ let mut g = playing(1);
+ let y0 = g.cur.unwrap().y;
+ run(&mut g, 0, 799);
+ assert_eq!(g.cur.unwrap().y, y0);
+ run(&mut g, 799, 2);
+ assert_eq!(g.cur.unwrap().y, y0 + 1);
+ run(&mut g, 801, 800);
+ assert_eq!(g.cur.unwrap().y, y0 + 2);
+ assert_eq!(g.wake_in(1601).map(|w| w <= 800), Some(true));
+ }
+
+ #[test]
+ fn it_lands_waits_half_a_second_and_locks() {
+ let mut g = playing(3);
+ // let it fall to the floor
+ let mut t = 0;
+ while !g.resting() {
+ t += 1;
+ g.tick(t);
+ assert!(t < 30_000);
+ }
+ let landed = t;
+ let (_, steps) = run(&mut g, landed + 1, LOCK_MS - 2);
+ assert!(steps.is_empty(), "{steps:?}");
+ let (_, steps) = run(&mut g, landed + LOCK_MS - 1, 10);
+ assert_eq!(steps, vec![Step::Locked]);
+ assert!(g.board.iter().flatten().filter(|&&c| c != 0).count() == 4);
+ assert!(g.cur.is_some(), "the next piece is already in");
+ }
+
+ #[test]
+ fn walls_stop_the_piece_and_moves_into_them_say_so() {
+ let mut g = playing(7);
+ let mut n = 0;
+ while g.shift(-1, 0) {
+ n += 1;
+ assert!(n < 12);
+ }
+ assert!(g.cur.unwrap().cells().iter().any(|c| c.0 == 0));
+ assert!(!g.shift(-1, 0));
+ let mut m = 0;
+ while g.shift(1, 0) {
+ m += 1;
+ assert!(m < 20);
+ }
+ assert!(g.cur.unwrap().cells().iter().any(|c| c.0 == W as i32 - 1));
+ assert!(m >= 6);
+ }
+
+ #[test]
+ fn a_turn_next_to_the_wall_kicks_the_piece_back_in() {
+ // a standing I against the right wall turned flat would stick out: it is moved left
+ let mut g = playing(7);
+ g.cur = Some(Piece { kind: 0, rot: 1, x: 7, y: 5 }); // cells at x = 9
+ assert!(g.fits(&g.cur.unwrap()));
+ assert!(g.turn(0));
+ let p = g.cur.unwrap();
+ assert!(g.fits(&p));
+ assert_eq!(p.rot, 2);
+ assert!(p.cells().iter().all(|c| c.0 <= 9));
+ // the square does not turn at all
+ g.cur = Some(Piece { kind: 1, rot: 0, x: 3, y: 5 });
+ assert!(!g.turn(0));
+ }
+
+ #[test]
+ fn turning_is_refused_when_it_can_not_fit() {
+ let mut g = playing(7);
+ for y in 0..H {
+ for x in 0..W {
+ g.board[y][x] = 1;
+ }
+ }
+ // a one-cell-wide shaft, a flat I at the bottom of it
+ for y in 10..H {
+ g.board[y][4] = 0;
+ }
+ g.cur = Some(Piece { kind: 0, rot: 1, x: 2, y: 10 }); // standing in column 4
+ assert!(g.fits(&g.cur.unwrap()));
+ let before = g.cur;
+ assert!(!g.turn(0));
+ assert_eq!(g.cur, before);
+ }
+
+ #[test]
+ fn full_rows_blink_then_go_and_the_rest_falls() {
+ let mut g = playing(2);
+ // two full rows with a gap at column 0, and a single block on top of them
+ for y in H - 2..H {
+ for x in 1..W {
+ g.board[y][x] = 3;
+ }
+ }
+ g.board[H - 3][5] = 6;
+ // a vertical I to fill column 0: x = -2 puts its cells in column 0
+ g.cur = Some(Piece { kind: 0, rot: 1, x: -2, y: H as i32 - 4 });
+ assert!(g.fits(&g.cur.unwrap()));
+ let level = g.level();
+ let mut t = 0;
+ let mut got = None;
+ while got.is_none() && t < 5000 {
+ t += 1;
+ let s = g.tick(t);
+ if matches!(s, Step::Cleared(_)) {
+ got = Some(s);
+ }
+ }
+ assert_eq!(got, Some(Step::Cleared(2)));
+ assert_eq!(g.score, 300 * (level + 1));
+ assert_eq!(g.lines, 2);
+ let f = g.flash.unwrap();
+ assert_eq!(f.rows, 0b11 << (H - 2));
+ assert!(g.cur.is_none());
+ assert_eq!(g.wake_in(t), Some(FLASH_MS));
+ // the blink runs, the rows go
+ let mut lit = 0;
+ for _ in 0..FLASH_STEPS as u32 * FLASH_MS + 5 {
+ t += 1;
+ if g.flash.is_some_and(|f| f.lit()) {
+ lit += 1;
+ }
+ g.tick(t);
+ }
+ assert!(lit > 100, "the rows blinked white");
+ assert!(g.flash.is_none());
+ assert!(g.cur.is_some(), "the next piece is in");
+ // what was on top fell two rows: the single block and the top of the I piece (column 0) are at the bottom
+ assert_eq!(g.board[H - 1][5], 6);
+ assert_eq!(g.board[H - 1][0], 1);
+ assert_eq!(g.board[H - 2][0], 1);
+ assert_eq!(g.board[H - 1].iter().filter(|&&c| c != 0).count(), 2);
+ assert_eq!(g.board[H - 2].iter().filter(|&&c| c != 0).count(), 1);
+ assert!(g.board[..H - 2].iter().flatten().all(|&c| c == 0));
+ }
+
+ #[test]
+ fn a_tetris_scores_800_and_the_level_follows_the_lines() {
+ let mut g = playing(2);
+ for y in H - 4..H {
+ for x in 1..W {
+ g.board[y][x] = 2;
+ }
+ }
+ g.cur = Some(Piece { kind: 0, rot: 1, x: -2, y: H as i32 - 4 });
+ let mut t = 0;
+ loop {
+ t += 1;
+ if let Step::Cleared(n) = g.tick(t) {
+ assert_eq!(n, 4);
+ break;
+ }
+ assert!(t < 5000);
+ }
+ assert_eq!(g.score, 800);
+ g.lines = 9;
+ assert_eq!(g.level(), 0);
+ g.lines = 10;
+ assert_eq!(g.level(), 1);
+ g.lines = 10_000;
+ assert_eq!(g.level(), 19);
+ assert!(g.interval() == 33);
+ }
+
+ #[test]
+ fn holding_makes_it_fall_fast_and_scores_a_point_per_row() {
+ let mut g = playing(4);
+ let y0 = g.cur.unwrap().y;
+ g.set_soft(true, 10);
+ // first row after SOFT_MS, then one per SOFT_MS
+ run(&mut g, 10, SOFT_MS - 2);
+ assert_eq!(g.cur.unwrap().y, y0);
+ run(&mut g, 10 + SOFT_MS - 2, 3);
+ assert_eq!(g.cur.unwrap().y, y0 + 1);
+ run(&mut g, 10 + SOFT_MS + 1, 4 * SOFT_MS);
+ assert_eq!(g.cur.unwrap().y, y0 + 5);
+ assert_eq!(g.score, 5);
+ // letting go: back to the level's speed
+ let now = 10 + 5 * SOFT_MS + 1;
+ g.set_soft(false, now);
+ let y = g.cur.unwrap().y;
+ run(&mut g, now, 700);
+ assert_eq!(g.cur.unwrap().y, y);
+ run(&mut g, now + 700, 150);
+ assert_eq!(g.cur.unwrap().y, y + 1);
+ }
+
+ #[test]
+ fn a_piece_on_the_floor_can_be_slid_but_not_forever() {
+ let mut g = playing(3);
+ let mut t = 0;
+ while !g.resting() {
+ t += 1;
+ g.tick(t);
+ }
+ // slide every 400 ms: the timer restarts, up to the cap, then the piece locks anyway
+ let landed = t;
+ let mut left = true;
+ let mut locked_at = None;
+ for _ in 0..40 {
+ t += 400;
+ for k in 0..400 {
+ if g.tick(t - 400 + k) != Step::Nothing {
+ locked_at = Some(t - 400 + k);
+ break;
+ }
+ }
+ if locked_at.is_some() {
+ break;
+ }
+ if !g.shift(if left { -1 } else { 1 }, t) {
+ left = !left;
+ g.shift(if left { -1 } else { 1 }, t);
+ }
+ if !g.resting() {
+ break; // slid off the stack: fine for this test
+ }
+ }
+ let n = (locked_at.expect("it locks") - landed) / 400;
+ assert!(n >= 2 && n <= 2 + MAX_RESETS as u32 + 2, "{n}");
+ }
+
+ #[test]
+ fn a_full_stack_ends_the_game() {
+ let mut g = playing(8);
+ for y in 0..H {
+ for x in 0..W {
+ g.board[y][x] = if x == 0 { 0 } else { 1 };
+ }
+ }
+ // the next spawn has no room
+ g.board[0][0] = 1;
+ let mut t = 0;
+ let mut over = false;
+ while t < 3000 {
+ t += 1;
+ if g.tick(t) == Step::Crashed {
+ over = true;
+ break;
+ }
+ }
+ assert!(over);
+ assert_eq!(g.state, State::Over);
+ assert_eq!(g.wake_in(t), None);
+ assert!(!g.shift(1, t) && !g.turn(t));
+ }
+
+ #[test]
+ fn the_ghost_is_where_the_piece_lands() {
+ let mut g = playing(6);
+ let gh = g.ghost().unwrap();
+ assert!(g.fits(&gh));
+ assert!(!g.fits(&Piece { y: gh.y + 1, ..gh }));
+ assert_eq!((gh.kind, gh.rot, gh.x), (g.cur.unwrap().kind, g.cur.unwrap().rot, g.cur.unwrap().x));
+ g.board[H - 1] = [1; W];
+ let gh2 = g.ghost().unwrap();
+ assert_eq!(gh2.y, gh.y - 1);
+ }
+
+ #[test]
+ fn pausing_leaves_nothing_overdue() {
+ let mut g = playing(6);
+ let y = g.cur.unwrap().y;
+ g.rebase(1_000_000);
+ assert_eq!(g.tick(1_000_000), Step::Nothing);
+ assert_eq!(g.cur.unwrap().y, y);
+ assert!(g.wake_in(1_000_000).unwrap() > 700);
+ }
+
+ #[test]
+ fn the_clock_may_wrap() {
+ let mut g = Game::new(3);
+ g.start(u32::MAX - 100);
+ let y = g.cur.unwrap().y;
+ let mut t = u32::MAX - 100;
+ for _ in 0..900 {
+ t = t.wrapping_add(1);
+ g.tick(t);
+ }
+ assert_eq!(g.cur.unwrap().y, y + 1);
+ }
+
+ #[test]
+ fn best_score_blob_round_trips_and_rejects_junk() {
+ assert_eq!(decode(&encode(12345)), 12345);
+ assert_eq!(decode(&[]), 0);
+ assert_eq!(decode(b"SH1\x01\x00\x00\x00"), 0);
+ assert_eq!(decode(&encode(u32::MAX)), SCORE_MAX);
+ }
+
+ /// Whatever is pressed, the stack never holds more than the well and every piece stays on the board.
+ #[test]
+ fn random_play_keeps_the_rules() {
+ for seed in 1..40u32 {
+ let mut g = playing(seed);
+ let mut r = seed * 7919;
+ let mut t = 0u32;
+ for _ in 0..30_000 {
+ t += 7;
+ match next(&mut r) % 9 {
+ 0 => {
+ g.shift(-1, t);
+ }
+ 1 => {
+ g.shift(1, t);
+ }
+ 2 => {
+ g.turn(t);
+ }
+ 3 => g.set_soft(next(&mut r) % 2 == 0, t),
+ _ => {}
+ }
+ g.tick(t);
+ if let Some(p) = g.cur {
+ if g.state == State::Playing {
+ assert!(g.fits(&p), "seed {seed} t {t}");
+ }
+ }
+ if g.state == State::Over {
+ g.start(t);
+ }
+ }
+ }
+ }
+}
diff --git a/apps/tetris/src/main.rs b/apps/tetris/src/main.rs
new file mode 100644
index 0000000..c75593b
--- /dev/null
+++ b/apps/tetris/src/main.rs
@@ -0,0 +1,170 @@
+#![cfg_attr(any(target_os = "none", wp2_sim), no_main, cfg_attr(target_os = "none", no_std))]
+
+#[cfg_attr(not(any(target_os = "none", wp2_sim)), allow(dead_code))]
+mod game;
+#[cfg_attr(not(any(target_os = "none", wp2_sim)), allow(dead_code))]
+mod view;
+
+#[cfg(not(any(target_os = "none", wp2_sim)))]
+fn main() {}
+
+#[cfg(any(target_os = "none", wp2_sim))]
+mod device {
+ use crate::game::{Game, State, Step, decode, due, encode};
+ use crate::view::{frame, seen};
+ use cmf_wp2_app::{Api, BUTTON, CROWN, PAUSE, RESUME, TOUCH_DOWN, TOUCH_UP};
+ use cmf_wp2_ui::haptic::{DOUBLE, DONE, Motor, TICK};
+
+ cmf_wp2_app::entry!(main);
+ cmf_wp2_app::app_icon!();
+
+ /// A finger that stays on the glass this long is a hold (the piece drops fast), a shorter one is a tap (it turns).
+ const HOLD_MS: u32 = 220;
+ /// Taps right after the game ended don't start a new one: they were meant for the game that just ended.
+ const RETRY_MS: u32 = 700;
+ /// Turning the crown clockwise moves the piece right. Flip this if your watch counts the other way.
+ const CROWN_RIGHT: i16 = 1;
+
+ // true on RESUME, false on BUTTON
+ fn paused(api: &Api) -> bool {
+ loop {
+ match api.event(u32::MAX).map(|e| e.kind) {
+ Some(RESUME) => return true,
+ Some(BUTTON) => return false,
+ _ => {}
+ }
+ }
+ }
+
+ fn seed(api: &Api) -> u32 {
+ let t = api.time().map_or(0, |t| (t.minute as u32 * 60 + t.second as u32) * 1000 + t.millis as u32);
+ api.now().wrapping_mul(2_654_435_761) ^ t
+ }
+
+ /// The finger on the glass: when it came down and what the game was doing then.
+ #[derive(Clone, Copy)]
+ struct Finger {
+ at: u32,
+ state: State,
+ holding: bool,
+ }
+
+ fn main(api: &'static Api) -> i32 {
+ let mut screen = api;
+ let mut motor = Motor::new(api); // dropped on return: the motor goes off
+ let mut blob = [0u8; 16];
+ let n = api.load(&mut blob);
+ let mut best = if n > 0 { decode(&blob[..n as usize]) } else { 0 };
+ let mut g = Game::new(seed(api));
+ let mut on_screen = Some(frame(&mut screen, &g, best, None));
+ api.show();
+ let mut finger: Option = None;
+ let mut over_at = 0u32;
+ loop {
+ motor.update();
+ let now = api.now();
+ // what is due next: the game, the end of a tap (a hold begins), the motor
+ let mut wait = g.wake_in(now).unwrap_or(u32::MAX);
+ if let Some(f) = finger.filter(|f| f.state == State::Playing && !f.holding) {
+ let left = (f.at.wrapping_add(HOLD_MS).wrapping_sub(now) as i32).max(0) as u32;
+ wait = wait.min(left);
+ }
+ if let Some(m) = motor.wait() {
+ wait = wait.min(m);
+ }
+ let mut first = api.event(wait);
+ let mut redraw_all = false;
+ let mut quit = false;
+ // handle this event and everything else already queued, then draw once
+ for _ in 0..16 {
+ let Some(e) = first.take().or_else(|| api.event(0)) else { break };
+ let now = api.now();
+ match e.kind {
+ BUTTON => quit = true,
+ PAUSE => {
+ motor.off();
+ g.set_soft(false, now);
+ if !paused(api) {
+ quit = true;
+ } else {
+ finger = None;
+ g.rebase(api.now());
+ redraw_all = true;
+ }
+ }
+ TOUCH_DOWN => {
+ finger = Some(Finger { at: now, state: g.state, holding: false });
+ }
+ TOUCH_UP => {
+ let Some(f) = finger.take() else { continue };
+ if f.holding {
+ g.set_soft(false, now);
+ } else if f.state != g.state {
+ // the game changed under the finger: this touch belonged to something else
+ } else {
+ match g.state {
+ State::Playing => {
+ g.turn(now);
+ }
+ State::Ready => g.start(now),
+ State::Over => {
+ if due(f.at, over_at.wrapping_add(RETRY_MS)) {
+ g.start(now);
+ }
+ }
+ }
+ }
+ }
+ CROWN => {
+ g.shift(if e.delta * CROWN_RIGHT > 0 { 1 } else { -1 }, now);
+ }
+ _ => {}
+ }
+ if quit {
+ break;
+ }
+ }
+ if quit {
+ api.keep_screen_on(false);
+ return 0;
+ }
+ let now = api.now();
+ // a finger that stayed down: the piece drops
+ if let Some(f) = &mut finger {
+ if f.state == State::Playing && g.state == State::Playing && !f.holding && due(now, f.at.wrapping_add(HOLD_MS)) {
+ f.holding = true;
+ g.set_soft(true, now);
+ }
+ }
+ // what is due in the game; at most a few things per wake-up, the rest on the next one
+ for _ in 0..4 {
+ if g.wake_in(now) != Some(0) {
+ break;
+ }
+ match g.tick(now) {
+ Step::Locked => motor.play(TICK),
+ Step::Cleared(n) => motor.play(if n >= 4 { DONE } else { DOUBLE }),
+ Step::Crashed => {
+ motor.play(DONE);
+ over_at = now;
+ if g.score > best {
+ best = g.score;
+ api.save(&encode(best)); // on change: the app can be ended without notice
+ }
+ }
+ Step::Nothing => {}
+ }
+ }
+ if g.state == State::Over && finger.is_some_and(|f| f.state == State::Playing) {
+ finger = None; // the hold that ended the game ends with it
+ }
+ let before = on_screen;
+ let now_seen = seen(&g, best);
+ if redraw_all || before != Some(now_seen) {
+ on_screen = Some(frame(&mut screen, &g, best, if redraw_all { None } else { before }));
+ api.show();
+ }
+ api.keep_screen_on(g.state == State::Playing);
+ }
+ }
+}
diff --git a/apps/tetris/src/view.rs b/apps/tetris/src/view.rs
new file mode 100644
index 0000000..058102f
--- /dev/null
+++ b/apps/tetris/src/view.rs
@@ -0,0 +1,569 @@
+// Drawing, through cmf-wp2-ui's Surface: the watch draws with `&Api`, the tests with `Fb`. One buffer and no double
+// buffering, so a frame repaints only the cells and numbers that changed, and never paints a pixel twice in different
+// colours: each cell is its own 20 px square, filled and then drawn on once.
+
+use crate::game::{Game, H, SCORE_MAX, State, W, shape};
+use cmf_wp2_ui::draw::rrect;
+use cmf_wp2_ui::text::{big, big_width, centre, int, width};
+use cmf_wp2_ui::{C, Rgb, Surface};
+
+pub const SIZE: i32 = cmf_wp2_ui::SIZE;
+/// A cell, and the well's top left corner: 200 x 400 px, centred. Its far corners sit 224 px from the centre, inside
+/// the round panel (233).
+pub const CELL: i32 = 20;
+pub const BX: i32 = C - W as i32 * CELL / 2;
+pub const BY: i32 = C - H as i32 * CELL / 2;
+
+const BLACK: u16 = 0;
+const WELL: Rgb = Rgb(9, 10, 14);
+const DOT: Rgb = Rgb(30, 33, 44);
+const FRAME: Rgb = Rgb(58, 63, 82);
+const PANEL: Rgb = Rgb(20, 22, 30);
+const WHITE: Rgb = Rgb(255, 255, 255);
+const GREY: u16 = 0x8C71;
+const TEAL: Rgb = Rgb(94, 230, 168);
+
+/// I O T S Z J L
+pub const COLORS: [Rgb; 7] = [
+ Rgb(62, 214, 230),
+ Rgb(255, 201, 60),
+ Rgb(160, 108, 240),
+ Rgb(94, 230, 168),
+ Rgb(242, 87, 95),
+ Rgb(60, 130, 240),
+ Rgb(255, 148, 64),
+];
+
+/// What a cell shows: 0 empty, 1..=7 a block of that kind, GHOST + kind where the piece would land, FLASH a
+/// blinking row.
+const GHOST: u8 = 8;
+const FLASH: u8 = 15;
+
+/// The HUD: numbers right-aligned at LEFT_X on the left of the well, the next piece and the best score on the right.
+const LEFT_X: i32 = BX - 12;
+const RIGHT_X: i32 = BX + W as i32 * CELL + 14;
+const FIELD_W: i32 = 96;
+const SCORE_Y: i32 = 140;
+const LINES_Y: i32 = 206;
+const LEVEL_Y: i32 = 272;
+const NEXT_Y: i32 = 140;
+const BEST_Y: i32 = 272;
+
+/// What is on screen after a frame.
+#[derive(Clone, Copy, PartialEq, Debug)]
+pub struct Seen {
+ cells: [[u8; W]; H],
+ score: u32,
+ lines: u32,
+ level: u32,
+ next: u8,
+ best: u32,
+ state: State,
+}
+
+fn compose(g: &Game) -> [[u8; W]; H] {
+ if g.state == State::Ready {
+ return [[0; W]; H];
+ }
+ let mut c = g.board;
+ if g.state == State::Playing && g.flash.is_none() {
+ if let Some(gh) = g.ghost() {
+ for (x, y) in gh.cells() {
+ if y >= 0 && c[y as usize][x as usize] == 0 {
+ c[y as usize][x as usize] = GHOST + gh.kind;
+ }
+ }
+ }
+ }
+ if let Some(p) = g.cur {
+ for (x, y) in p.cells() {
+ if y >= 0 {
+ c[y as usize][x as usize] = p.kind + 1;
+ }
+ }
+ }
+ if let Some(f) = g.flash.filter(|f| f.lit()) {
+ for (y, row) in c.iter_mut().enumerate() {
+ if f.rows >> y & 1 == 1 {
+ *row = [FLASH; W];
+ }
+ }
+ }
+ c
+}
+
+pub fn seen(g: &Game, best: u32) -> Seen {
+ Seen {
+ cells: compose(g),
+ score: g.score.min(SCORE_MAX),
+ lines: g.lines.min(9999),
+ level: g.level() + 1,
+ next: g.next,
+ best: best.min(SCORE_MAX),
+ state: g.state,
+ }
+}
+
+/// A block of `size` px: a darker rim, a lit face and a small sheen, like the icon.
+fn tile(s: &mut impl Surface, x: i32, y: i32, size: i32, c: Rgb, bg: Rgb) {
+ let r = size / 4;
+ let dark = c.scale(680);
+ rrect(s, x + 1, y + 1, size - 2, size - 2, r + 1, dark, bg);
+ rrect(s, x + 2, y + 2, size - 4, size - 5, r, c, dark);
+ rrect(s, x + size / 4 + 1, y + size / 5 + 1, size / 2, 2, 1, c.mix(WHITE, 470), c);
+}
+
+/// The outline of where the piece will land.
+fn ghost(s: &mut impl Surface, x: i32, y: i32, c: Rgb) {
+ let dim = c.scale(420);
+ rrect(s, x + 1, y + 1, CELL - 2, CELL - 2, 5, dim, WELL);
+ rrect(s, x + 3, y + 3, CELL - 6, CELL - 6, 3, WELL, dim);
+}
+
+fn cell(s: &mut impl Surface, cx: usize, cy: usize, v: u8) {
+ let (x, y) = (BX + cx as i32 * CELL, BY + cy as i32 * CELL);
+ s.rect(x, y, CELL, CELL, WELL.rgb565());
+ match v {
+ 0 => s.rect(x + CELL / 2 - 1, y + CELL / 2 - 1, 2, 2, DOT.rgb565()),
+ 1..=7 => tile(s, x, y, CELL, COLORS[v as usize - 1], WELL),
+ GHOST..=14 => ghost(s, x, y, COLORS[(v - GHOST) as usize]),
+ _ => tile(s, x, y, CELL, Rgb(245, 248, 255), WELL),
+ }
+}
+
+/// A number in a box, right-aligned at `xr`.
+fn field(s: &mut impl Surface, xr: i32, y: i32, n: u32, c: u16) {
+ let mut buf = [0u8; 11];
+ let t = int(n as i32, &mut buf);
+ s.rect(xr - FIELD_W, y, FIELD_W, 16, BLACK);
+ s.text(xr - width(t), y, t, c);
+}
+
+fn label(s: &mut impl Surface, xr: i32, y: i32, t: &str) {
+ s.text(xr - width(t), y - 20, t, GREY);
+}
+
+fn next_box(s: &mut impl Surface, kind: u8) {
+ const BW: i32 = 84;
+ const BH: i32 = 64;
+ const T: i32 = 14;
+ rrect(s, RIGHT_X, NEXT_Y + 2, BW, BH, 14, PANEL, Rgb(0, 0, 0));
+ let c = shape(kind, 0);
+ let (x0, x1) = (c.iter().map(|p| p.0).min().unwrap_or(0), c.iter().map(|p| p.0).max().unwrap_or(0));
+ let (y0, y1) = (c.iter().map(|p| p.1).min().unwrap_or(0), c.iter().map(|p| p.1).max().unwrap_or(0));
+ let (w, h) = ((x1 - x0 + 1) * T, (y1 - y0 + 1) * T);
+ let (ox, oy) = (RIGHT_X + (BW - w) / 2, NEXT_Y + 2 + (BH - h) / 2);
+ for (px, py) in c {
+ tile(s, ox + (px - x0) * T, oy + (py - y0) * T, T, COLORS[kind as usize % 7], PANEL);
+ }
+}
+
+fn hud(s: &mut impl Surface, n: &Seen, p: Option<&Seen>) {
+ let changed = |f: fn(&Seen) -> u32| p.is_none_or(|p| f(p) != f(n));
+ if p.is_none() {
+ label(s, LEFT_X, SCORE_Y, "SCORE");
+ label(s, LEFT_X, LINES_Y, "LINES");
+ label(s, LEFT_X, LEVEL_Y, "LEVEL");
+ s.text(RIGHT_X + 2, NEXT_Y - 20, "NEXT", GREY);
+ s.text(RIGHT_X + 2, BEST_Y - 20, "BEST", GREY);
+ }
+ if changed(|s| s.score) {
+ field(s, LEFT_X, SCORE_Y, n.score, WHITE.rgb565());
+ }
+ if changed(|s| s.lines) {
+ field(s, LEFT_X, LINES_Y, n.lines, TEAL.rgb565());
+ }
+ if changed(|s| s.level) {
+ field(s, LEFT_X, LEVEL_Y, n.level, TEAL.rgb565());
+ }
+ if p.is_none_or(|p| p.next != n.next) {
+ next_box(s, n.next);
+ }
+ if changed(|s| s.best) {
+ // left-aligned under its label
+ let mut buf = [0u8; 11];
+ let t = int(n.best as i32, &mut buf);
+ s.rect(RIGHT_X, BEST_Y, FIELD_W, 16, BLACK);
+ s.text(RIGHT_X + 2, BEST_Y, t, WHITE.rgb565());
+ }
+}
+
+fn frame_bars(s: &mut impl Surface) {
+ let h = H as i32 * CELL;
+ let w = W as i32 * CELL;
+ s.rect(BX - 4, BY, 2, h + 4, FRAME.rgb565());
+ s.rect(BX + w + 2, BY, 2, h + 4, FRAME.rgb565());
+ s.rect(BX - 4, BY + h + 2, w + 8, 2, FRAME.rgb565());
+}
+
+/// The big title: each letter in the colour of a piece.
+fn title(s: &mut impl Surface, y: i32) {
+ const T: &str = "TETRIS";
+ let x = C - big_width(T, 5) / 2;
+ for (i, ch) in T.char_indices() {
+ let mut one = [0u8; 4];
+ let t = ch.encode_utf8(&mut one);
+ big(s, x + i as i32 * 40, y, t, 5, COLORS[[2, 4, 1, 0, 3, 5][i]].rgb565());
+ }
+}
+
+fn ready(s: &mut impl Surface, best: u32) {
+ s.rect(0, 0, SIZE, SIZE, BLACK);
+ title(s, 70);
+ // a T piece about to drop into the gap in the row under it
+ const P: i32 = 34;
+ let (x0, y0) = (C - (3 * P - 2) / 2, 142);
+ let black = Rgb(0, 0, 0);
+ for (cx, cy, k, dim) in [(0, 0, 2, false), (1, 0, 2, false), (2, 0, 2, false), (1, 1, 2, false), (0, 2, 5, true), (2, 2, 5, true)] {
+ let c = COLORS[k];
+ tile(s, x0 + cx * P, y0 + cy * P, P - 2, if dim { c.scale(500) } else { c }, black);
+ }
+ centre(s, C, 268, "TAP TO PLAY", WHITE.rgb565());
+ centre(s, C, 312, "TAP: TURN", GREY);
+ centre(s, C, 334, "HOLD: DROP", GREY);
+ centre(s, C, 356, "CROWN: MOVE", GREY);
+ if best > 0 {
+ let mut buf = [0u8; 11];
+ let mut line = [0u8; 16];
+ let n = int(best as i32, &mut buf).as_bytes();
+ line[..5].copy_from_slice(b"BEST ");
+ line[5..5 + n.len()].copy_from_slice(n);
+ centre(s, C, 396, core::str::from_utf8(&line[..5 + n.len()]).unwrap_or("?"), TEAL.rgb565());
+ }
+}
+
+fn over(s: &mut impl Surface, n: &Seen) {
+ let (w, h) = (192, 176);
+ let (x, y) = (C - w / 2, 136);
+ rrect(s, x, y, w, h, 22, PANEL, WELL);
+ let red = COLORS[4].rgb565();
+ big(s, C - big_width("GAME", 3) / 2, y + 14, "GAME", 3, red);
+ big(s, C - big_width("OVER", 3) / 2, y + 42, "OVER", 3, red);
+ let mut buf = [0u8; 11];
+ centre(s, C, y + 86, int(n.score as i32, &mut buf), WHITE.rgb565());
+ let mut line = [0u8; 16];
+ let b = int(n.best as i32, &mut buf).as_bytes();
+ line[..5].copy_from_slice(b"BEST ");
+ line[5..5 + b.len()].copy_from_slice(b);
+ centre(s, C, y + 110, core::str::from_utf8(&line[..5 + b.len()]).unwrap_or("?"), TEAL.rgb565());
+ centre(s, C, y + 146, "TAP TO PLAY", GREY);
+}
+
+/// Draws the frame for `g`. `prev`: what is on screen now; `None`, or another state, repaints everything.
+pub fn frame(s: &mut impl Surface, g: &Game, best: u32, prev: Option) -> Seen {
+ let now = seen(g, best);
+ match prev.filter(|p| p.state == now.state) {
+ None => {
+ if now.state == State::Ready {
+ ready(s, best);
+ } else {
+ s.rect(0, 0, SIZE, SIZE, BLACK);
+ frame_bars(s);
+ for (y, row) in now.cells.iter().enumerate() {
+ for (x, &v) in row.iter().enumerate() {
+ cell(s, x, y, v);
+ }
+ }
+ hud(s, &now, None);
+ if now.state == State::Over {
+ over(s, &now);
+ }
+ }
+ }
+ Some(p) => {
+ if now.state == State::Playing {
+ for (y, (a, b)) in p.cells.iter().zip(&now.cells).enumerate() {
+ for (x, (&u, &v)) in a.iter().zip(b).enumerate() {
+ if u != v {
+ cell(s, x, y, v);
+ }
+ }
+ }
+ hud(s, &now, Some(&p));
+ }
+ }
+ }
+ now
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::game::Piece;
+ use cmf_wp2_ui::{Count, Fb};
+ use std::vec;
+ use std::vec::Vec;
+
+ fn screen() -> Vec {
+ vec![0u16; (SIZE * SIZE) as usize]
+ }
+
+ fn full(g: &Game, best: u32) -> Vec {
+ let mut px = screen();
+ frame(&mut Fb::new(&mut px), g, best, None);
+ px
+ }
+
+ fn playing(seed: u32) -> Game {
+ let mut g = Game::new(seed);
+ g.start(0);
+ g
+ }
+
+ fn inside(x: i32, y: i32) -> bool {
+ (x - C) * (x - C) + (y - C) * (y - C) <= C * C
+ }
+
+ #[test]
+ fn the_well_and_its_frame_lie_inside_the_round_panel() {
+ let (w, h) = (W as i32 * CELL, H as i32 * CELL);
+ for (x, y) in [(BX - 4, BY), (BX + w + 4, BY), (BX - 4, BY + h + 4), (BX + w + 4, BY + h + 4)] {
+ assert!(inside(x, y), "({x}, {y}) is off the panel");
+ }
+ assert_eq!((BX, BY), (133, 33));
+ }
+
+ #[test]
+ fn the_hud_lies_inside_the_round_panel() {
+ // every text and box: its corners (a label is 5 chars, a number up to 6, the next box 84 x 66)
+ let right = RIGHT_X + FIELD_W;
+ for (x0, x1, y0, y1) in [
+ (LEFT_X - 80, LEFT_X, SCORE_Y - 20, SCORE_Y - 4),
+ (LEFT_X - FIELD_W, LEFT_X, SCORE_Y, SCORE_Y + 16),
+ (LEFT_X - 80, LEFT_X, LINES_Y - 20, LINES_Y + 16),
+ (LEFT_X - 80, LEFT_X, LEVEL_Y - 20, LEVEL_Y + 16),
+ (RIGHT_X, RIGHT_X + 64, NEXT_Y - 20, NEXT_Y - 4),
+ (RIGHT_X, RIGHT_X + 84, NEXT_Y + 2, NEXT_Y + 66),
+ (RIGHT_X, right, BEST_Y - 20, BEST_Y + 16),
+ ] {
+ for (x, y) in [(x0, y0), (x1, y0), (x0, y1), (x1, y1)] {
+ assert!(inside(x, y), "({x}, {y})");
+ }
+ }
+ }
+
+ #[test]
+ fn the_title_screens_text_fits_the_panel() {
+ let wide = |t: &str, y: i32| {
+ let w = width(t);
+ assert!(inside(C - w / 2, y) && inside(C + w / 2, y) && inside(C - w / 2, y + 16) && inside(C + w / 2, y + 16), "{t}");
+ };
+ wide("TAP TO PLAY", 268);
+ wide("CROWN: MOVE", 356);
+ wide("BEST 999999", 396);
+ let tw = big_width("TETRIS", 5);
+ assert!(inside(C - tw / 2, 70) && inside(C + tw / 2, 110));
+ }
+
+ /// Plays on its own for a while and, now and then, compares what the partial frames made with a full repaint.
+ #[test]
+ fn partial_frames_match_a_full_repaint() {
+ for seed in [1u32, 8, 77] {
+ let mut g = playing(seed);
+ let mut px = screen();
+ let mut prev = None;
+ let mut r = seed.wrapping_mul(2_654_435_761) | 1;
+ let mut rnd = move || {
+ r ^= r << 13;
+ r ^= r >> 17;
+ r ^= r << 5;
+ r
+ };
+ let mut checked = 0;
+ let mut t = 0u32;
+ for step in 0..6000u32 {
+ t += 16;
+ match rnd() % 11 {
+ 0 | 1 => {
+ g.shift(-1, t);
+ }
+ 2 | 3 => {
+ g.shift(1, t);
+ }
+ 4 => {
+ g.turn(t);
+ }
+ 5 => g.set_soft(rnd() % 3 != 0, t),
+ _ => {}
+ }
+ g.tick(t);
+ if g.state == State::Over {
+ prev = Some(frame(&mut Fb::new(&mut px), &g, 3, prev));
+ assert_eq!(px, full(&g, 3), "over, seed {seed}");
+ g.start(t);
+ prev = None;
+ }
+ prev = Some(frame(&mut Fb::new(&mut px), &g, 3, prev));
+ if step % 9 == 0 {
+ let want = full(&g, 3);
+ let bad = px.iter().zip(&want).position(|(a, b)| a != b);
+ assert_eq!(bad.map(|i| (i as i32 % SIZE, i as i32 / SIZE)), None, "seed {seed} step {step}");
+ checked += 1;
+ }
+ }
+ assert!(checked > 100);
+ }
+ }
+
+ #[test]
+ fn a_still_frame_draws_nothing() {
+ for state in [State::Ready, State::Playing] {
+ let mut g = Game::new(4);
+ if state == State::Playing {
+ g.start(0);
+ }
+ let mut px = screen();
+ let mut fb = Fb::new(&mut px);
+ let p = frame(&mut fb, &g, 10, None);
+ let rects = fb.rects;
+ assert!(rects > 0);
+ frame(&mut fb, &g, 10, Some(p));
+ assert_eq!(fb.rects, rects, "{state:?}");
+ }
+ }
+
+ #[test]
+ fn a_move_costs_a_handful_of_cells_not_the_screen() {
+ let mut g = playing(5);
+ let mut px = screen();
+ let mut fb = Fb::new(&mut px);
+ let p = frame(&mut fb, &g, 0, None);
+ let first = fb.rects;
+ g.shift(1, 10);
+ fb.rects = 0;
+ let p = frame(&mut fb, &g, 0, Some(p));
+ let move_cost = fb.rects;
+ // the piece and its guide change cells: at most 16 of them, a few rects each
+ assert!(move_cost > 0 && move_cost < 700, "{move_cost}");
+ assert!(move_cost * 8 < first, "{move_cost} vs a full paint of {first}");
+ g.turn(20);
+ fb.rects = 0;
+ frame(&mut fb, &g, 0, Some(p));
+ assert!(fb.rects < 900, "{}", fb.rects);
+ // and a full repaint is cheap enough to do at any time
+ let mut c = Count::default();
+ frame(&mut c, &g, 0, None);
+ assert!(c.rects < 3000, "{}", c.rects);
+ }
+
+ #[test]
+ fn cells_stay_inside_their_squares() {
+ // draw each kind of cell on a marked background and look for pixels outside the 20 px square
+ for v in 0..=FLASH {
+ if (9..GHOST).contains(&v) {
+ continue;
+ }
+ let mut px = vec![0xABCDu16; (SIZE * SIZE) as usize];
+ cell(&mut Fb::new(&mut px), 3, 4, v);
+ let (x0, y0) = (BX + 3 * CELL, BY + 4 * CELL);
+ for y in 0..SIZE {
+ for x in 0..SIZE {
+ let inside = x >= x0 && x < x0 + CELL && y >= y0 && y < y0 + CELL;
+ if !inside {
+ assert_eq!(px[(y * SIZE + x) as usize], 0xABCD, "value {v} spilled to ({x}, {y})");
+ }
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn each_kind_has_its_own_colour_on_screen() {
+ let mut seen = Vec::new();
+ for k in 1..=7u8 {
+ let mut px = screen();
+ cell(&mut Fb::new(&mut px), 0, 0, k);
+ seen.push(px[((BY + 10) * SIZE + BX + 8) as usize]);
+ }
+ seen.sort();
+ seen.dedup();
+ assert_eq!(seen.len(), 7);
+ }
+
+ #[test]
+ fn the_ghost_shows_under_the_piece_and_not_over_blocks() {
+ let mut g = playing(6);
+ g.cur = Some(Piece { kind: 2, rot: 0, x: 3, y: 0 });
+ let c = compose(&g);
+ let gh = g.ghost().unwrap();
+ for (x, y) in gh.cells() {
+ assert_eq!(c[y as usize][x as usize], GHOST + 2);
+ }
+ for (x, y) in g.cur.unwrap().cells() {
+ assert_eq!(c[y as usize][x as usize], 3);
+ }
+ // locked blocks are never overdrawn by the guide
+ g.board[H - 1] = [4; W];
+ let c = compose(&g);
+ assert!(c[H - 1].iter().all(|&v| v == 4));
+ }
+
+ #[test]
+ fn a_blinking_row_is_white_every_other_step() {
+ let mut g = playing(2);
+ for y in H - 1..H {
+ for x in 1..W {
+ g.board[y][x] = 2;
+ }
+ }
+ g.cur = Some(Piece { kind: 0, rot: 1, x: -2, y: H as i32 - 4 });
+ let mut t = 0;
+ while g.flash.is_none() {
+ t += 1;
+ g.tick(t);
+ assert!(t < 5000);
+ }
+ let mut saw = (false, false);
+ for _ in 0..600 {
+ t += 1;
+ g.tick(t);
+ if let Some(f) = g.flash {
+ let c = compose(&g);
+ if f.lit() {
+ assert_eq!(c[H - 1], [FLASH; W]);
+ saw.0 = true;
+ } else {
+ assert_ne!(c[H - 1], [FLASH; W]);
+ saw.1 = true;
+ }
+ }
+ }
+ assert_eq!(saw, (true, true));
+ }
+
+ /// `PREVIEW=/abs/dir cargo test dump_preview`: raw RGB565 frames of the screen, for pictures.
+ #[test]
+ fn dump_preview() {
+ let Ok(dir) = std::env::var("PREVIEW") else { return };
+ let save = |name: &str, px: &[u16]| {
+ let bytes: Vec = px.iter().flat_map(|v| v.to_le_bytes()).collect();
+ std::fs::write(format!("{dir}/{name}.raw"), bytes).unwrap();
+ };
+ let g = Game::new(3);
+ save("ready", &full(&g, 12400));
+ // a game in progress: pile some random blocks, a falling piece, and a few cleared rows
+ let mut g = playing(11);
+ let rows: [&str; 8] = ["IIIIZZ.TTT", "OO.JJJ.ZZT", "OOSSJLLLZZ", "TTTSSLJJJZ", "ZZ.OOLJ.SS", ".ZZOOL.SSL", "LLL.TTTSSL", "LJJJ.T.ZZL"];
+ for (i, r) in rows.iter().enumerate() {
+ for (x, ch) in r.chars().enumerate() {
+ g.board[H - 8 + i][x] = match ch {
+ 'I' => 1,
+ 'O' => 2,
+ 'T' => 3,
+ 'S' => 4,
+ 'Z' => 5,
+ 'J' => 6,
+ 'L' => 7,
+ _ => 0,
+ };
+ }
+ }
+ g.score = 4350;
+ g.lines = 23;
+ g.cur = Some(Piece { kind: 2, rot: 1, x: 4, y: 6 });
+ save("playing", &full(&g, 12400));
+ let mut g2 = g.clone();
+ g2.state = State::Over;
+ save("over", &full(&g2, 12400));
+ }
+}
diff --git a/apps/tetris/store.md b/apps/tetris/store.md
new file mode 100644
index 0000000..a29b5da
--- /dev/null
+++ b/apps/tetris/store.md
@@ -0,0 +1,13 @@
+Falling blocks on your wrist. Pieces drop into a 10 by 20 well: fill a row and it clears. Clear ten rows and the
+pieces fall faster. A faint outline shows where the piece will land. Your best score is kept on the watch.
+
+- **Turn the crown** to move the piece left and right.
+- **Tap** the screen to turn it.
+- **Hold** your finger on the screen to drop it faster.
+
+Press the crown or swipe right to leave.
+
+## Requirements
+
+The [patched firmware](/firmware) and the [App Loader](/firmware). Open it from the **Apps** row at the end of the
+watch's app list (list style, not the waterfall).
diff --git a/apps/tetris/store.toml b/apps/tetris/store.toml
new file mode 100644
index 0000000..e9ceacd
--- /dev/null
+++ b/apps/tetris/store.toml
@@ -0,0 +1,6 @@
+# The app's listing in the FMC store (README.md, "store.toml"). The page's body is store.md.
+name = "Tetris"
+summary = "Falling blocks. Crown moves, tap turns, hold drops"
+version = "0.1.0"
+author = "arunk140"
+screenshots = ["shots/ready.png", "shots/playing.png", "shots/over.png"]