Skip to content

Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.

Game READMEs point to NumPlay, Tetris notes, media tools

Mason3632493070b0d2a
diff --git a/games/chess/README.md b/games/chess/README.md
index 8787e9e3..3fe138cc 100644
--- a/games/chess/README.md
+++ b/games/chess/README.md
@@ -1,3 +1,5 @@
+> **NumChess is part of [NumPlay](../../README.md)**, every NumWorks game in one app. Get it with all the others, or on its own as `NumChess.nwa` from the [latest release](https://github.com/Mason363/NumPlay/releases/latest).
+
<p align="center">
<img src="docs/icon.png" width="84" alt="NumChess icon">
</p>
@@ -10,13 +12,12 @@
</p>
<p align="center">
- <a href="https://github.com/Mason363/NumChess/releases/latest"><img src="https://img.shields.io/github/v/release/Mason363/NumChess?label=release&color=81b64c" alt="Latest release"></a>
- <a href="https://github.com/Mason363/NumChess/actions/workflows/build.yml"><img src="https://github.com/Mason363/NumChess/actions/workflows/build.yml/badge.svg" alt="Build status"></a>
+ <a href="https://github.com/Mason363/NumPlay/releases/latest"><img src="https://img.shields.io/github/v/release/Mason363/NumPlay?label=release&color=81b64c" alt="Latest release"></a>
<img src="https://img.shields.io/badge/installed%20size-20%20KB-3a3835" alt="Installed size: 20 KB">
</p>
<p align="center">
- <a href="https://github.com/Mason363/NumChess/releases/latest/download/chess.nwa"><b>Download chess.nwa</b></a>
+ <a href="https://github.com/Mason363/NumPlay/releases/latest/download/NumChess.nwa"><b>Download NumChess.nwa</b></a>
&nbsp;·&nbsp; <a href="#install">Install</a>
&nbsp;·&nbsp; <a href="#controls">Controls</a>
&nbsp;·&nbsp; <a href="#build">Build</a>
@@ -131,9 +132,9 @@ All the rules are included: castling, en passant, underpromotion, and draws by s
## Install
-1. Download **[chess.nwa](https://github.com/Mason363/NumChess/releases/latest/download/chess.nwa)** from the [latest release](https://github.com/Mason363/NumChess/releases/latest).
+1. Download **[NumChess.nwa](https://github.com/Mason363/NumPlay/releases/latest/download/NumChess.nwa)** from the [latest NumPlay release](https://github.com/Mason363/NumPlay/releases/latest).
2. Plug the calculator into your computer and open **[my.numworks.com/apps](https://my.numworks.com/apps)** in Chrome or Edge.
-3. Upload `chess.nwa`. **Chess** appears at the end of the calculator's home screen.
+3. Upload `NumChess.nwa`. **Chess** appears at the end of the calculator's home screen.
If you're building from source, `make run` builds and installs in one step.
@@ -175,4 +176,4 @@ make test # engine tests on the host: perft on six positions, hashing, searc
make run # install on a connected calculator
```
-Every push is built by GitHub Actions. Pushing a `v*` tag publishes a release with `chess.nwa` attached.
+NumPlay's GitHub Actions build every push and publish `NumChess.nwa` with each NumPlay release.
diff --git a/games/crossyroad/README.md b/games/crossyroad/README.md
index a912140a..9fc290e0 100644
--- a/games/crossyroad/README.md
+++ b/games/crossyroad/README.md
@@ -1,3 +1,5 @@
+> **Crossy Road is part of [NumPlay](../../README.md)**, every NumWorks game in one app. Get it with all the others, or on its own as `CrossyRoad.nwa` from the [latest release](https://github.com/Mason363/NumPlay/releases/latest).
+
# CrossyWorks
Crossy Road for the NumWorks calculator.
@@ -13,7 +15,7 @@ Hop as far as you can. Dodge cars, trucks and trains, ride logs and lily pads ac
## Install
-1. Download `crossyroad.nwa` from the [latest release](https://github.com/Mason363/CrossyWorks/releases/latest).
+1. Download [`CrossyRoad.nwa`](https://github.com/Mason363/NumPlay/releases/latest/download/CrossyRoad.nwa) from the [latest NumPlay release](https://github.com/Mason363/NumPlay/releases/latest).
2. Plug in your calculator and open [my.numworks.com/apps](https://my.numworks.com/apps).
3. Add the file and send it to the calculator.
diff --git a/games/numdash/README.md b/games/numdash/README.md
index 00c96833..b3fd0bd6 100644
--- a/games/numdash/README.md
+++ b/games/numdash/README.md
@@ -1,10 +1,12 @@
+> **NumDash is part of [NumPlay](../../README.md)**, every NumWorks game in one app. Get it with all the others, or on its own as `NumDash.nwa` from the [latest release](https://github.com/Mason363/NumPlay/releases/latest).
+
# NumDash
**Geometry Dash on your NumWorks calculator.**
NumDash is a fan-made version of Geometry Dash that runs right on a NumWorks graphing calculator. Jump over spikes, fly the ship, collect secret coins and try to beat the first seven levels of the real game, all with the calculator's keys.
-### [⬇ Download NumDash.nwa](https://github.com/Mason363/NumDash/releases/latest/download/NumDash.nwa)
+### [⬇ Download NumDash.nwa](https://github.com/Mason363/NumPlay/releases/latest/download/NumDash.nwa)
<img src="docs/screenshots/menu.png" width="640" alt="The NumDash main menu">
@@ -12,7 +14,7 @@ NumDash is a fan-made version of Geometry Dash that runs right on a NumWorks gra
You only need the calculator, its USB cable and a computer with Chrome or Edge.
-1. **Download** [NumDash.nwa](https://github.com/Mason363/NumDash/releases/latest/download/NumDash.nwa) (the button above).
+1. **Download** [NumDash.nwa](https://github.com/Mason363/NumPlay/releases/latest/download/NumDash.nwa) (the button above).
2. **Plug** your calculator into the computer with the USB cable.
3. **Open** [my.numworks.com/apps](https://my.numworks.com/apps) and follow the steps to send the file to your calculator.
4. **Play:** on the calculator, press the Home key and open **NumDash**.
@@ -88,4 +90,4 @@ make test # tests, level replays and random-input tests
make run # desktop version (arrow keys, Space to jump, Esc to go back)
```
-`make assets` and `make levels` rebuild the graphics and level data (Python 3 with numpy and Pillow). Changing the `VERSION` file on `main` publishes a new release automatically.
+`make assets` and `make levels` rebuild the graphics and level data (Python 3 with numpy and Pillow).
diff --git a/games/numdrive/README.md b/games/numdrive/README.md
index 658c4c61..45055299 100644
--- a/games/numdrive/README.md
+++ b/games/numdrive/README.md
@@ -1,3 +1,5 @@
+> **NumDrive is part of [NumPlay](../../README.md)**, every NumWorks game in one app. Get it with all the others, or on its own as `NumDrive.nwa` from the [latest release](https://github.com/Mason363/NumPlay/releases/latest).
+
# NumDrive: Drive Mad for NumWorks
NumDrive is a Drive Mad style driving game for the NumWorks N0120 calculator.
@@ -12,7 +14,7 @@ NumDrive is a Drive Mad style driving game for the NumWorks N0120 calculator.
## Install
-1. Download `NumDrive.nwa` from the [latest release](https://github.com/Mason363/NumDrive/releases/latest).
+1. Download [`NumDrive.nwa`](https://github.com/Mason363/NumPlay/releases/latest/download/NumDrive.nwa) from the [latest NumPlay release](https://github.com/Mason363/NumPlay/releases/latest).
2. Plug your calculator into a computer and open [my.numworks.com/apps](https://my.numworks.com/apps) in Chrome or Edge.
3. Upload `NumDrive.nwa` and send it to the calculator.
4. Open NumDrive from the home screen.
@@ -26,6 +28,7 @@ NumDrive is a Drive Mad style driving game for the NumWorks N0120 calculator.
| OK or Back | Pause |
| Arrows, then OK | Pick a button or a level |
| Back on a card | Level list |
+| Back on the level list | Quit |
| Home | Quit |
Your progress is saved on the calculator.
diff --git a/games/tetris/README.md b/games/tetris/README.md
new file mode 100644
index 00000000..a2ea57d1
--- /dev/null
+++ b/games/tetris/README.md
@@ -0,0 +1,29 @@
+> **Tetris is part of [NumPlay](../../README.md)**, every NumWorks game in one app. Get it with all the others, or on its own as `Tetris.nwa` from the [latest release](https://github.com/Mason363/NumPlay/releases/latest).
+
+# Tetris
+
+The classic, for the NumWorks calculator, written in Rust by **[Tatone26](https://github.com/Tatone26)** (A. Sainero) in [Numworks-games](https://github.com/Tatone26/Numworks-games/tree/main/apps/tetris). It plays by the modern rules: the 7-piece bag, hold, ghost piece, wall kicks, hard and soft drop, and a save that lets you quit mid-game and continue later.
+
+The original is released into the public domain ([UNLICENSE](UNLICENSE)). This copy, made for NumPlay, changes a few things:
+
+- **Full screen**: 12-pixel blocks, so the playfield fills the whole height of the screen, with the panels resized to match.
+- **Number pad arrows**: 8, 4, 6 and 2 work like the arrow keys, in the game and in the menus.
+- Settings are saved as `tetris.set` (the name used to lack an extension and a terminator), and a full storage no longer stops the game.
+- A smaller build (size-optimized, link-time optimization), and an entry point for the NumPlay launcher.
+
+## Controls
+
+| Key | Action |
+| --- | --- |
+| Left / Right, or 4 / 6 | Move |
+| Down, or 2 | Soft drop |
+| Up, or 8 | Hard drop |
+| OK / Back | Rotate left / right |
+| ⌫ | Hold |
+| Shift | Pause |
+
+## Build
+
+`cargo build --release` (Rust with the `thumbv7em-none-eabihf` target, `arm-none-eabi-gcc` and `nwlink` in the path) writes the app to `target/thumbv7em-none-eabihf/release/tetris`. From the NumPlay root, `make apps` copies it to `build/apps/Tetris.nwa`.
+
+`numworks_utils` and `nppm_decoder` are Tatone26's libraries from the same repository.
diff --git a/games/tetris/tetris/src/ui_tetris.rs b/games/tetris/tetris/src/ui_tetris.rs
index 06d3b1ee..d4a27379 100644
--- a/games/tetris/tetris/src/ui_tetris.rs
+++ b/games/tetris/tetris/src/ui_tetris.rs
@@ -119,8 +119,8 @@ pub fn draw_stable_ui(level: u16, level_lines: u16, score: u32, high_score: u32)
draw_lines_number(level_lines);
}
-/// A number right-padded to 6 characters: zeros for scores, spaces otherwise.
-fn padded(value: u32, zeros: bool) -> String<8> {
+/// A score, padded with zeros to 6 digits.
+fn padded(value: u32) -> String<8> {
let mut txt: String<8> = String::new();
if value > 999_999 {
txt.push_str("999999\0").unwrap();
@@ -129,7 +129,7 @@ fn padded(value: u32, zeros: bool) -> String<8> {
let mut digits: String<11> = string_from_u32(value);
digits.pop();
for _ in 0..(6 - digits.chars().count()) {
- txt.push(if zeros { '0' } else { ' ' }).unwrap();
+ txt.push('0').unwrap();
}
txt.push_str(digits.as_str()).unwrap();
txt.push('\0').unwrap();
@@ -138,19 +138,33 @@ fn padded(value: u32, zeros: bool) -> String<8> {
pub fn draw_score(score: u32, high_score: bool) {
draw_label(
- padded(score, true).as_str(),
+ padded(score).as_str(),
RIGHT_X,
TOP_Y,
if high_score { 1 } else { 3 },
);
}
+/// Draws a number centred on its row, clearing what was there before.
+fn draw_value(value: u32, panel_x: u16, panel_y: u16, row: u16) {
+ push_rect_uniform(
+ Rect {
+ x: panel_x + FRAME,
+ y: panel_y + FRAME + 4 + row * LINE,
+ width: PANEL_W - 2 * FRAME,
+ height: LINE - 2,
+ },
+ COLOR_CONFIG.bckgrd,
+ );
+ draw_label(string_from_u32(value).as_str(), panel_x, panel_y, row);
+}
+
pub fn draw_level(level: u16) {
- draw_label(padded(level as u32, false).as_str(), RIGHT_X, BOTTOM_Y, 1);
+ draw_value(level as u32, RIGHT_X, BOTTOM_Y, 1);
}
pub fn draw_lines_number(line: u16) {
- draw_label(padded(line as u32, false).as_str(), RIGHT_X, BOTTOM_Y, 3);
+ draw_value(line as u32, RIGHT_X, BOTTOM_Y, 3);
}
/// Draws a given tetrimino.
diff --git a/launcher/src/home.c b/launcher/src/home.c
index b6bca3db..0a675d49 100644
--- a/launcher/src/home.c
+++ b/launcher/src/home.c
@@ -201,7 +201,7 @@ int np_home(int *selected, bool returning) {
if (unzooming) h.zoom = 1;
ui_keys_t keys = {np_keys(), 0, 0}; /* ignore keys still held from before */
uint32_t last = np_millis();
- bool dirty = true;
+ bool dirty = true, bar_dirty = false;
int result = -3;
for (;;) {
uint32_t now = np_millis();
@@ -246,8 +246,8 @@ int np_home(int *selected, bool returning) {
} else {
uint32_t before = h.shot_time * 22 / SHOT_MS;
h.shot_time += elapsed;
- if (h.shot_time >= SHOT_MS) h.slide = 0.0001f;
- if (h.shot_time * 22 / SHOT_MS != before) dirty = true; /* the progress bar moves */
+ if (h.shot_time >= SHOT_MS) h.slide = 0.0001f, dirty = true;
+ if (h.shot_time * 22 / SHOT_MS != before) bar_dirty = true; /* only the progress bar moves */
}
}
}
@@ -274,7 +274,10 @@ int np_home(int *selected, bool returning) {
}
if (dirty) {
ui_frame(scene, &h);
- dirty = false;
+ dirty = bar_dirty = false;
+ } else if (bar_dirty) {
+ gfx_render(scene, &h, 176, 192); /* the strip holding the progress bar */
+ bar_dirty = false;
} else {
np_sleep(16);
}
diff --git a/launcher/src/settings.c b/launcher/src/settings.c
index 20a2209e..6f467998 100644
--- a/launcher/src/settings.c
+++ b/launcher/src/settings.c
@@ -145,10 +145,11 @@ static void dialog_scene(void *ctx) {
strcat(line, g->title);
strcat(line, "?");
gfx_text_center(&np_font_title, 160, 80, line, 0xFFFF, 256);
- strcpy(line, "This deletes ");
- strcat(line, g->title);
- int y = gfx_paragraph(&np_font_body, 160, 102, 290, 16, line, 0xFFFF, 240);
- y = gfx_paragraph(&np_font_body, 160, y, 290, 16, "and all of its saved progress. You can't undo this.", 0xFFFF, 240);
+ char body[96];
+ strcpy(body, "This deletes ");
+ strcat(body, g->title);
+ strcat(body, " and all of its saved progress. You can't undo this.");
+ int y = gfx_paragraph(&np_font_body, 160, 102, 280, 16, body, 0xFFFF, 240);
gfx_paragraph(&np_font_small, 160, y + 4, 290, 13,
"To play it again, you'll have to reinstall all of NumPlay from my.numworks.com/apps, and "
"reinstalling may reset your progress in every game.",
diff --git a/tools/media/numdash_frames.c b/tools/media/numdash_frames.c
new file mode 100644
index 00000000..153fa499
--- /dev/null
+++ b/tools/media/numdash_frames.c
@@ -0,0 +1,65 @@
+/* Renders NumDash gameplay for the README: plays a level with one of the
+ * recorded inputs from games/numdash/tests/replays and saves raw RGB565
+ * frames that tools/record.py's helpers turn into a GIF.
+ * usage: numdash_frames level replay.txt out_dir first_tick last_tick step */
+#include "fx.h"
+#include "scene.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static uint16_t fb[GFX_W * GFX_H];
+
+int main(int argc, char **argv) {
+ if (argc < 7) return 2;
+ int lvl = atoi(argv[1]), first = atoi(argv[4]), last = atoi(argv[5]), step = atoi(argv[6]);
+ static Level L;
+ static Game g;
+ if (!level_load_builtin(&L, (unsigned)lvl)) return 1;
+ static int ticks[20000], vals[20000];
+ int n = 0, t, v;
+ FILE *f = fopen(argv[2], "r");
+ while (f && fscanf(f, "input=%d,%d\n", &t, &v) == 2 && n < 20000) ticks[n] = t, vals[n++] = v;
+ if (f) fclose(f);
+ game_start(&g, &L, false);
+ fx_reset();
+ int pos = 0, frame = 0;
+ bool held = false;
+ for (int i = 1; i <= last; i++) {
+ while (pos < n && ticks[pos] <= i) held = vals[pos++];
+ game_step(&g, held);
+ if (i % 6 == 0) fx_update(&g, 6.0f / 240, rgb(125, 255, 0), rgb(0, 255, 255), false);
+ if (g.dead) {
+ fprintf(stderr, "dead at tick %d\n", i);
+ return 1;
+ }
+ if (i >= first && (i - first) % step == 0) {
+ SceneOpts o = {0};
+ o.p1 = rgb(125, 255, 0);
+ o.p2 = rgb(0, 255, 255);
+ o.show_percent = true;
+ o.show_bar = true;
+ o.attempt = 1;
+ o.time = i / 240.f;
+ scene_prepare(&g, &o);
+ for (int s = 0; s < STRIPS; s++) {
+ gfx_begin_strip(s);
+ scene_draw();
+ memcpy(fb + s * STRIP_H * GFX_W, gfx_strip, sizeof(gfx_strip));
+ }
+ char path[512];
+ snprintf(path, sizeof path, "%s/%06d_%06d.raw", argv[3], frame++, (i - first) * 1000 / 240);
+ FILE *o2 = fopen(path, "wb");
+ fwrite(fb, sizeof fb, 1, o2);
+ fclose(o2);
+ }
+ }
+ return 0;
+}
+
+/* no file system here */
+uint8_t *platform_storage(size_t *size) {
+ (void)size;
+ return NULL;
+}
+void platform_storage_commit(void) {}
diff --git a/tools/media/tetris_bot.py b/tools/media/tetris_bot.py
new file mode 100644
index 00000000..089e88e6
--- /dev/null
+++ b/tools/media/tetris_bot.py
@@ -0,0 +1,215 @@
+#!/usr/bin/env python3
+"""Plays Tetris in the ARM emulator for the README's GIF.
+
+Runs the real calculator build (Tetris.nwa) in tools/emu.py, reads the board
+and the NEXT panel from the screen, and places each piece with a classic
+heuristic (few holes, low and flat stack, clear lines). Saves raw frames that
+tools/record.py turns into a GIF.
+
+Usage: tetris_bot.py Tetris.nwa out_dir [--pieces 40] [--fps 25]
+"""
+import argparse
+import os
+import struct
+import sys
+
+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
+import emu # noqa: E402
+
+FIELD_X, FIELD_Y, CELL, W, H = 100, 0, 12, 10, 20
+# tile colours (centre pixel, RGB565) -> piece types, as in tetriminos.rs
+TYPES = "TJZOSLI"
+COLOR_OF = {"T": 6, "J": 1, "Z": 4, "O": 0, "S": 3, "L": 2, "I": 5}
+BLOCKS = {
+ "T": [[(0, 0), (-1, 0), (1, 0), (0, -1)], [(0, 0), (1, 0), (0, 1), (0, -1)], [(0, 0), (-1, 0), (1, 0), (0, 1)],
+ [(0, 0), (-1, 0), (0, 1), (0, -1)]],
+ "J": [[(-1, 0), (-1, -1), (0, 0), (1, 0)], [(0, 1), (0, 0), (0, -1), (1, -1)], [(-1, 0), (0, 0), (1, 0), (1, 1)],
+ [(-1, 1), (0, 1), (0, 0), (0, -1)]],
+ "Z": [[(-1, -1), (0, -1), (0, 0), (1, 0)], [(0, 0), (0, 1), (1, 0), (1, -1)], [(-1, 0), (0, 0), (0, 1), (1, 1)],
+ [(-1, 1), (-1, 0), (0, 0), (0, -1)]],
+ "O": [[(0, 0), (-1, 0), (-1, 1), (0, 1)]] * 4,
+ "S": [[(-1, 0), (0, 0), (0, -1), (1, -1)], [(0, 0), (1, 1), (1, 0), (0, -1)], [(1, 0), (0, 0), (0, 1), (-1, 1)],
+ [(-1, -1), (-1, 0), (0, 0), (0, 1)]],
+ "L": [[(-1, 0), (0, 0), (1, 0), (1, -1)], [(1, 1), (0, 1), (0, 0), (0, -1)], [(-1, 0), (-1, 1), (0, 0), (1, 0)],
+ [(0, 1), (0, 0), (0, -1), (-1, -1)]],
+ "I": [[(0, 0), (1, 0), (-1, 0), (-2, 0)], [(0, 0), (0, -1), (0, 1), (0, 2)], [(0, 1), (1, 1), (-1, 1), (-2, 1)],
+ [(-1, 0), (-1, -1), (-1, 1), (-1, 2)]],
+}
+SPAWN_X = 5
+
+
+def pixel(calc, x, y):
+ return struct.unpack_from("<H", calc.screen, (y * 320 + x) * 2)[0]
+
+
+def classify(c):
+ """Piece colour of a tile centre, or None for empty and ghost cells."""
+ r, g, b = (c >> 11) * 255 // 31, ((c >> 5) & 63) * 255 // 63, (c & 31) * 255 // 31
+ if max(r, g, b) < 90:
+ return None
+ if r > 200 and g > 180 and b < 80:
+ return "O"
+ if r > 200 and 80 < g < 160 and b < 60:
+ return "L"
+ if r > 200 and g < 60:
+ return "Z"
+ if g > 180 and r < 120 and b < 80:
+ return "S"
+ if b > 200 and g > 180:
+ return "I"
+ if b > 150 and r < 80 and g < 80:
+ return "J"
+ if r > 70 and b > 120 and g < 60:
+ return "T"
+ return "?"
+
+
+def read_board(calc):
+ board = []
+ for y in range(H):
+ row = []
+ for x in range(W):
+ row.append(classify(pixel(calc, FIELD_X + x * CELL + CELL // 2 + 1, FIELD_Y + y * CELL + CELL // 2 + 1)))
+ board.append(row)
+ return board
+
+
+def read_next(calc):
+ """Colour of the piece in the NEXT panel (left, top)."""
+ seen = {}
+ for y in range(40, 110, 3):
+ for x in range(14, 84, 3):
+ t = classify(pixel(calc, x, y))
+ if t and t != "?":
+ seen[t] = seen.get(t, 0) + 1
+ return max(seen, key=seen.get) if seen else None
+
+
+def fits(board, piece, rot, px, py):
+ for dx, dy in BLOCKS[piece][rot]:
+ x, y = px + dx, py + dy
+ if x < 0 or x >= W or y >= H:
+ return False
+ if y >= 0 and board[y][x]:
+ return False
+ return True
+
+
+def drop(board, piece, rot, px):
+ py = -2
+ if not fits(board, piece, rot, px, py):
+ return None
+ while fits(board, piece, rot, px, py + 1):
+ py += 1
+ new = [row[:] for row in board]
+ for dx, dy in BLOCKS[piece][rot]:
+ if py + dy < 0:
+ return None
+ new[py + dy][px + dx] = piece
+ cleared = [r for r in new if all(r)]
+ new = [r for r in new if not all(r)]
+ new = [[None] * W for _ in range(len(cleared))] + new
+ return new, len(cleared)
+
+
+def score(board, lines):
+ heights = []
+ holes = 0
+ for x in range(W):
+ h = 0
+ for y in range(H):
+ if board[y][x]:
+ h = H - y
+ break
+ heights.append(h)
+ top = H - h
+ holes += sum(1 for y in range(top, H) if not board[y][x])
+ bump = sum(abs(heights[i] - heights[i + 1]) for i in range(W - 1))
+ return -0.51 * sum(heights) + 0.76 * lines - 0.36 * holes - 0.18 * bump
+
+
+def best_move(board, piece):
+ best = None
+ for rot in range(4 if piece != "O" else 1):
+ for px in range(-2, W + 2):
+ r = drop(board, piece, rot, px)
+ if not r:
+ continue
+ s = score(*r)
+ if best is None or s > best[0]:
+ best = (s, rot, px)
+ return best
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("nwa")
+ ap.add_argument("out")
+ ap.add_argument("--pieces", type=int, default=40)
+ ap.add_argument("--fps", type=int, default=25)
+ a = ap.parse_args()
+ os.makedirs(a.out, exist_ok=True)
+ c = emu.Calculator(a.nwa)
+ frame = [0]
+
+ def grab(calc):
+ path = os.path.join(a.out, f"{frame[0]:06d}_{int(calc.now_ms):06d}.raw")
+ open(path, "wb").write(bytes(calc.screen))
+ frame[0] += 1
+
+ def run_until(ms):
+ c.run(ms, grab, 1000 / a.fps)
+
+ def tap(key, down=35, up=45):
+ t = c.now_ms
+ c.keys.append((t, t + down, emu.KEYS[key]))
+ run_until(t + down + up)
+
+ run_until(900)
+ tap("ok") # Play
+ run_until(c.now_ms + 1500)
+ # the first piece: wait until it shows up
+ current = None
+ while current is None:
+ run_until(c.now_ms + 100)
+ for row in read_board(c)[:3]:
+ for cell in row:
+ if cell and cell != "?":
+ current = cell
+ for n in range(a.pieces):
+ board = [[cell if cell != "?" else "X" for cell in row] for row in read_board(c)]
+ # the falling piece is in the top rows: remove it from the board
+ for y in range(4):
+ for x in range(W):
+ if board[y][x] == current:
+ board[y][x] = None
+ nxt = read_next(c)
+ move = best_move(board, current)
+ if os.environ.get("BOT_DEBUG"):
+ for row in board[12:]:
+ print("".join((cell or ".")[0] for cell in row))
+ print("current", current, "next", nxt, "move", move)
+ if not move:
+ break
+ _, rot, px = move
+ if rot == 3:
+ tap("ok")
+ else:
+ for _ in range(rot):
+ tap("back")
+ dx = px - SPAWN_X
+ for _ in range(abs(dx)):
+ tap("left" if dx < 0 else "right")
+ tap("up", 40, 160)
+ if os.environ.get("BOT_DEBUG"):
+ after = read_board(c)
+ landed = [(x, y) for y in range(H) for x in range(W) if after[y][x] and not board[y][x]]
+ expect = drop(board, current, rot, px)
+ print(f"{current} rot {rot} x {px}: landed {sorted(landed)[:4]}")
+ current = nxt
+ run_until(c.now_ms + 1200)
+ print(f"tetris_bot: {frame[0]} frames, {n + 1} pieces")
+
+
+if __name__ == "__main__":
+ main()