34 Commits

Author SHA1 Message Date
7e378ada8b Few explanations how the game works 2026-05-22 00:04:06 +03:00
0749cc5003 Demonolithify tests 2026-05-21 23:59:16 +03:00
db124eeb97 Split tests per level 2026-05-21 23:56:03 +03:00
cb326d432f Fix level tests 2026-05-21 23:47:24 +03:00
cd3d3395c5 Update screenshot 2026-05-21 23:37:35 +03:00
250c326c92 Add all levels 2026-05-21 23:37:19 +03:00
abc0fa7784 Add level 11: Advanced Anchors
`shapes:` list defines 2-3 polygons (name + sides + interior angle sum);
`copies:` is a list of 3-4 selections (with possible repetition) drawn
from the same pool. serde_yaml expands aliases on parse, so the target
is the inlined form; players using `- &name` anchors inside the list
and `*name` aliases in `copies:` produce the same Value and pass via
the semantic short-circuit.

All randomised per seed (ChaCha8Rng XOR'd with 0x..0B).

Not wired into levels::registry() yet — integration belongs to a follow-up.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 23:17:44 +03:00
9b2f6d4731 Add level 10: Vault Ledger (dynamic values)
`vault:` with four entries — decimal int gold, decimal int silver,
fractional float experience, and an ISO-8601 date string. Description
hints at hex/octal/exponent equivalents the player can write — any
form parsing to the same numeric value passes.

All four values randomised per seed (ChaCha8Rng XOR'd with 0x..0A).

Not wired into levels::registry() yet — integration belongs to a follow-up.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 23:16:51 +03:00
2bf412e65b Add level 9: Merge Keys (special operators)
`door_defaults` plus `north_door` and `south_door`, each containing a
`<<:` key whose value is the defaults dict. north overrides locked,
south overrides material. serde_yaml treats `<<` as a literal mapping
key, so the target and a player's `<<: *defaults` form parse to the
same Value.

Default material/locked and which side overrides which are randomised
per seed (ChaCha8Rng XOR'd with 0x..09).

Not wired into levels::registry() yet — integration belongs to a follow-up.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 23:16:32 +03:00
5bbf7ca107 Make L5 more natural 2026-05-21 23:15:50 +03:00
bcdd487eec Enable levels 4 and 5 2026-05-21 23:11:01 +03:00
736c6bd564 Add level 8: Scroll of Tags (tags + newlines)
Three keys:
- scroll: multi-line string (block scalar `|`)
- weight: fractional float (e.g. 12.5) — forces float without needing
  the `!!float` tag in the target text
- title:  string of digits (player needs quotes or `!!str` to avoid int)

Per-seed deterministic via ChaCha8Rng XOR'd with 0x..08.

Not wired into levels::registry() yet — integration belongs to a follow-up.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 23:03:58 +03:00
3f8ea45ef7 Add level 7: The Floor Map (complex nested data)
Top-level `floor:` int + `rooms:` mapping where each room carries a
type, a locked flag, an exits list, and a contents list. Two rooms
picked from a name/kind pool; exits and contents drawn from typed
pools. Deterministic per seed (ChaCha8Rng XOR'd with 0x..07).

Not wired into levels::registry() yet — integration belongs to a follow-up.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 23:03:35 +03:00
a8b91f1645 Merge branch 'level-6' 2026-05-21 23:02:33 +03:00
040bec6c80 Merge branch 'level-5' 2026-05-21 23:01:19 +03:00
9f8e5caaa8 Add level 11: Advanced Anchors
`shapes:` list defines 2-3 polygons (name + sides + interior angle sum);
`copies:` is a list of 3-4 selections (with possible repetition) drawn
from the same pool. serde_yaml expands aliases on parse, so the target
is the inlined form; players using `- &name` anchors inside the list
and `*name` aliases in `copies:` produce the same Value and pass via
the semantic short-circuit.

All randomised per seed (ChaCha8Rng XOR'd with 0x..0B).

Not wired into levels::registry() yet — integration belongs to a follow-up.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 22:59:44 +03:00
424ef3e8fd Add level 10: Vault Ledger (dynamic values)
`vault:` with four entries — decimal int gold, decimal int silver,
fractional float experience, and an ISO-8601 date string. Description
hints at hex/octal/exponent equivalents the player can write — any
form parsing to the same numeric value passes.

All four values randomised per seed (ChaCha8Rng XOR'd with 0x..0A).

Not wired into levels::registry() yet — integration belongs to a follow-up.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 22:58:25 +03:00
b2f9f24b68 Merge pull request 'Add level 4: The Chest (lists)' (#1) from level-4 into master
Reviewed-on: #1
2026-05-21 22:57:16 +03:00
f0a7992626 Add level 9: Merge Keys (special operators)
`door_defaults` plus `north_door` and `south_door`, each containing a
`<<:` key whose value is the defaults dict. north overrides locked,
south overrides material. serde_yaml treats `<<` as a literal mapping
key, so the target and a player's `<<: *defaults` form parse to the
same Value.

Default material/locked and which side overrides which are randomised
per seed (ChaCha8Rng XOR'd with 0x..09).

Not wired into levels::registry() yet — integration belongs to a follow-up.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 22:56:44 +03:00
4d06100300 Add level 8: Scroll of Tags (tags + newlines)
Three keys:
- scroll: multi-line string (block scalar `|`)
- weight: fractional float (e.g. 12.5) — forces float without needing
  the `!!float` tag in the target text
- title:  string of digits (player needs quotes or `!!str` to avoid int)

Per-seed deterministic via ChaCha8Rng XOR'd with 0x..08.

Not wired into levels::registry() yet — integration belongs to a follow-up.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 22:55:56 +03:00
5b73daee4c Add level 7: The Floor Map (complex nested data)
Top-level `floor:` int + `rooms:` mapping where each room carries a
type, a locked flag, an exits list, and a contents list. Two rooms
picked from a name/kind pool; exits and contents drawn from typed
pools. Deterministic per seed (ChaCha8Rng XOR'd with 0x..07).

Not wired into levels::registry() yet — integration belongs to a follow-up.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 22:55:08 +03:00
c0e89ca1a1 Add level 6: Anchors
Target structure: a `trap:` dict plus a `rooms:` map where 2-3 rooms
all share the same trap. serde_yaml expands aliases on parse, so the
emitted target is the inlined form; players using `&anchor` / `*alias`
produce the same parsed Value and pass via the semantic short-circuit.

Trap properties (type / depth / spikes) and reused rooms are randomised
per seed (ChaCha8Rng XOR'd with 0x..06).

Not wired into levels::registry() yet — integration belongs to a follow-up.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 22:54:08 +03:00
b805a49aaa Add level 5: Chambers (dictionaries + lists)
Top-level `chambers:` mapping; each chamber name maps to an item list.
2-3 chambers, 2-3 items each, drawn from typed pools. Deterministic per
seed via ChaCha8Rng XOR'd with 0x..05.

Not wired into levels::registry() yet — integration belongs to a follow-up.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 22:12:23 +03:00
07f82a7086 Add level 4: The Chest (lists)
Top-level `chest:` key with a 3-5 item sequence drawn from a small pool.
Per-seed deterministic via ChaCha8Rng XOR'd with 0x..04. Description
rendered with tera; flavor uses a 📦 emoji.

Not wired into levels::registry() yet — integration belongs to a follow-up.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 21:51:35 +03:00
bac059a789 Add docs 2026-05-21 21:27:37 +03:00
aa6094fdb1 Cursor fix 2026-05-21 21:24:00 +03:00
f817c7b93e Various pre-release cosmetic fixes 2026-05-21 21:21:44 +03:00
cb0abb3e3b Move help to a separate dialog box 2026-05-21 19:26:30 +03:00
a6741da14c Replace tiers with achievements 2026-05-21 19:17:58 +03:00
4765917be4 Switch to ^X as default submission key 2026-05-21 19:00:46 +03:00
42153b1733 Add statusbar w/shortcuts 2026-05-21 18:58:54 +03:00
4b3b1ce5a0 Add typewriter effect 2026-05-21 18:52:19 +03:00
740685afc5 Add level names 2026-05-21 18:31:43 +03:00
845cad7f74 Update TUI to scroll from the bottom 2026-05-21 18:31:29 +03:00
20 changed files with 2314 additions and 335 deletions

1
Cargo.lock generated
View File

@@ -1496,6 +1496,7 @@ dependencies = [
"serde_yaml",
"similar",
"tera",
"unicode-width",
]
[[package]]

View File

@@ -23,3 +23,4 @@ dirs = "5"
anyhow = "1"
ratatui = "0.26"
crossterm = "0.27"
unicode-width = "0.1"

16
README.md Normal file
View File

@@ -0,0 +1,16 @@
# YAMLabyrinth
A text dungeon game that teaches you YAML.
The game uses actual YAML parsing libraries and generates semi-random levels
by describing a secret YAML file that the user has to recreate in the editor.
There are 11 levels in the game, so if you're on level 12, you won the game!
![screenshot](screenshot.png)
## How to start:
cargo run
## Dependencies

10
game.ini Normal file
View File

@@ -0,0 +1,10 @@
# YAMLabyrinth — game configuration.
# Delete this file to use defaults. Keys are case-insensitive; spaces
# and underscores in keys are equivalent.
# Animate level prompts character-by-character in the log.
typewriter_effect = true
# Typing speed in characters per minute. Higher = faster.
# Defaults: 2000 cpm (~30 ms per character).
typewriter_speed_cpm = 2000

BIN
screenshot.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

130
src/config.rs Normal file
View File

@@ -0,0 +1,130 @@
//! Game configuration, loaded from `./game.ini`.
//!
//! Two settings today:
//! - `typewriter_effect` (bool, default `true`) — animate level prompts
//! character-by-character as they appear in the log.
//! - `typewriter_speed_cpm` (u32, default `1000`) — typing speed in
//! characters per minute (~60 ms per character).
//!
//! Missing keys fall back to defaults. Missing file falls back to all
//! defaults. Comments (`#` or `;`) and `[sections]` are ignored.
use std::path::PathBuf;
use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GameConfig {
pub typewriter_enabled: bool,
pub typewriter_speed_cpm: u32,
}
impl Default for GameConfig {
fn default() -> Self {
Self {
typewriter_enabled: true,
typewriter_speed_cpm: 1000,
}
}
}
impl GameConfig {
/// How long each character takes to appear during the typewriter
/// animation. Falls back to the default speed if `speed_cpm` is 0.
pub fn char_duration(&self) -> Duration {
let cpm = if self.typewriter_speed_cpm == 0 {
Self::default().typewriter_speed_cpm
} else {
self.typewriter_speed_cpm
};
Duration::from_millis(60_000 / cpm as u64)
}
}
pub fn config_path() -> PathBuf {
PathBuf::from("game.ini")
}
pub fn load() -> GameConfig {
match std::fs::read_to_string(config_path()) {
Ok(content) => parse(&content),
Err(_) => GameConfig::default(),
}
}
pub fn parse(content: &str) -> GameConfig {
let mut cfg = GameConfig::default();
for line in content.lines() {
let line = line.trim();
if line.is_empty()
|| line.starts_with('#')
|| line.starts_with(';')
|| line.starts_with('[')
{
continue;
}
let Some((key, value)) = line.split_once('=') else {
continue;
};
let key = key.trim().to_lowercase().replace(' ', "_");
let value = value.trim();
match key.as_str() {
"typewriter_effect" | "typewriter_enabled" => {
if let Ok(b) = value.parse::<bool>() {
cfg.typewriter_enabled = b;
}
}
"typewriter_speed" | "typewriter_speed_cpm" => {
if let Ok(n) = value.parse::<u32>() {
cfg.typewriter_speed_cpm = n;
}
}
_ => {}
}
}
cfg
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn defaults() {
let cfg = GameConfig::default();
assert!(cfg.typewriter_enabled);
assert_eq!(cfg.typewriter_speed_cpm, 1000);
// 1000 cpm = 60 ms per char
assert_eq!(cfg.char_duration().as_millis(), 60);
}
#[test]
fn parser_reads_both_underscored_and_spaced_keys() {
let ini = "\
# comment\n\
; another comment\n\
[section]\n\
typewriter effect = false\n\
typewriter_speed_cpm = 240\n\
";
let cfg = parse(ini);
assert!(!cfg.typewriter_enabled);
assert_eq!(cfg.typewriter_speed_cpm, 240);
// 240 cpm = 250 ms per char
assert_eq!(cfg.char_duration().as_millis(), 250);
}
#[test]
fn parser_keeps_defaults_on_garbage() {
let cfg = parse("typewriter_effect = maybe\ntypewriter_speed_cpm = fast\n");
assert_eq!(cfg, GameConfig::default());
}
#[test]
fn zero_speed_falls_back_to_default_duration() {
let cfg = GameConfig {
typewriter_enabled: true,
typewriter_speed_cpm: 0,
};
assert_eq!(cfg.char_duration().as_millis(), 60);
}
}

View File

@@ -9,3 +9,6 @@ Third level is dictionaries. Each direction now leads to a feature with its own
straight:
type: wall
depth:
The rendered description ends with a hint reminding the player that each
feature's name goes under a `type:` key (the property keeps its own name).

148
src/levels/l03_dict.rs Normal file
View File

@@ -0,0 +1,148 @@
//! Level 3 — dictionaries. Each direction leads to a feature with its
//! own type + one characteristic property.
//!
//! Paired design note: `l03.md`.
use rand::seq::SliceRandom;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
use serde::Serialize;
use serde_yaml::{Mapping, Value};
use crate::describe::Describer;
use super::{Generated, Level};
pub struct Dict;
const DIRECTIONS: &[&str] = &["left", "right", "straight", "back", "up", "down"];
enum Feature {
Door,
Tunnel,
Pit,
Stairs,
Wall,
Altar,
}
impl Feature {
fn name(&self) -> &'static str {
match self {
Feature::Door => "door",
Feature::Tunnel => "tunnel",
Feature::Pit => "pit",
Feature::Stairs => "stairs",
Feature::Wall => "wall",
Feature::Altar => "altar",
}
}
fn random(rng: &mut ChaCha8Rng) -> Self {
match rng.gen_range(0..6) {
0 => Feature::Door,
1 => Feature::Tunnel,
2 => Feature::Pit,
3 => Feature::Stairs,
4 => Feature::Wall,
_ => Feature::Altar,
}
}
/// One characteristic property: (key, value).
fn property(&self, rng: &mut ChaCha8Rng) -> (&'static str, Value) {
match self {
Feature::Door => ("locked", Value::Bool(rng.gen_bool(0.5))),
Feature::Tunnel => ("depth", Value::from(rng.gen_range(5..=30i64))),
Feature::Pit => ("depth", Value::from(rng.gen_range(5..=30i64))),
Feature::Stairs => {
let going = if rng.gen_bool(0.5) { "up" } else { "down" };
("going", Value::String(going.to_string()))
}
Feature::Wall => ("cracked", Value::Bool(rng.gen_bool(0.5))),
Feature::Altar => ("blessed", Value::Bool(rng.gen_bool(0.5))),
}
}
}
#[derive(Serialize)]
struct DescCtx {
entries: Vec<DescEntry>,
}
#[derive(Serialize)]
struct DescEntry {
direction: String,
feature: String,
prop_name: String,
prop_value: String,
}
impl Level for Dict {
fn id(&self) -> u8 {
3
}
fn name(&self) -> &'static str {
"Dictionaries"
}
fn generate(&self, seed: u64) -> Generated {
// Per-level constant so the same `current_seed` produces different
// content per level.
let mut rng = ChaCha8Rng::seed_from_u64(seed ^ 0x0000_0000_0000_0003);
let n = rng.gen_range(2..=3);
let directions: Vec<&'static str> =
DIRECTIONS.choose_multiple(&mut rng, n).copied().collect();
let mut top = Mapping::new();
let mut entries = Vec::with_capacity(directions.len());
for d in &directions {
let feature = Feature::random(&mut rng);
let (prop_name, prop_value) = feature.property(&mut rng);
let mut inner = Mapping::new();
inner.insert(
Value::String("type".to_string()),
Value::String(feature.name().to_string()),
);
inner.insert(
Value::String(prop_name.to_string()),
prop_value.clone(),
);
top.insert(Value::String((*d).to_string()), Value::Mapping(inner));
let prop_value_str = match &prop_value {
Value::Bool(b) => b.to_string(),
Value::Number(n) => n.to_string(),
Value::String(s) => s.clone(),
_ => String::new(),
};
entries.push(DescEntry {
direction: (*d).to_string(),
feature: feature.name().to_string(),
prop_name: prop_name.to_string(),
prop_value: prop_value_str,
});
}
let target_yaml =
serde_yaml::to_string(&Value::Mapping(top)).expect("serialise mapping");
let mut d = Describer::new();
d.register(
"l03",
"{% for e in entries %}- {{ e.direction }} → {{ e.feature }} ({{ e.prop_name }}: {{ e.prop_value }})\n{% endfor %}\n💡 Each feature is a dictionary — give it a `type:` key plus its property.",
)
.expect("register template");
let description = d
.render("l03", &DescCtx { entries })
.expect("render template");
Generated {
target_yaml,
description,
flavor: "🧭 You stand at a junction. Each path reveals its own detail.".to_string(),
}
}
}

71
src/levels/l04_list.rs Normal file
View File

@@ -0,0 +1,71 @@
//! Level 4 — lists. A chest of loot lies open before you.
//!
//! Paired design note: `l04.md`.
use rand::seq::SliceRandom;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
use serde::Serialize;
use serde_yaml::{Mapping, Sequence, Value};
use crate::describe::Describer;
use super::{Generated, Level};
pub struct List;
const ITEMS: &[&str] = &[
"sword", "torch", "rope", "bread", "dagger", "scroll", "gem", "coin", "potion", "shield",
];
#[derive(Serialize)]
struct DescCtx {
items: Vec<String>,
}
impl Level for List {
fn id(&self) -> u8 {
4
}
fn name(&self) -> &'static str {
"The Chest"
}
fn generate(&self, seed: u64) -> Generated {
let mut rng = ChaCha8Rng::seed_from_u64(seed ^ 0x0000_0000_0000_0004);
let n = rng.gen_range(3..=5);
let items: Vec<&'static str> = ITEMS.choose_multiple(&mut rng, n).copied().collect();
let seq: Sequence = items
.iter()
.map(|i| Value::String((*i).to_string()))
.collect();
let mut top = Mapping::new();
top.insert(Value::String("chest".to_string()), Value::Sequence(seq));
let target_yaml =
serde_yaml::to_string(&Value::Mapping(top)).expect("serialise mapping");
let mut d = Describer::new();
d.register(
"l04",
"A chest lies open. Inside:\n{% for it in items %}- {{ it }}\n{% endfor %}\n💡 Wrap the items as a YAML list under a `chest:` key.",
)
.expect("register template");
let description = d
.render(
"l04",
&DescCtx {
items: items.iter().map(|s| s.to_string()).collect(),
},
)
.expect("render template");
Generated {
target_yaml,
description,
flavor: "📦 A chest of loot lies open before you.".to_string(),
}
}
}

120
src/levels/l05_dict_list.rs Normal file
View File

@@ -0,0 +1,120 @@
//! Level 5 — dictionaries AND lists. Each chamber keeps its own inventory.
//!
//! Paired design note: `l05.md`.
use rand::seq::SliceRandom;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
use serde::Serialize;
use serde_yaml::{Mapping, Sequence, Value};
use crate::describe::Describer;
use super::{Generated, Level};
pub struct DictList;
const CHAMBERS: &[&str] = &[
"armory", "pantry", "library", "vault", "kitchen", "cellar",
];
const ITEMS: &[&str] = &[
"sword", "shield", "bread", "water", "tome", "scroll", "gem", "coin", "dagger", "potion",
];
#[derive(Serialize)]
struct DescCtx {
sentences: Vec<String>,
}
/// Pick "a" or "an" based on the first letter — keeps the prose reading
/// naturally without giving away that chamber names are YAML keys.
fn article(word: &str) -> &'static str {
let first = word.chars().next().map(|c| c.to_ascii_lowercase());
if matches!(first, Some('a') | Some('e') | Some('i') | Some('o') | Some('u')) {
"an"
} else {
"a"
}
}
/// Join the item list as English: `a sword`, `a sword and a shield`,
/// `a sword, a shield, and a potion` (Oxford comma for 3+).
fn join_items(items: &[&str]) -> String {
let parts: Vec<String> = items
.iter()
.map(|i| format!("{} {}", article(i), i))
.collect();
match parts.as_slice() {
[] => String::new(),
[one] => one.clone(),
[a, b] => format!("{a} and {b}"),
rest => {
let (last, head) = rest.split_last().unwrap();
format!("{}, and {}", head.join(", "), last)
}
}
}
impl Level for DictList {
fn id(&self) -> u8 {
5
}
fn name(&self) -> &'static str {
"Chambers"
}
fn generate(&self, seed: u64) -> Generated {
let mut rng = ChaCha8Rng::seed_from_u64(seed ^ 0x0000_0000_0000_0005);
let n = rng.gen_range(2..=3);
let chamber_names: Vec<&'static str> =
CHAMBERS.choose_multiple(&mut rng, n).copied().collect();
let mut inner = Mapping::new();
let mut sentences = Vec::new();
for name in &chamber_names {
let item_n = rng.gen_range(2..=3);
let items: Vec<&'static str> =
ITEMS.choose_multiple(&mut rng, item_n).copied().collect();
let seq: Sequence = items
.iter()
.map(|i| Value::String((*i).to_string()))
.collect();
inner.insert(Value::String((*name).to_string()), Value::Sequence(seq));
let be = if items.len() == 1 { "is" } else { "are" };
sentences.push(format!(
"There {be} {} inside {} {name}.",
join_items(&items),
article(name),
));
}
let mut top = Mapping::new();
top.insert(
Value::String("chambers".to_string()),
Value::Mapping(inner),
);
let target_yaml =
serde_yaml::to_string(&Value::Mapping(top)).expect("serialise mapping");
let mut d = Describer::new();
d.register(
"l05",
"Several chambers branch off, each with its own contents:\n\
{% for s in sentences %}\n {{ s }}{% endfor %}\n\n\
💡 Wrap the whole tree under a `chambers:` key — a dict of lists.",
)
.expect("register template");
let description = d
.render("l05", &DescCtx { sentences })
.expect("render template");
Generated {
target_yaml,
description,
flavor: "🏛 You enter a hall. Doors lead to many chambers.".to_string(),
}
}
}

113
src/levels/l06_anchors.rs Normal file
View File

@@ -0,0 +1,113 @@
//! Level 6 — anchors. Two rooms share the same trap — define it once.
//!
//! Paired design note: `l06.md`.
//!
//! Note: serde_yaml resolves aliases at parse time, so the target is
//! emitted **expanded** (the trap dict appears in each room). Players
//! who use anchors/aliases will produce the same parsed `Value` and
//! pass via the semantic short-circuit. Players who paste the dict
//! verbatim also pass.
use rand::seq::SliceRandom;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
use serde::Serialize;
use serde_yaml::{Mapping, Value};
use crate::describe::Describer;
use super::{Generated, Level};
pub struct Anchors;
const ROOM_NAMES: &[&str] = &["north", "south", "east", "west"];
const TRAP_TYPES: &[&str] = &["pit", "snare", "dart", "rune"];
#[derive(Serialize)]
struct DescCtx {
trap_type: String,
trap_depth: i64,
trap_spikes: bool,
rooms: Vec<String>,
}
impl Level for Anchors {
fn id(&self) -> u8 {
6
}
fn name(&self) -> &'static str {
"Anchors"
}
fn generate(&self, seed: u64) -> Generated {
let mut rng = ChaCha8Rng::seed_from_u64(seed ^ 0x0000_0000_0000_0006);
let trap_type = *TRAP_TYPES.choose(&mut rng).expect("non-empty");
let trap_depth = rng.gen_range(10..=30i64);
let trap_spikes = rng.gen_bool(0.5);
let n_rooms = rng.gen_range(2..=3);
let rooms: Vec<&'static str> = ROOM_NAMES
.choose_multiple(&mut rng, n_rooms)
.copied()
.collect();
let mut trap = Mapping::new();
trap.insert(
Value::String("type".to_string()),
Value::String(trap_type.to_string()),
);
trap.insert(Value::String("depth".to_string()), Value::from(trap_depth));
trap.insert(
Value::String("spikes".to_string()),
Value::Bool(trap_spikes),
);
let mut rooms_map = Mapping::new();
for r in &rooms {
rooms_map.insert(
Value::String((*r).to_string()),
Value::Mapping(trap.clone()),
);
}
let mut top = Mapping::new();
top.insert(Value::String("trap".to_string()), Value::Mapping(trap));
top.insert(
Value::String("rooms".to_string()),
Value::Mapping(rooms_map),
);
let target_yaml =
serde_yaml::to_string(&Value::Mapping(top)).expect("serialise mapping");
let mut d = Describer::new();
d.register(
"l06",
"A single trap recurs through these halls:\n\
- type: {{ trap_type }}\n\
- depth: {{ trap_depth }}\n\
- spikes: {{ trap_spikes }}\n\
\n\
Reuse it for these rooms: {% for r in rooms %}{{ r }}{% if not loop.last %}, {% endif %}{% endfor %}.\n\
💡 Define `trap: &name` once and reference it as `*name` in every room.",
)
.expect("register template");
let description = d
.render(
"l06",
&DescCtx {
trap_type: trap_type.to_string(),
trap_depth,
trap_spikes,
rooms: rooms.iter().map(|s| s.to_string()).collect(),
},
)
.expect("render template");
Generated {
target_yaml,
description,
flavor: "🪤 A trap recurs through these halls.".to_string(),
}
}
}

144
src/levels/l07_complex.rs Normal file
View File

@@ -0,0 +1,144 @@
//! Level 7 — complex data structures. The full map of a single floor.
//!
//! Paired design note: `l07.md`.
use rand::seq::SliceRandom;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
use serde::Serialize;
use serde_yaml::{Mapping, Sequence, Value};
use crate::describe::Describer;
use super::{Generated, Level};
pub struct Complex;
const EXITS: &[&str] = &["north", "south", "east", "west", "up", "down"];
const CONTENTS: &[&str] = &[
"torch", "bench", "gold", "ruby", "scroll", "tome", "dagger", "shield",
];
const ROOMS: &[(&str, &str)] = &[
("entrance", "hall"),
("treasury", "vault"),
("library", "study"),
("kitchen", "scullery"),
];
#[derive(Serialize)]
struct DescCtx {
floor: i64,
rooms: Vec<RoomDesc>,
}
#[derive(Serialize)]
struct RoomDesc {
name: String,
kind: String,
locked: bool,
exits: Vec<String>,
contents: Vec<String>,
}
impl Level for Complex {
fn id(&self) -> u8 {
7
}
fn name(&self) -> &'static str {
"The Floor Map"
}
fn generate(&self, seed: u64) -> Generated {
let mut rng = ChaCha8Rng::seed_from_u64(seed ^ 0x0000_0000_0000_0007);
let floor = rng.gen_range(1..=5i64);
let chosen: Vec<&(&'static str, &'static str)> =
ROOMS.choose_multiple(&mut rng, 2).collect();
let mut rooms_map = Mapping::new();
let mut desc_rooms = Vec::new();
for (name, kind) in &chosen {
let exits_n = rng.gen_range(1..=3);
let exits: Vec<&'static str> =
EXITS.choose_multiple(&mut rng, exits_n).copied().collect();
let contents_n = rng.gen_range(1..=3);
let contents: Vec<&'static str> = CONTENTS
.choose_multiple(&mut rng, contents_n)
.copied()
.collect();
let locked = rng.gen_bool(0.5);
let mut room = Mapping::new();
room.insert(
Value::String("type".to_string()),
Value::String((*kind).to_string()),
);
room.insert(Value::String("locked".to_string()), Value::Bool(locked));
let exits_seq: Sequence = exits
.iter()
.map(|e| Value::String((*e).to_string()))
.collect();
let contents_seq: Sequence = contents
.iter()
.map(|c| Value::String((*c).to_string()))
.collect();
room.insert(
Value::String("exits".to_string()),
Value::Sequence(exits_seq),
);
room.insert(
Value::String("contents".to_string()),
Value::Sequence(contents_seq),
);
rooms_map.insert(Value::String((*name).to_string()), Value::Mapping(room));
desc_rooms.push(RoomDesc {
name: (*name).to_string(),
kind: (*kind).to_string(),
locked,
exits: exits.iter().map(|s| s.to_string()).collect(),
contents: contents.iter().map(|s| s.to_string()).collect(),
});
}
let mut top = Mapping::new();
top.insert(Value::String("floor".to_string()), Value::from(floor));
top.insert(
Value::String("rooms".to_string()),
Value::Mapping(rooms_map),
);
let target_yaml =
serde_yaml::to_string(&Value::Mapping(top)).expect("serialise mapping");
let mut d = Describer::new();
// No tab characters: ratatui's Paragraph renders tabs unevenly,
// which combined with the typewriter's progressive reveal can
// produce overlapping characters. Use plain spaces for indents.
d.register(
"l07",
"Floor {{ floor }}.\n\n\
{% for r in rooms %}{{ r.name }} — a {{ r.kind }} (locked: {{ r.locked }})\n\
exits: {% for e in r.exits %}{{ e }}{% if not loop.last %}, {% endif %}{% endfor %}\n\
contents: {% for c in r.contents %}{{ c }}{% if not loop.last %}, {% endif %}{% endfor %}\n\n\
{% endfor %}\
💡 Combine maps, lists, and scalars — `floor:` is an int, each room is a dict with two lists.",
)
.expect("register template");
let description = d
.render(
"l07",
&DescCtx {
floor,
rooms: desc_rooms,
},
)
.expect("render template");
Generated {
target_yaml,
description,
flavor: "🗺 The map of this floor is rich with detail.".to_string(),
}
}
}

111
src/levels/l08_tags.rs Normal file
View File

@@ -0,0 +1,111 @@
//! Level 8 — tags and newlines. The scroll preserves its lines and
//! demands explicit types.
//!
//! Paired design note: `l08.md`.
//!
//! The target value uses:
//! - a multi-line string for `scroll:` (block scalar `|` round-trips through
//! serde_yaml as a `Value::String` with embedded newlines),
//! - a fractional float for `weight:` (forces float type without needing the
//! `!!float` tag in the target text — but the player can use either),
//! - a string of digits for `title:` (player needs quotes or `!!str` to
//! avoid the integer interpretation).
use rand::seq::SliceRandom;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
use serde::Serialize;
use serde_yaml::{Mapping, Value};
use crate::describe::Describer;
use super::{Generated, Level};
pub struct Tags;
const VERBS: &[&str] = &["Beware", "Avoid", "Heed", "Mark"];
const NOUNS: &[&str] = &[
"the path that turns twice",
"the third spring",
"the silent statue",
"the moonlit door",
];
const TITLES: &[&str] = &["1024", "2048", "4096", "8192"];
#[derive(Serialize)]
struct DescCtx {
scroll_lines: Vec<String>,
weight: f64,
title: String,
}
impl Level for Tags {
fn id(&self) -> u8 {
8
}
fn name(&self) -> &'static str {
"Scroll of Tags"
}
fn generate(&self, seed: u64) -> Generated {
let mut rng = ChaCha8Rng::seed_from_u64(seed ^ 0x0000_0000_0000_0008);
let line_n = 2;
let scroll_lines: Vec<String> = (0..line_n)
.map(|_| {
let v = VERBS.choose(&mut rng).unwrap();
let n = NOUNS.choose(&mut rng).unwrap();
format!("{v} {n}.")
})
.collect();
// Block scalar `|` produces a string ending in `\n` after the last line.
let scroll_text = format!("{}\n", scroll_lines.join("\n"));
// Fractional weight so serde_yaml's float serialisation keeps the
// `.5` and matches the player's submission unambiguously.
let weight = rng.gen_range(1..=20) as f64 + 0.5;
let title = TITLES.choose(&mut rng).unwrap().to_string();
let mut top = Mapping::new();
top.insert(
Value::String("scroll".to_string()),
Value::String(scroll_text),
);
top.insert(Value::String("weight".to_string()), Value::from(weight));
top.insert(
Value::String("title".to_string()),
Value::String(title.clone()),
);
let target_yaml =
serde_yaml::to_string(&Value::Mapping(top)).expect("serialise mapping");
let mut d = Describer::new();
d.register(
"l08",
"A scroll demands its types. Match exactly:\n\
scroll: multi-line text{% for line in scroll_lines %}\n {{ line }}{% endfor %}\n\
weight: must parse as the float {{ weight }}\n\
title: must parse as the string \"{{ title }}\"\n\
💡 Block scalar `|` preserves newlines; `!!str` (or quotes) forces a digit-only string.",
)
.expect("register template");
let description = d
.render(
"l08",
&DescCtx {
scroll_lines,
weight,
title,
},
)
.expect("render template");
Generated {
target_yaml,
description,
flavor: "📜 An ancient scroll insists on its precise form.".to_string(),
}
}
}

135
src/levels/l09_operators.rs Normal file
View File

@@ -0,0 +1,135 @@
//! Level 9 — special operators. The merge key (`<<`) lets a door
//! inherit a template and override one field.
//!
//! Paired design note: `l09.md`.
//!
//! `serde_yaml` treats `<<` as a literal mapping key (it does NOT
//! perform YAML 1.1 merge-key resolution). The target therefore carries
//! a `<<` key whose value is the defaults dict, exactly as the player's
//! `<<: *defaults` parses.
use rand::seq::SliceRandom;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
use serde::Serialize;
use serde_yaml::{Mapping, Value};
use crate::describe::Describer;
use super::{Generated, Level};
pub struct Operators;
const MATERIALS: &[&str] = &["oak", "iron", "stone", "silver", "bone"];
#[derive(Serialize)]
struct DescCtx {
default_material: String,
default_locked: bool,
north_locked: bool,
south_material: String,
}
impl Level for Operators {
fn id(&self) -> u8 {
9
}
fn name(&self) -> &'static str {
"Merge Keys"
}
fn generate(&self, seed: u64) -> Generated {
let mut rng = ChaCha8Rng::seed_from_u64(seed ^ 0x0000_0000_0000_0009);
let default_material = (*MATERIALS.choose(&mut rng).unwrap()).to_string();
let default_locked = rng.gen_bool(0.5);
// The north door overrides locked; choose the opposite so the
// override is meaningful.
let north_locked = !default_locked;
// The south door overrides material; pick anything but default.
let other_materials: Vec<&str> = MATERIALS
.iter()
.filter(|m| **m != default_material)
.copied()
.collect();
let south_material = (*other_materials.choose(&mut rng).unwrap()).to_string();
// Build the defaults mapping (referenced by all doors).
let mut defaults = Mapping::new();
defaults.insert(
Value::String("material".to_string()),
Value::String(default_material.clone()),
);
defaults.insert(
Value::String("locked".to_string()),
Value::Bool(default_locked),
);
let mut north_door = Mapping::new();
north_door.insert(
Value::String("<<".to_string()),
Value::Mapping(defaults.clone()),
);
north_door.insert(
Value::String("locked".to_string()),
Value::Bool(north_locked),
);
let mut south_door = Mapping::new();
south_door.insert(
Value::String("<<".to_string()),
Value::Mapping(defaults.clone()),
);
south_door.insert(
Value::String("material".to_string()),
Value::String(south_material.clone()),
);
let mut top = Mapping::new();
top.insert(
Value::String("door_defaults".to_string()),
Value::Mapping(defaults),
);
top.insert(
Value::String("north_door".to_string()),
Value::Mapping(north_door),
);
top.insert(
Value::String("south_door".to_string()),
Value::Mapping(south_door),
);
let target_yaml =
serde_yaml::to_string(&Value::Mapping(top)).expect("serialise mapping");
let mut d = Describer::new();
d.register(
"l09",
"Two doors share a template:\n\
default material: {{ default_material }}\n\
default locked: {{ default_locked }}\n\
\n\
north_door overrides locked → {{ north_locked }}\n\
south_door overrides material → {{ south_material }}\n\
💡 Anchor the defaults (`door_defaults: &name`) and merge with `<<: *name` in each door.",
)
.expect("register template");
let description = d
.render(
"l09",
&DescCtx {
default_material,
default_locked,
north_locked,
south_material,
},
)
.expect("render template");
Generated {
target_yaml,
description,
flavor: "🚪 Two doors echo a single template.".to_string(),
}
}
}

101
src/levels/l10_dynamic.rs Normal file
View File

@@ -0,0 +1,101 @@
//! Level 10 — dynamic values. The vault ledger accepts numbers and
//! dates in many forms.
//!
//! Paired design note: `l10.md`.
//!
//! The target is canonical (decimal ints, decimal float, ISO date
//! string). The lesson is that the player can write equivalent values
//! in hex / octal / exponent forms — all parse to the same number.
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
use serde::Serialize;
use serde_yaml::{Mapping, Value};
use crate::describe::Describer;
use super::{Generated, Level};
pub struct Dynamic;
#[derive(Serialize)]
struct DescCtx {
gold_dec: i64,
gold_hex: String,
silver_dec: i64,
silver_oct: String,
experience: f64,
date: String,
}
impl Level for Dynamic {
fn id(&self) -> u8 {
10
}
fn name(&self) -> &'static str {
"Vault Ledger"
}
fn generate(&self, seed: u64) -> Generated {
let mut rng = ChaCha8Rng::seed_from_u64(seed ^ 0x0000_0000_0000_000A);
let gold = rng.gen_range(0x100..=0xFFFi64);
let silver = rng.gen_range(0o100..=0o777i64);
// Fractional float so the canonical serialisation keeps the `.5`.
let experience = rng.gen_range(10..=99) as f64 + 0.5;
let year = rng.gen_range(1100..=2050i64);
let month = rng.gen_range(1..=12i64);
let day = rng.gen_range(1..=28i64);
let date = format!("{year:04}-{month:02}-{day:02}");
let mut vault = Mapping::new();
vault.insert(Value::String("gold".to_string()), Value::from(gold));
vault.insert(Value::String("silver".to_string()), Value::from(silver));
vault.insert(
Value::String("experience".to_string()),
Value::from(experience),
);
vault.insert(
Value::String("date".to_string()),
Value::String(date.clone()),
);
let mut top = Mapping::new();
top.insert(Value::String("vault".to_string()), Value::Mapping(vault));
let target_yaml =
serde_yaml::to_string(&Value::Mapping(top)).expect("serialise mapping");
let mut d = Describer::new();
d.register(
"l10",
"The vault ledger demands its values:\n\
gold: {{ gold_dec }} (try hex: 0x{{ gold_hex }})\n\
silver: {{ silver_dec }} (try octal: 0o{{ silver_oct }})\n\
experience: {{ experience }} (any equivalent float form passes)\n\
date: {{ date }} (an ISO-8601 date string)\n\
💡 Any equivalent numeric form passes — what matters is the parsed value.",
)
.expect("register template");
let description = d
.render(
"l10",
&DescCtx {
gold_dec: gold,
gold_hex: format!("{:X}", gold),
silver_dec: silver,
silver_oct: format!("{:o}", silver),
experience,
date,
},
)
.expect("render template");
Generated {
target_yaml,
description,
flavor: "🪙 A vault ledger awaits in many ciphers.".to_string(),
}
}
}

