diff --git a/pkgs/id/book/design/first-apps.md b/pkgs/id/book/design/first-apps.md index 5cdc88ba06..d61c8b4ba6 100644 --- a/pkgs/id/book/design/first-apps.md +++ b/pkgs/id/book/design/first-apps.md @@ -18,9 +18,9 @@ The did-it data model has its own investigation: `2026-10-29T13-04-50Z_investiga - Early surfaces. `2026-03-20T05-30-00Z_feature_collaborative_cursor_enhancements` (2026-03-20) and `2026-03-23T00:00:00Z_feature_file_list_ui` (2026-03-23) are the earliest records in this theme — collaborative cursors and the file list UI of the pre-worlds editor generation. `2026-04-01T00-00-00Z_feature_multi_instance` covers multi-instance support for `id`. `2026-10-17T09-00-00Z_feature_world_fixtures` designs session recording to replayable fixtures, the testing base the app designs rely on. - Games and assets. `2026-11-08T09-14-46Z_research_id5988_prior_art_bot_games_programmable_worlds` is the prior-art research on scripted-bot battle games and user-programmable worlds. `2026-11-06T00-50-21Z_design_dynamic_world_tick_cost` designs the dynamic-world per-tick cost model and the bot-battle benchmark. `2026-11-08T00-57-08Z_design_shader_asset_format` designs the shader asset format v1. `2026-10-16T15-00-00Z_feature_roc_grid` is the RocGrid record — a bounds-checked grid library for world programs, the library the grid guest app demonstrates. -## The shipped first apps: the 10 Roc guest apps +## The shipped first apps: the 11 Roc guest apps -The platform's working first apps are the 10 deployable Roc guest apps in `pkgs/id/examples/`, plus the one packaged app. They run on the shared Plaza platform (`examples/roc-world/`), whose guest shape is fixed: every app provides `init`, `update`, `view`, `layout`, `records`, `wants`, `snapshot` and `restore`; guests are compiled to import-free Wasm modules with no WASI, no filesystem, network, clock or randomness imports; all effects go through the capability protocol, with requests answered as participant-0 events and refusals returned as events with stable error codes (`cap_denied`, `unknown_cap`, `bad_args`, `failed`, `actor_denied`, `outside_ceiling`, `result_too_large`). The full platform treatment is in [Design: worlds and the guest runtime](worlds-runtime.md). +The platform's working first apps are the 11 deployable Roc guest apps in `pkgs/id/examples/`, plus the one packaged app. They run on the shared Plaza platform (`examples/roc-world/`), whose guest shape is fixed: every app provides `init`, `update`, `view`, `layout`, `records`, `wants`, `snapshot` and `restore`; guests are compiled to import-free Wasm modules with no WASI, no filesystem, network, clock or randomness imports; all effects go through the capability protocol, with requests answered as participant-0 events and refusals returned as events with stable error codes (`cap_denied`, `unknown_cap`, `bad_args`, `failed`, `actor_denied`, `outside_ceiling`, `result_too_large`). The full platform treatment is in [Design: worlds and the guest runtime](worlds-runtime.md). | App | Location | What it is | | ---------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | @@ -31,6 +31,7 @@ The platform's working first apps are the 10 deployable Roc guest apps in `pkgs/ | roc-chat | `examples/roc-chat/` | Minimal chat client on `RocCap` with `chat.say` and `chat.history`; typing `hist` shows the newest 8 lines. | | roc-grid | `examples/roc-grid/` | RocGrid demo: a 4×3 byte grid, `set` claims the centre cell, bounds-checked reads with fallback. | | roc-mind-map | `examples/roc-mind-map/` | Mind map for `mind-map/same-label-distinct-nodes` (#13609): stable node IDs, a typed `related` cross-link that survives reparent and rename, refused single-history cycles, preserved positions. | +| roc-burrow | `examples/roc-burrow/` | Burrow for `burrow/detour-to-exit` (#13603): a three-cell excavation and exit loop — dig clears adjacent soil once, the rock is impassable, the exit opens only after three clears; `records` and `snapshot` publish the same domain document. | | roc-screen | `examples/roc-screen/` | Screen and Key demo: a bordered-box counter screen document; presenters render the structured grid. | | territory | `examples/territory/` | Multiplayer territory game: at most 8 seated players on a 16×8 grid, adjacency-only claiming, seats persist across leave, rejoin and restart. | | roc-cap-demo | `examples/roc-cap-demo/` | Library-import worked example (#5957): a capability-dependent Roc library over `records.read`, with two compile-must-fail negative tests. | @@ -63,7 +64,7 @@ An example with invented data, following the v1 design: a creator exports the pr Grounding, from the library survey for this book (checkout `1ccb4a19457`, 2026-11-23): -- Shipped: the 10 Roc guest apps and the packaged tic-tac-toe app listed in the table above, with checked-in Wasm artifacts beside most apps so host conformance suites run without a Roc toolchain. These are the first apps in the literal sense: working guest programs on the shipped Plaza platform. +- Shipped: the 11 Roc guest apps and the packaged tic-tac-toe app listed in the table above, with checked-in Wasm artifacts beside most apps so host conformance suites run without a Roc toolchain. These are the first apps in the literal sense: working guest programs on the shipped Plaza platform. - Shipped: the program-side machinery the ecosystem designs build on — the program registry and gallery surface named in the CLI (`gallery`, `publish`, `unpublish`, `publications` command families exist in the shipped CLI table), and the bundle record path the #10662 listing design distinguishes itself from: author-signed bundle records with author, name, version and payload hash, fetched by content hash and verified on the bundle path. - Shipped as a proof of concept only: the first app of #2031 — sticky notes plus did-it — exists as the integration test `tests/first_app_poc.rs` and a README in `examples/first-app-poc/`. It is not a packaged application. - Still design: the ecosystem ladder as designed — signed bundle export/import/fork as the v1 user flow (#6291 is a design record; the record states no implementation code is in it), the gallery as a registry with update channels (#6293, design only), the hosted public gallery as an operated instance (#6294, design only), and creator tooling (#6308, design only). The chat v1, boards and match-attestation designs are likewise design records; the shipped chat and boards functionality in the `id` program is the earlier application surface documented in the reference chapters, not an implementation of these v1 designs — the records themselves make no completion claim, and this chapter makes none for them. diff --git a/pkgs/id/book/development/add-a-guest.md b/pkgs/id/book/development/add-a-guest.md index 63f08fed69..fd1b2d4cdd 100644 --- a/pkgs/id/book/development/add-a-guest.md +++ b/pkgs/id/book/development/add-a-guest.md @@ -15,6 +15,7 @@ Worked examples live in `pkgs/id/examples/`. Each app is a directory holding its | `examples/roc-chat/` | Chat over the capability protocol: `chat.say` and `chat.history` through `RocCap`. | | `examples/roc-grid/` | The `RocGrid` library: a 4×3 byte grid with bounds-checked reads. | | `examples/roc-mind-map/` | Stable IDs with duplicate labels, a typed cross-link, refused cycles, preserved positions. | +| `examples/roc-burrow/` | An excavation game on a semantic text grid: dig/walk commands, a clear quota gating the exit, literal-vector host replay. | | `examples/roc-screen/` | The `Screen` and `Key` libraries: a structured screen document instead of text. | | `examples/lounge/` | The capability system end to end: subscriptions, arrival greetings through `chat.say`, and refusal counting. | | `examples/territory/` | A complete multiplayer game: at most 8 seated players on a 16×8 grid, adjacency-only claiming, seats that persist across leave, rejoin and restart. | diff --git a/pkgs/id/book/library/guests-and-shells.md b/pkgs/id/book/library/guests-and-shells.md index 6f4684fe73..d8cc621fb1 100644 --- a/pkgs/id/book/library/guests-and-shells.md +++ b/pkgs/id/book/library/guests-and-shells.md @@ -37,9 +37,9 @@ The runtime provider set named in `ABI.md` is `time.now`, `time.tick` (subscribe The Roc client library is `RocCap`: a session issuing request ids `r0`, `r1`, and so on, with `issue`, `attach`, `requests`, and `route`, and builders `chat_request`, `now_request`, `players_request`, `world_request`, `history_request`, `records_request`, `schedule_at_request`, and `schedule_cancel_request`. -## The ten Roc guest apps +## The eleven Roc guest apps -Checked-in `.wasm` artefacts sit beside most apps, so the host conformance suites run without a Roc toolchain. `pkgs/id/apps/tic-tac-toe/` is the sole packaged app; the other nine live in `pkgs/id/examples/`. +Checked-in `.wasm` artefacts sit beside most apps, so the host conformance suites run without a Roc toolchain. `pkgs/id/apps/tic-tac-toe/` is the sole packaged app; the other ten live in `pkgs/id/examples/`. | App | Location | What it does | | ---------------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -50,6 +50,7 @@ Checked-in `.wasm` artefacts sit beside most apps, so the host conformance suite | roc-chat | `examples/roc-chat/` | Minimal chat client on `RocCap` with `chat.say` and `chat.history`; typing `hist` shows the newest 8 lines. | | roc-grid | `examples/roc-grid/` | `RocGrid` demo: a 4×3 byte grid where `set` claims the centre cell; bounds-checked reads with a fallback. | | roc-mind-map | `examples/roc-mind-map/` | Mind map for `mind-map/same-label-distinct-nodes` (#13609): nodes distinguished by stable ID with duplicate `Archive` labels, a typed `related` cross-link through reparent and rename, refused single-history cycles, preserved positions; `records` and `snapshot` publish the same domain document. | +| roc-burrow | `examples/roc-burrow/` | Burrow for `burrow/detour-to-exit` (#13603): a three-cell excavation and exit loop on a semantic text grid — dig clears adjacent soil exactly once, the rock is impassable, the exit accepts entry only once three clears are banked; `records` and `snapshot` publish the same domain document. | | roc-screen | `examples/roc-screen/` | `Screen` and `Key` demo: a bordered-box counter screen document, `+` increments; presenters (SSH ANSI, browser DOM) render the structured grid. | | territory | `examples/territory/` | Multiplayer territory game: at most 8 seated players on a 16×8 grid, adjacency-only claiming, seats persist across leave, rejoin, and restart. | | roc-cap-demo | `examples/roc-cap-demo/` | Library-import worked example (#5957): a capability-dependent Roc library (`lib/Greeter.roc` over `records.read`) plus its app, with two compile-must-fail negative tests — a missing capability on `platform-no-caps.roc`, and a wrong `RocCap` signature. | diff --git a/pkgs/id/crates/id-worlds/src/sandbox.rs b/pkgs/id/crates/id-worlds/src/sandbox.rs index 2d0ac9a63a..6347400391 100644 --- a/pkgs/id/crates/id-worlds/src/sandbox.rs +++ b/pkgs/id/crates/id-worlds/src/sandbox.rs @@ -2184,6 +2184,231 @@ mod tests { assert_eq!(records(&mut restored), records(&mut live)); } + #[test] + fn checked_in_burrow_replays_detour_to_exit() { + // Oracle: burrow/detour-to-exit in app-vectors.json (revision + // b9d8177). Inputs are the vector's own, event tags included: the + // tag is host journal deduplication metadata and the guest does not + // read it. The after states are literal copies of the vector + // projections; the outcome is asserted beside them. + let wasm = include_bytes!("../../../examples/roc-burrow/burrow.wasm"); + let runner = Sandbox::compile(wasm, SandboxLimits::default()).unwrap(); + let mut live = runner.instantiate(7).unwrap(); + let records = |world: &mut WorldInstance| -> serde_json::Value { + serde_json::from_slice(&world.records().unwrap().unwrap()).unwrap() + }; + let expected = |after: serde_json::Value, outcome: &str| -> serde_json::Value { + let mut doc = after; + doc["outcome"] = serde_json::json!(outcome); + doc + }; + let view_rows = |world: &mut WorldInstance| -> Vec { + let view = String::from_utf8(world.view().unwrap()).unwrap(); + let Some(crate::world_presentation::WorldSurface::Screen(screen)) = + crate::world_presentation::parse_surface(&view).unwrap() + else { + panic!("the burrow view must be a structured screen: {view}"); + }; + screen + .cells + .chunks(usize::from(screen.width)) + .map(|row| row.iter().map(|cell| cell.symbol.as_str()).collect()) + .collect() + }; + assert_eq!( + records(&mut live), + expected( + serde_json::json!({ + "digger": [0, 1], + "soil": [[1, 1], [2, 1], [2, 2]], + "cleared_count": 0, + "phase": "digging" + }), + "" + ) + ); + // The semantic text grid: digger west, two soil cells and the rock + // on the middle row; the third soil and the exit on the bottom row. + let rows = view_rows(&mut live); + assert!(rows.iter().any(|row| row.contains("A s s #")), "{rows:?}"); + assert!(rows.iter().any(|row| row.contains(". . s X")), "{rows:?}"); + assert!( + rows.iter().any(|row| row.contains("soil left=3 cleared=0/3")), + "{rows:?}" + ); + // (input, expected outcome, expected after-state) + let steps = [ + ( + r#"{"kind":"Dig","direction":"E","event":"d1"}"#, + "cleared", + serde_json::json!({ + "digger": [1, 1], + "soil": [[2, 1], [2, 2]], + "cleared_count": 1, + "phase": "digging" + }), + ), + ( + r#"{"kind":"Dig","direction":"E","event":"d2"}"#, + "cleared", + serde_json::json!({ + "digger": [2, 1], + "soil": [[2, 2]], + "cleared_count": 2, + "phase": "digging" + }), + ), + ( + r#"{"kind":"Dig","direction":"E","event":"d3"}"#, + "blocked-rock", + serde_json::json!({ + "digger": [2, 1], + "soil": [[2, 2]], + "cleared_count": 2, + "phase": "digging" + }), + ), + ( + r#"{"kind":"Dig","direction":"S","event":"d4"}"#, + "cleared", + serde_json::json!({ + "digger": [2, 2], + "soil": [], + "cleared_count": 3, + "phase": "digging" + }), + ), + ( + r#"{"kind":"Walk","direction":"E","event":"w1"}"#, + "escaped", + serde_json::json!({ + "digger": [3, 2], + "soil": [], + "cleared_count": 3, + "phase": "escaped" + }), + ), + ]; + for (input, outcome, after) in steps { + live.update(1, input.as_bytes()).unwrap(); + assert_eq!(records(&mut live), expected(after, outcome), "{input}"); + } + // Escaped: the digger stands on the exit cell, no soil remains, + // and a further dig is refused with the state final. + let rows = view_rows(&mut live); + assert!(rows.iter().any(|row| row.contains(". . . A")), "{rows:?}"); + assert!( + rows.iter().any(|row| row.contains("soil left=0 cleared=3/3")), + "{rows:?}" + ); + assert!( + rows.iter() + .any(|row| row.contains("phase=escaped last=escaped")), + "{rows:?}" + ); + live.update(1, br#"{"kind":"Dig","direction":"W","event":"d5"}"#) + .unwrap(); + assert_eq!( + records(&mut live), + expected( + serde_json::json!({ + "digger": [3, 2], + "soil": [], + "cleared_count": 3, + "phase": "escaped" + }), + "refused" + ) + ); + } + + #[test] + fn checked_in_burrow_snapshot_restore_and_scope_distinctions() { + // The snapshot/restore half of the #13603 acceptance, plus the + // scope distinctions: host events never drive the guest, the + // view's presentation text is not domain state, and refusals the + // vector does not exercise still change nothing. + let wasm = include_bytes!("../../../examples/roc-burrow/burrow.wasm"); + let runner = Sandbox::compile(wasm, SandboxLimits::default()).unwrap(); + let records = |world: &mut WorldInstance| -> serde_json::Value { + serde_json::from_slice(&world.records().unwrap().unwrap()).unwrap() + }; + let initial = serde_json::json!({ + "digger": [0, 1], + "soil": [[1, 1], [2, 1], [2, 2]], + "cleared_count": 0, + "phase": "digging", + "outcome": "" + }); + + // Restore a snapshot into a new instance and compare the next + // accepted operations through the regular host. + let mut live = runner.instantiate(7).unwrap(); + live.update(1, br#"{"kind":"Dig","direction":"E","event":"d1"}"#) + .unwrap(); + live.update(1, br#"{"kind":"Dig","direction":"E","event":"d2"}"#) + .unwrap(); + let snapshot = live.snapshot().unwrap().unwrap(); + let mut restored = runner.instantiate(7).unwrap(); + restored.restore(&snapshot).unwrap(); + assert_eq!(records(&mut restored), records(&mut live)); + assert_eq!(restored.view().unwrap(), live.view().unwrap()); + assert_eq!(restored.snapshot().unwrap().unwrap(), snapshot); + for input in [ + r#"{"kind":"Dig","direction":"E","event":"d3"}"#, + r#"{"kind":"Dig","direction":"S","event":"d4"}"#, + r#"{"kind":"Walk","direction":"E","event":"w1"}"#, + ] { + live.update(1, input.as_bytes()).unwrap(); + restored.update(1, input.as_bytes()).unwrap(); + assert_eq!(records(&mut restored), records(&mut live), "{input}"); + } + assert_eq!( + records(&mut restored)["phase"], + serde_json::json!("escaped") + ); + + // A host (participant 0) delivery is not a player command. + let mut host_driven = runner.instantiate(7).unwrap(); + host_driven + .update(0, br#"{"kind":"Dig","direction":"E","event":"d1"}"#) + .unwrap(); + assert_eq!(records(&mut host_driven), initial); + + // Records carry exactly the five domain keys: no grid glyphs, no + // status lines, no level constants. + let doc = records(&mut host_driven); + let mut keys: Vec<&str> = doc + .as_object() + .unwrap() + .keys() + .map(String::as_str) + .collect(); + keys.sort_unstable(); + assert_eq!( + keys, + ["cleared_count", "digger", "outcome", "phase", "soil"] + ); + let text = doc.to_string(); + assert!(!text.contains("soil left"), "{text}"); + assert!(!text.contains("rock"), "{text}"); + + // Walking into uncleared soil and digging off the board edge are + // refusals that change nothing but the last outcome. + let mut refused = runner.instantiate(7).unwrap(); + refused + .update(1, br#"{"kind":"Walk","direction":"E","event":"w0"}"#) + .unwrap(); + let mut after = initial.clone(); + after["outcome"] = serde_json::json!("blocked-soil"); + assert_eq!(records(&mut refused), after); + refused + .update(1, br#"{"kind":"Dig","direction":"W","event":"d0"}"#) + .unwrap(); + after["outcome"] = serde_json::json!("blocked-edge"); + assert_eq!(records(&mut refused), after); + } + #[test] fn checked_in_chat_example_sends_and_reads_history() { use crate::world::{WorldEvent, WorldEventKind}; diff --git a/pkgs/id/examples/roc-burrow/README.md b/pkgs/id/examples/roc-burrow/README.md new file mode 100644 index 0000000000..8db5a4c784 --- /dev/null +++ b/pkgs/id/examples/roc-burrow/README.md @@ -0,0 +1,49 @@ +# Roc Burrow Example + +A playable burrow world for `burrow/detour-to-exit` (#13603). +On a 4×3 board the digger starts at (0,1); soil fills (1,1), (2,1) and +(2,2), a rock blocks (3,1) and the exit waits at (3,2). Digging enters an +orthogonally adjacent soil cell and clears it exactly once. The rock is +impassable. The exit accepts entry only once three soil cells have been +cleared, so the digger detours south around the rock. + +Inputs are JSON commands: + +- `{"kind":"Dig","direction":"E","event":"d1"}` digs into adjacent soil + (`cleared`), moving the digger into the cell. +- Digging toward the rock reports `blocked-rock` and changes nothing; + digging toward the board edge reports `blocked-edge`; digging toward + open floor is `refused`. +- `{"kind":"Walk","direction":"E","event":"w1"}` enters an already open + cell (`moved`); uncleared soil refuses with `blocked-soil`. +- Entering the exit with three clears reports `escaped` and sets the + phase; before three clears it reports `blocked-exit`. + +The `event` tag is host journal deduplication metadata; the guest does +not read it. Host events (participant 0) are ignored. + +`records` publishes the domain state (`digger`, `soil`, `cleared_count`, +`phase`, and the last `outcome`); `snapshot` is the same document, so a +snapshot restored into a fresh instance compares byte-identical through +the regular host. The view is a semantic text grid — `A` the digger, +`s` soil, `#` the rock, `X` the exit, `.` open floor — with the +remaining soil and the clear quota as text lines. + +## Build + +```bash +./build.sh +``` + +Produces `burrow.wasm`, validated as an import-free Wasm module. + +## Run + +```bash +id serve --data-dir ./data --world --world-admin-token "$ADMIN" \ + --world-module "$PWD/examples/roc-burrow/burrow.wasm" \ + --world-ssh-port 2223 --web --port 8787 +``` + +Join with SSH or the web page and send an input such as +`{"kind":"Dig","direction":"E","event":"d1"}` to start digging. diff --git a/pkgs/id/examples/roc-burrow/build.sh b/pkgs/id/examples/roc-burrow/build.sh new file mode 100755 index 0000000000..51f4547dc4 --- /dev/null +++ b/pkgs/id/examples/roc-burrow/build.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")" +export ROC="${ROC:-roc}" +source ../roc-toolchain.sh + +if [ -z "${WASM_TOOLS:-}" ]; then + if command -v wasm-tools >/dev/null 2>&1; then + WASM_TOOLS="wasm-tools" + else + STORE_TOOL=$(ls -d /nix/store/*-wasm-tools-*/bin/wasm-tools 2>/dev/null | head -n1 || true) + if [ -n "$STORE_TOOL" ] && [ -x "$STORE_TOOL" ]; then + WASM_TOOLS="$STORE_TOOL" + else + WASM_TOOLS="nix run nixpkgs#wasm-tools --" + fi + fi +fi + +if [ -z "${WASM_OPT:-}" ]; then + if command -v wasm-opt >/dev/null 2>&1; then + WASM_OPT="wasm-opt" + else + STORE_OPT=$(ls -d /nix/store/*-binaryen-*/bin/wasm-opt 2>/dev/null | head -n1 || true) + if [ -n "$STORE_OPT" ] && [ -x "$STORE_OPT" ]; then + WASM_OPT="$STORE_OPT" + else + WASM_OPT="nix shell nixpkgs#binaryen --command wasm-opt" + fi + fi +fi + +(cd ../roc-world && ./build-host.sh >/dev/null) +"$ROC" build main.roc --target=wasm32 --wasm-memory=8454144 --output=burrow.wasm + +# Same size discipline as roc-grid: optimize, strip DWARF, keep the name section +# so Wasmtime traps still resolve, then validate the import-free module. +$WASM_OPT -Os --all-features burrow.wasm -o burrow.wasm.opt +mv burrow.wasm.opt burrow.wasm +$WASM_TOOLS strip burrow.wasm -o burrow.wasm.stripped +mv burrow.wasm.stripped burrow.wasm +$WASM_TOOLS validate burrow.wasm +echo "Built burrow.wasm (import-free Roc world module)" diff --git a/pkgs/id/examples/roc-burrow/burrow.wasm b/pkgs/id/examples/roc-burrow/burrow.wasm new file mode 100644 index 0000000000..591108583d Binary files /dev/null and b/pkgs/id/examples/roc-burrow/burrow.wasm differ diff --git a/pkgs/id/examples/roc-burrow/main.roc b/pkgs/id/examples/roc-burrow/main.roc new file mode 100644 index 0000000000..4bea62997a --- /dev/null +++ b/pkgs/id/examples/roc-burrow/main.roc @@ -0,0 +1,275 @@ +app [program] { pf: platform "../roc-world/platform.roc" } + +import pf.RocJson +import pf.Screen + +# A burrow for burrow/detour-to-exit (#13603): a three-cell excavation and +# exit loop on a 4x3 board. Dig enters orthogonally adjacent soil and clears +# it exactly once; the rock at (3,1) is impassable; the exit at (3,2) opens +# only once three soil cells have been cleared. The level configuration is +# fixed and immutable: rock, exit and quota are constants of the guest, and +# the terrain under the digger is never stored as a glyph. +# +# Each player event is one JSON command, {"kind":"Dig"|"Walk", +# "direction":"N"|"S"|"E"|"W", ...}. The "event" tag a caller may carry is +# host journal deduplication metadata; the guest does not read it. Host +# events (participant 0) are ignored. `records` publishes the domain state +# (digger, remaining soil, cleared count, phase, last outcome) and +# `snapshot` is the same document, so a snapshot restored into a fresh +# instance compares byte-identical through the regular host. The view is a +# semantic text grid: A is the digger, s is soil, # is the rock, X is the +# exit and . is open floor, with the remaining soil and quota as text. + +Pos : { x : U64, y : U64 } +Model : { digger : Pos, soil : List(Pos), cleared : U64, phase : Str, outcome : Str } + +program = { init, update, view, layout, records, wants, snapshot, restore } + +board_width : U64 +board_width = 4 + +board_height : U64 +board_height = 3 + +rock_pos : Pos +rock_pos = { x: 3, y: 1 } + +exit_pos : Pos +exit_pos = { x: 3, y: 2 } + +required_clears : U64 +required_clears = 3 + +init : U64 -> Model +init = |_seed| initial + +initial : Model +initial = { + digger: { x: 0, y: 1 }, + soil: [{ x: 1, y: 1 }, { x: 2, y: 1 }, { x: 2, y: 2 }], + cleared: 0, + phase: "digging", + outcome: "", +} + +update : Model, U64, Str -> Model +update = |model, pid, ev| + if pid == 0 { + model + } else { + command(model, ev) + } + +command : Model, Str -> Model +command = |model, text| match RocJson.decode(text) { + Err(_) => { ..model, outcome: "invalid" } + Ok(cmd) => { + kind = string_field(cmd, "kind") + direction = string_field(cmd, "direction") + if kind == "Dig" { + dig(model, direction) + } else if kind == "Walk" { + walk(model, direction) + } else { + { ..model, outcome: "invalid" } + } + } +} + +dig : Model, Str -> Model +dig = |model, direction| + if model.phase == "escaped" { + { ..model, outcome: "refused" } + } else if !is_direction(direction) { + { ..model, outcome: "invalid" } + } else match target_of(model.digger, direction) { + Outside => { ..model, outcome: "blocked-edge" } + Inside(target) => + if target == rock_pos { + { ..model, outcome: "blocked-rock" } + } else if target == exit_pos { + enter_exit(model, target) + } else if has_soil(model.soil, target) { + { + ..model, + digger: target, + soil: List.keep_if(model.soil, |cell| cell != target), + cleared: model.cleared + 1, + outcome: "cleared", + } + } else { + { ..model, outcome: "refused" } + } + } + +walk : Model, Str -> Model +walk = |model, direction| + if model.phase == "escaped" { + { ..model, outcome: "refused" } + } else if !is_direction(direction) { + { ..model, outcome: "invalid" } + } else match target_of(model.digger, direction) { + Outside => { ..model, outcome: "blocked-edge" } + Inside(target) => + if target == rock_pos { + { ..model, outcome: "blocked-rock" } + } else if target == exit_pos { + enter_exit(model, target) + } else if has_soil(model.soil, target) { + { ..model, outcome: "blocked-soil" } + } else { + { ..model, digger: target, outcome: "moved" } + } + } + +# The exit accepts entry only once the clear quota is met; before that it +# is a locked cell and entering it changes nothing. +enter_exit : Model, Pos -> Model +enter_exit = |model, target| + if model.cleared >= required_clears { + { ..model, digger: target, phase: "escaped", outcome: "escaped" } + } else { + { ..model, outcome: "blocked-exit" } + } + +is_direction : Str -> Bool +is_direction = |direction| direction == "N" or direction == "S" or direction == "E" or direction == "W" + +target_of : Pos, Str -> [Inside(Pos), Outside] +target_of = |from, direction| + if direction == "E" and from.x + 1 < board_width { + Inside({ x: from.x + 1, y: from.y }) + } else if direction == "W" and from.x > 0 { + Inside({ x: from.x - 1, y: from.y }) + } else if direction == "S" and from.y + 1 < board_height { + Inside({ x: from.x, y: from.y + 1 }) + } else if direction == "N" and from.y > 0 { + Inside({ x: from.x, y: from.y - 1 }) + } else { + Outside + } + +has_soil : List(Pos), Pos -> Bool +has_soil = |soil, pos| List.any(soil, |cell| cell == pos) + +plain = { fg: 0, bg: 0, bold: Bool.False } + +view : Model -> Str +view = |model| { + frame = Screen.boxed(Screen.new(36, 9), 0, 0, 36, 9, "burrow") + grid = List.fold([0, 1, 2], frame, |screen, y| + Screen.put_text(screen, 2, y + 2, row_text(model, y), plain)) + status = "soil left=${List.len(model.soil).to_str()} cleared=${model.cleared.to_str()}/${required_clears.to_str()}" + detail = "phase=${model.phase} last=${model.outcome}" + Screen.render_json( + Screen.put_text(Screen.put_text(grid, 2, 6, status, plain), 2, 7, detail, plain), + ) +} + +row_text : Model, U64 -> Str +row_text = |model, y| Str.join_with(List.map([0, 1, 2, 3], |x| glyph(model, { x, y })), " ") + +glyph : Model, Pos -> Str +glyph = |model, pos| + if pos == model.digger { + "A" + } else if pos == rock_pos { + "#" + } else if pos == exit_pos { + "X" + } else if has_soil(model.soil, pos) { + "s" + } else { + "." + } + +## This program renders the same layout at any viewport. +layout : Model, U64, U64 -> Str +layout = |model, _width, _height| view(model) + +records : Model -> Str +records = |model| encode_or_crash(document(model)) + +## No subscriptions and no requests. +wants : Model -> Str +wants = |_model| "{}" + +snapshot : Model -> Str +snapshot = |model| encode_or_crash(document(model)) + +restore : Str -> Model +restore = |text| match RocJson.decode(text) { + Err(_) => initial + Ok(doc) => match RocJson.as_array(field(doc, "digger")) { + Err(_) => initial + Ok(_) => { + digger: pos_of(doc, "digger"), + soil: List.map(array_field(doc, "soil"), pos_item), + cleared: number_field(doc, "cleared_count"), + phase: string_field(doc, "phase"), + outcome: string_field(doc, "outcome"), + } + } +} + +# --- helpers --------------------------------------------------------------- + +document : Model -> RocJson +document = |model| RocJson.Object([ + { key: "digger", value: pos_json(model.digger) }, + { key: "soil", value: RocJson.Array(List.map(model.soil, pos_json)) }, + { key: "cleared_count", value: RocJson.Number(model.cleared.to_str()) }, + { key: "phase", value: RocJson.String(model.phase) }, + { key: "outcome", value: RocJson.String(model.outcome) }, +]) + +pos_json : Pos -> RocJson +pos_json = |p| RocJson.Array([RocJson.Number(p.x.to_str()), RocJson.Number(p.y.to_str())]) + +pos_of : RocJson, Str -> Pos +pos_of = |doc, key| match RocJson.as_array(field(doc, key)) { + Ok(items) => { x: item_number(items, 0), y: item_number(items, 1) } + Err(_) => { x: 0, y: 0 } +} + +pos_item : RocJson -> Pos +pos_item = |item| match RocJson.as_array(item) { + Ok(items) => { x: item_number(items, 0), y: item_number(items, 1) } + Err(_) => { x: 0, y: 0 } +} + +item_number : List(RocJson), U64 -> U64 +item_number = |items, index| match List.get(items, index) { + Ok(found) => number(found) + Err(_) => 0 +} + +encode_or_crash = |value| match RocJson.encode(value) { + Ok(text) => text + Err(_) => crash "burrow attempted to encode an invalid or oversized JSON value" +} + +field = |value, key| match RocJson.get(value, key) { + Ok(found) => found + Err(_) => RocJson.Null +} + +string_field = |value, key| match RocJson.as_string(field(value, key)) { + Ok(text) => text + Err(_) => "" +} + +array_field = |value, key| match RocJson.as_array(field(value, key)) { + Ok(items) => items + Err(_) => [] +} + +number_field = |value, key| number(field(value, key)) + +number = |value| match RocJson.as_number(value) { + Ok(text) => match U64.from_str(text) { + Ok(found) => found + Err(_) => 0 + } + Err(_) => 0 +} diff --git a/pkgs/id/scripts/rebuild-roc-examples.sh b/pkgs/id/scripts/rebuild-roc-examples.sh index fa4014cdc3..f13f0bc33c 100644 --- a/pkgs/id/scripts/rebuild-roc-examples.sh +++ b/pkgs/id/scripts/rebuild-roc-examples.sh @@ -21,6 +21,7 @@ examples=( examples/roc-chat examples/roc-counter examples/roc-grid + examples/roc-burrow examples/roc-mind-map examples/roc-screen examples/roc-text-counter diff --git a/pkgs/id/tests/toolchain_pin.rs b/pkgs/id/tests/toolchain_pin.rs index 3981b3f759..632996a6dd 100644 --- a/pkgs/id/tests/toolchain_pin.rs +++ b/pkgs/id/tests/toolchain_pin.rs @@ -10,12 +10,13 @@ use std::fs; use std::path::Path; use std::process::Command; -const ROC_EXAMPLE_BUILDS: [&str; 9] = [ +const ROC_EXAMPLE_BUILDS: [&str; 10] = [ "examples/lounge/build.sh", "examples/roc-chat/build.sh", "examples/roc-counter/build.sh", "examples/roc-grid/build.sh", "examples/roc-mind-map/build.sh", + "examples/roc-burrow/build.sh", "examples/roc-screen/build.sh", "examples/roc-text-counter/build.sh", "examples/territory/build.sh",