View File

@@ -0,0 +1,141 @@
//! Level 11 — advanced anchors. Anchor shapes inside a list, alias
//! them elsewhere.
//!
//! Paired design note: `l11.md`.
//!
//! Like L6, serde_yaml expands aliases on parse, so the emitted target
//! is the fully-inlined form. Players who use `&anchor` / `*alias`
//! produce the same `Value` and pass via the semantic short-circuit.
use rand::seq::SliceRandom;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha8Rng;
use serde::Serialize;
use serde_yaml::{Mapping, Sequence, Value};
use crate::describe::Describer;
use super::{Generated, Level};
pub struct AdvAnchors;
const SHAPES: &[(&str, i64)] = &[
("triangle", 3),
("square", 4),
("pentagon", 5),
("hexagon", 6),
("heptagon", 7),
("octagon", 8),
];
#[derive(Serialize)]
struct DescCtx {
shapes: Vec<ShapeDesc>,
copies: Vec<String>,
}
#[derive(Serialize)]
struct ShapeDesc {
name: String,
sides: i64,
interior_angle_sum: i64,
}
fn shape_value(name: &str, sides: i64) -> Value {
let mut m = Mapping::new();
m.insert(
Value::String("name".to_string()),
Value::String(name.to_string()),
);
m.insert(Value::String("sides".to_string()), Value::from(sides));
m.insert(
Value::String("interior".to_string()),
Value::from((sides - 2) * 180),
);
Value::Mapping(m)
}
impl Level for AdvAnchors {
fn id(&self) -> u8 {
11
}
fn name(&self) -> &'static str {
"Advanced Anchors"
}
fn generate(&self, seed: u64) -> Generated {
let mut rng = ChaCha8Rng::seed_from_u64(seed ^ 0x0000_0000_0000_000B);
let n = rng.gen_range(2..=3);
let picked: Vec<(&'static str, i64)> = SHAPES
.choose_multiple(&mut rng, n)
.copied()
.collect();
// The defining `shapes:` list.
let shapes_seq: Sequence = picked
.iter()
.map(|(name, sides)| shape_value(name, *sides))
.collect();
// `copies:` — random selections with possible repetition.
let m = rng.gen_range(3..=4);
let mut copies_seq = Sequence::new();
let mut copy_names = Vec::new();
for _ in 0..m {
let (name, sides) = picked.choose(&mut rng).unwrap();
copies_seq.push(shape_value(name, *sides));
copy_names.push((*name).to_string());
}
let mut top = Mapping::new();
top.insert(
Value::String("shapes".to_string()),
Value::Sequence(shapes_seq),
);
top.insert(
Value::String("copies".to_string()),
Value::Sequence(copies_seq),
);
let target_yaml =
serde_yaml::to_string(&Value::Mapping(top)).expect("serialise mapping");
let shape_descs: Vec<ShapeDesc> = picked
.iter()
.map(|(name, sides)| ShapeDesc {
name: (*name).to_string(),
sides: *sides,
interior_angle_sum: (sides - 2) * 180,
})
.collect();
let mut d = Describer::new();
d.register(
"l11",
"Shapes are defined once and reused.\n\
Definitions:\n\
{% for s in shapes %}- {{ s.name }}: sides={{ s.sides }}, interior={{ s.interior_angle_sum }}\n\
{% endfor %}\n\
Copies, in order: {% for c in copies %}{{ c }}{% if not loop.last %}, {% endif %}{% endfor %}\n\
💡 Anchor each shape in the list with `- &name`, then alias by `*name` in copies.",
)
.expect("register template");
let description = d
.render(
"l11",
&DescCtx {
shapes: shape_descs,
copies: copy_names,
},
)
.expect("render template");
Generated {
target_yaml,
description,
flavor: "🔺 The geometry chamber repeats its forms.".to_string(),
}
}
}

View File

@@ -12,32 +12,59 @@
pub mod l01_minimum;
pub mod l02_kv;
pub mod l03_dict;
pub mod l04_list;
pub mod l05_dict_list;
pub mod l06_anchors;
pub mod l07_complex;
pub mod l08_tags;
pub mod l09_operators;
pub mod l10_dynamic;
pub mod l11_adv_anchors;
use serde::{Deserialize, Serialize};
/// Game-wide difficulty. Chosen once on the TierSelect screen; persisted
/// in `Progress.tier`. Maps to a fixed passing threshold per level.
/// Awarded per level based on the grade score. Replaces the old
/// game-wide difficulty tier. Thresholds:
/// - Gold ≥ 95 %
/// - Silver ≥ 80 %
/// - Bronze ≥ 70 %
/// - Below 70 % → no nugget (retry).
#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub enum Difficulty {
Easy,
Medium,
Hard,
pub enum Nugget {
Bronze,
Silver,
Gold,
}
impl Difficulty {
pub fn threshold(self) -> f64 {
match self {
Self::Easy => 0.70,
Self::Medium => 0.80,
Self::Hard => 0.95,
impl Nugget {
/// Map a grade ratio (0.0..=1.0) to a nugget. `None` means the
/// player didn't clear the level — retry without advancing.
pub fn from_score(score: f64) -> Option<Self> {
if score >= 0.95 {
Some(Nugget::Gold)
} else if score >= 0.80 {
Some(Nugget::Silver)
} else if score >= 0.70 {
Some(Nugget::Bronze)
} else {
None
}
}
pub fn label(self) -> &'static str {
pub fn emoji(self) -> &'static str {
match self {
Self::Easy => "Easy (70%)",
Self::Medium => "Medium (80%)",
Self::Hard => "Hard (95%)",
Self::Bronze => "🥉",
Self::Silver => "🥈",
Self::Gold => "🥇",
}
}
pub fn name(self) -> &'static str {
match self {
Self::Bronze => "Bronze",
Self::Silver => "Silver",
Self::Gold => "Gold",
}
}
}
@@ -63,5 +90,14 @@ pub fn registry() -> Vec<Box<dyn Level>> {
vec![
Box::new(l01_minimum::Minimum),
Box::new(l02_kv::KeyValue),
Box::new(l03_dict::Dict),
Box::new(l04_list::List),
Box::new(l05_dict_list::DictList),
Box::new(l06_anchors::Anchors),
Box::new(l07_complex::Complex),
Box::new(l08_tags::Tags),
Box::new(l09_operators::Operators),
Box::new(l10_dynamic::Dynamic),
Box::new(l11_adv_anchors::AdvAnchors),
]
}

View File

@@ -1,3 +1,4 @@
pub mod config;
pub mod describe;
pub mod levels;
pub mod progress;
@@ -68,47 +69,258 @@ mod smoke {
// (4) Progress round-trips through the same YAML pipeline that disk
// save/load will use.
let p = progress::Progress {
tier: Some(levels::Difficulty::Medium),
completed: vec![1, 2],
nuggets: vec![(1, levels::Nugget::Silver), (2, levels::Nugget::Gold)],
current_level: 3,
current_seed: 0xCAFE,
attempts: 1,
};
let s = serde_yaml::to_string(&p).unwrap();
let loaded: progress::Progress = serde_yaml::from_str(&s).unwrap();
assert_eq!(loaded.tier, p.tier);
assert_eq!(loaded.nuggets, p.nuggets);
assert_eq!(loaded.current_level, p.current_level);
assert_eq!(loaded.current_seed, p.current_seed);
}
#[test]
fn levels_generate_canonical_yaml() {
let registry = levels::registry();
assert_eq!(registry.len(), 2);
// ---- Per-level tests --------------------------------------------
//
// One test per level. `checked_level` runs the invariants every
// level must satisfy (correct id, valid & deterministic canonical
// YAML, self-similarity 1.0); each test then pins the *shape* its
// design note promises and, where it is the whole lesson, the
// semantic forgiveness.
// Level 1: any null-equivalent passes via the semantic short-circuit.
let g1 = registry[0].generate(0);
let parsed: serde_yaml::Value = serde_yaml::from_str(&g1.target_yaml).unwrap();
assert!(parsed.is_null());
/// Look up a string key in a YAML mapping, panicking with a clear
/// message if it is missing — keeps the per-level assertions terse.
fn field<'a>(v: &'a Value, key: &str) -> &'a Value {
v.get(key)
.unwrap_or_else(|| panic!("expected key `{key}` in {v:?}"))
}
/// Parse a target YAML string, asserting it is well-formed.
fn parse(yaml: &str) -> Value {
serde_yaml::from_str(yaml).expect("target is valid YAML")
}
/// Generate level `index` (0-based) with `seed`, assert the invariants
/// every level must satisfy, and return its output for shape checks:
/// - the level reports `id == index + 1`,
/// - the target is valid YAML,
/// - generation is deterministic for a given seed,
/// - the canonical target scores 1.0 against itself.
fn checked_level(index: usize, seed: u64) -> levels::Generated {
let registry = levels::registry();
let level = &registry[index];
let want_id = index as u8 + 1;
assert_eq!(
similarity::semantic_or_textual(&g1.target_yaml, "---"),
level.id(),
want_id,
"registry index {index} must hold level {want_id}"
);
let g = level.generate(seed);
serde_yaml::from_str::<Value>(&g.target_yaml)
.unwrap_or_else(|e| panic!("level {want_id} target is not valid YAML: {e}"));
let again = level.generate(seed);
assert_eq!(
g.target_yaml, again.target_yaml,
"level {want_id} must be deterministic for a given seed"
);
assert_eq!(
similarity::semantic_or_textual(&g.target_yaml, &g.target_yaml),
1.0,
"level {want_id} target must score 1.0 against itself"
);
g
}
#[test]
fn registry_lists_all_eleven_levels() {
assert_eq!(
levels::registry().len(),
11,
"all 11 levels must be registered"
);
}
#[test]
fn level_01_minimum_is_a_null_document() {
// Any null-equivalent passes via the semantic short-circuit.
let g = checked_level(0, 0);
assert!(parse(&g.target_yaml).is_null(), "the minimum YAML is null");
assert_eq!(
similarity::semantic_or_textual(&g.target_yaml, "---"),
1.0,
"`---` should be accepted as the minimum YAML"
);
assert_eq!(
similarity::semantic_or_textual(&g1.target_yaml, "null"),
1.0
similarity::semantic_or_textual(&g.target_yaml, "null"),
1.0,
"`null` should be accepted as the minimum YAML"
);
}
// Level 2: deterministic per seed, non-empty mapping.
let g2 = registry[1].generate(42);
let v2: serde_yaml::Value = serde_yaml::from_str(&g2.target_yaml).unwrap();
let m = v2.as_mapping().expect("level 2 produces a mapping");
assert!(!m.is_empty());
let g2_again = registry[1].generate(42);
assert_eq!(
g2.target_yaml, g2_again.target_yaml,
"same seed should produce the same target"
#[test]
fn level_02_key_value_is_a_non_empty_mapping() {
let g = checked_level(1, 42);
let v = parse(&g.target_yaml);
assert!(
!v.as_mapping()
.expect("level 2 produces a mapping")
.is_empty(),
"level 2 yields a non-empty mapping"
);
}
#[test]
fn level_03_dict_nests_typed_mappings() {
// A mapping of mappings; each inner mapping carries a `type` key.
let g = checked_level(2, 123);
let v = parse(&g.target_yaml);
let m = v.as_mapping().expect("level 3 produces a mapping");
assert!(!m.is_empty(), "at least one direction");
for (_dir, feature) in m {
feature.as_mapping().expect("level 3 inner is a mapping");
assert!(
feature.get("type").is_some(),
"each direction must carry a `type` key"
);
}
}
#[test]
fn level_04_chest_is_a_list() {
// `chest:` is a list of 35 item strings.
let v = parse(&checked_level(3, 4).target_yaml);
let chest = field(&v, "chest").as_sequence().expect("chest is a list");
assert!((3..=5).contains(&chest.len()), "chest holds 35 items");
assert!(chest.iter().all(Value::is_string), "every item is a string");
}
#[test]
fn level_05_chambers_is_a_dict_of_lists() {
// `chambers:` is a dict of 23 lists, 23 items each.
let v = parse(&checked_level(4, 5).target_yaml);
let chambers = field(&v, "chambers")
.as_mapping()
.expect("chambers is a dict");
assert!((2..=3).contains(&chambers.len()), "23 chambers");
for (_name, items) in chambers {
let items = items.as_sequence().expect("each chamber holds a list");
assert!((2..=3).contains(&items.len()), "23 items per chamber");
}
}
#[test]
fn level_06_trap_repeats_in_every_room() {
// `trap:` is defined once; every room repeats it verbatim, so a
// player using `&anchor`/`*alias` parses to the same Value.
let v = parse(&checked_level(5, 6).target_yaml);
let trap = field(&v, "trap");
for key in ["type", "depth", "spikes"] {
assert!(trap.get(key).is_some(), "trap carries `{key}`");
}
let rooms = field(&v, "rooms").as_mapping().expect("rooms is a dict");
assert!(!rooms.is_empty(), "at least one room");
for (_room, payload) in rooms {
assert_eq!(payload, trap, "every room repeats the trap definition");
}
}
#[test]
fn level_07_floor_map_nests_maps_and_lists() {
// `floor:` int + `rooms:` dict; each room nests two lists.
let v = parse(&checked_level(6, 7).target_yaml);
assert!(field(&v, "floor").is_i64(), "floor is an integer");
let rooms = field(&v, "rooms").as_mapping().expect("rooms is a dict");
assert!(!rooms.is_empty(), "at least one room");
for (_name, room) in rooms {
assert!(field(room, "type").is_string(), "room.type is a string");
assert!(field(room, "locked").is_bool(), "room.locked is a bool");
assert!(field(room, "exits").is_sequence(), "room.exits is a list");
assert!(
field(room, "contents").is_sequence(),
"room.contents is a list"
);
}
}
#[test]
fn level_08_scroll_keeps_explicit_types() {
// Explicit types: a multi-line string, a float, and a digit-only
// string that must NOT collapse to an integer.
let v = parse(&checked_level(7, 8).target_yaml);
let scroll = field(&v, "scroll").as_str().expect("scroll is a string");
assert!(scroll.contains('\n'), "scroll preserves its newlines");
assert!(field(&v, "weight").is_f64(), "weight is a float");
let title = field(&v, "title");
assert!(title.is_string(), "title stays a string, not an int");
assert!(
title.as_str().unwrap().chars().all(|c| c.is_ascii_digit()),
"title is digit-only — the point of the `!!str` lesson"
);
}
#[test]
fn level_09_doors_merge_shared_defaults() {
// Merge keys: each door carries a literal `<<` whose value is the
// shared defaults dict, plus its own override.
let v = parse(&checked_level(8, 9).target_yaml);
let defaults = field(&v, "door_defaults");
for door in ["north_door", "south_door"] {
assert_eq!(
field(field(&v, door), "<<"),
defaults,
"{door} merges the shared defaults via `<<`"
);
}
assert!(field(field(&v, "north_door"), "locked").is_bool());
assert!(field(field(&v, "south_door"), "material").is_string());
}
#[test]
fn level_10_ledger_forgives_numeric_forms() {
// The ledger: int gold/silver, float experience, ISO date. The
// lesson is numeric forgiveness, so hex must score a perfect match.
let g = checked_level(9, 10);
let v = parse(&g.target_yaml);
let vault = field(&v, "vault");
let gold = field(vault, "gold").as_i64().expect("gold is an integer");
assert!(field(vault, "silver").is_i64(), "silver is an integer");
assert!(field(vault, "experience").is_f64(), "experience is a float");
assert!(field(vault, "date").is_string(), "date is an ISO string");
let hex_candidate = g
.target_yaml
.replace(&format!("gold: {gold}"), &format!("gold: 0x{gold:X}"));
assert_ne!(hex_candidate, g.target_yaml, "hex rewrite must apply");
assert_eq!(
similarity::semantic_or_textual(&g.target_yaml, &hex_candidate),
1.0,
"writing gold in hex must still score a perfect match"
);
}
#[test]
fn level_11_copies_alias_defined_shapes() {
// `shapes:` defines polygons; `copies:` reuses them, so each copy
// is structurally identical to one of the definitions.
let v = parse(&checked_level(10, 11).target_yaml);
let shapes = field(&v, "shapes").as_sequence().expect("shapes is a list");
assert!((2..=3).contains(&shapes.len()), "23 defined shapes");
for s in shapes {
assert!(field(s, "name").is_string(), "shape.name is a string");
let sides = field(s, "sides").as_i64().expect("shape.sides is an int");
assert_eq!(
field(s, "interior").as_i64().expect("shape.interior is an int"),
(sides - 2) * 180,
"interior angle sum follows (n-2)·180"
);
}
let copies = field(&v, "copies").as_sequence().expect("copies is a list");
assert!((3..=4).contains(&copies.len()), "34 copies");
for c in copies {
assert!(shapes.contains(c), "every copy aliases a defined shape");
}
}
}

View File

@@ -4,13 +4,16 @@ use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use crate::levels::Difficulty;
use crate::levels::Nugget;
#[derive(Default, Serialize, Deserialize)]
#[serde(default)]
pub struct Progress {
pub tier: Option<Difficulty>,
pub completed: Vec<u8>,
pub current_level: u8,
/// Nuggets awarded per level: `(level_id, nugget)` in order of
/// completion. A level appears at most once (re-runs after reset
/// rebuild the list from scratch).
pub nuggets: Vec<(u8, Nugget)>,
pub current_level: u8, // 1-indexed; 0 means a new game
pub current_seed: u64,
pub attempts: u32,
}

1033
src/tui.rs

File diff suppressed because it is too large Load Diff