Modern Apps git

← Modern-Apps.git

voxels: give villagers 11 professions with leveled trade tables

Commit
ed1993fc25a8c599b229afbb4c26f0e5894abe61
Author
Vayun Mathur <[email protected]>
When
2026-08-05 16:47 UTC (4 months ago)
Parents
6253dc2

Diff

games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.ktindex f3a15382e5..fe5b5033f7 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt@@ -63,9 +63,9 @@ class MainActivity : ComponentActivity() {                 var chestOpen by remember { mutableStateOf(false) }                 var cutsJson by remember { mutableStateOf("[]") }                 var stonecutterOpen by remember { mutableStateOf(false) }-                var tradesJson by remember { mutableStateOf("[]") }+                var tradesJson by remember { mutableStateOf("{}") }                 var tradeOpen by remember { mutableStateOf(false) }-                LaunchedEffect(Unit) { if (VoxelsNative.isAvailable) try { recipesJson = VoxelsNative.getRecipesJson(); tradesJson = VoxelsNative.getTradesJson(); smeltingJson = VoxelsNative.getSmeltingJson(); blessingCatalogJson = VoxelsNative.getBlessingCatalogJson(); cutsJson = VoxelsNative.getCutsJson() } catch (_: Exception) {} }+                LaunchedEffect(Unit) { if (VoxelsNative.isAvailable) try { recipesJson = VoxelsNative.getRecipesJson(); smeltingJson = VoxelsNative.getSmeltingJson(); blessingCatalogJson = VoxelsNative.getBlessingCatalogJson(); cutsJson = VoxelsNative.getCutsJson() } catch (_: Exception) {} }                 var achievementsManager by remember { mutableStateOf<VoxelsAchievementsManager?>(null) }                 val newAchievement by (achievementsManager?.newAchievement?.collectAsState() ?: remember { mutableStateOf(null) }) @@ -169,7 +169,12 @@ class MainActivity : ComponentActivity() {                                         com.vayunmathur.games.voxels.util.MusicFx.toggle(this@MainActivity, com.vayunmathur.games.voxels.ui.discTrack[held])                                     }                                     15 -> stonecutterOpen = true // stonecutter-                                    20 -> tradeOpen = true // villager+                                    // Every villager has its own profession and level, so the stall is+                                    // read fresh from the one that was tapped.+                                    20 -> {+                                        tradesJson = try { VoxelsNative.getTradesJson() } catch (_: Exception) { "{}" }+                                        tradeOpen = true+                                    }                                     30 -> { // chest                                         containerJson = try { VoxelsNative.getContainerJson() } catch (_: Exception) { """{"slots":[]}""" }                                         chestOpen = true
games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/TradeScreen.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/TradeScreen.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/TradeScreen.ktindex 973fcb84a1..8f7e74056f 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/TradeScreen.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/TradeScreen.kt@@ -8,10 +8,12 @@ import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn-import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip@@ -24,19 +26,50 @@ import com.vayunmathur.games.voxels.util.VoxelsNative import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.library.ui.Text -private data class Trade(val cost: Int, val costN: Int, val give: Int, val giveN: Int)+private data class Trade(+    val cost: Int, val costN: Int,+    val cost2: Int, val cost2N: Int,+    val give: Int, val giveN: Int,+    val level: Int,+)++private data class Stall(+    val profession: String,+    val level: Int,+    val maxLevel: Int,+    val done: Int,+    val nextAt: Int?,+    val trades: List<Trade>,+)++private fun parseStall(json: String): Stall {+    return try {+        val o = org.json.JSONObject(json)+        val arr = o.optJSONArray("trades")+        val trades = (0 until (arr?.length() ?: 0)).map { i ->+            val t = arr!!.getJSONObject(i)+            Trade(+                t.getInt("cost"), t.getInt("costN"),+                t.optInt("cost2"), t.optInt("cost2N"),+                t.getInt("give"), t.getInt("giveN"),+                t.optInt("level", 1),+            )+        }+        Stall(+            o.optString("prof", ""), o.optInt("level", 1), o.optInt("maxLevel", 1),+            o.optInt("done"), if (o.isNull("nextAt")) null else o.optInt("nextAt"), trades,+        )+    } catch (_: Exception) {+        Stall("", 1, 1, 0, null, emptyList())+    }+}  @Composable fun TradeOverlay(tradesJson: String, onClose: () -> Unit) {-    val trades = remember(tradesJson) {-        try {-            val arr = org.json.JSONArray(tradesJson)-            (0 until arr.length()).map { i ->-                val o = arr.getJSONObject(i)-                Trade(o.getInt("cost"), o.getInt("costN"), o.getInt("give"), o.getInt("giveN"))-            }-        } catch (_: Exception) { emptyList() }-    }+    // Trading can level the villager up mid-session, which appends new offers, so the list is+    // re-read from the engine after every successful exchange rather than cached at open.+    var json by remember(tradesJson) { mutableStateOf(tradesJson) }+    val stall = remember(json) { parseStall(json) }     Box(         Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.6f)).pointerInput(Unit) { detectTapGestures { onClose() } },         contentAlignment = Alignment.Center@@ -46,20 +79,53 @@ fun TradeOverlay(tradesJson: String, onClose: () -> Unit) {                 .pointerInput(Unit) { detectTapGestures { } }.padding(16.dp),             horizontalAlignment = Alignment.CenterHorizontally         ) {-            Text(stringResource(R.string.villager_trades), color = Color.White, fontSize = 18.sp)-            Text(stringResource(R.string.tap_a_trade_to_exchange_need_the_cost_it), color = Color.White.copy(0.6f), fontSize = 12.sp)+            Text(+                if (stall.profession.isEmpty()) stringResource(R.string.villager_trades) else stall.profession,+                color = Color.White, fontSize = 18.sp,+            )+            Text(+                stringResource(R.string.villager_level, stall.level, stall.maxLevel),+                color = Color(0xFF9CD08A), fontSize = 12.sp,+            )+            val nextAt = stall.nextAt+            Text(+                if (nextAt != null) stringResource(R.string.villager_next_tier, nextAt - stall.done)+                else stringResource(R.string.tap_a_trade_to_exchange_need_the_cost_it),+                color = Color.White.copy(0.6f), fontSize = 12.sp,+            )             Spacer(Modifier.height(10.dp))             LazyColumn(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) {-                items(trades.withIndex().toList()) { (i, t) ->-                    Row(-                        Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(Color.White.copy(0.07f))-                            .clickable { try { if (VoxelsNative.trade(i)) com.vayunmathur.games.voxels.util.SoundFx.playPlace() } catch (_: Exception) {} }-                            .padding(10.dp),-                        verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)-                    ) {-                        ItemChip(t.cost, t.costN)-                        Text("→", color = Color.White.copy(0.8f), fontSize = 20.sp)-                        ItemChip(t.give, t.giveN)+                stall.trades.forEachIndexed { i, t ->+                    if (i == 0 || stall.trades[i - 1].level != t.level) {+                        item(key = "tier${t.level}") {+                            Text(+                                stringResource(R.string.villager_tier, t.level),+                                color = Color.White.copy(0.4f), fontSize = 11.sp,+                            )+                        }+                    }+                    item(key = "trade$i") {+                        Row(+                            Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).background(Color.White.copy(0.07f))+                                .clickable {+                                    try {+                                        if (VoxelsNative.trade(i)) {+                                            com.vayunmathur.games.voxels.util.SoundFx.playPlace()+                                            json = VoxelsNative.getTradesJson()+                                        }+                                    } catch (_: Exception) {}+                                }+                                .padding(10.dp),+                            verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)+                        ) {+                            ItemChip(t.cost, t.costN)+                            if (t.cost2 != 0) {+                                Text("+", color = Color.White.copy(0.8f), fontSize = 16.sp)+                                ItemChip(t.cost2, t.cost2N)+                            }+                            Text("→", color = Color.White.copy(0.8f), fontSize = 20.sp)+                            ItemChip(t.give, t.giveN)+                        }                     }                 }             }
games/voxels/src/main/res/values/strings.xml
diff --git a/games/voxels/src/main/res/values/strings.xml b/games/voxels/src/main/res/values/strings.xmlindex 334486b9ad..221ec32b42 100644--- a/games/voxels/src/main/res/values/strings.xml+++ b/games/voxels/src/main/res/values/strings.xml@@ -21,6 +21,9 @@     <string name="create_play">Create &amp; Play</string>     <string name="villager_trades">Villager Trades</string>     <string name="tap_a_trade_to_exchange_need_the_cost_it">Tap a trade to exchange (need the cost items).</string>+    <string name="villager_level">Level %1$d of %2$d</string>+    <string name="villager_next_tier">%1$d more trades unlocks the next tier.</string>+    <string name="villager_tier">Tier %1$d</string>     <string name="seed_2">Seed: %1$s  •  %2$s</string>     <string name="estus">Estus ×%1$s</string>     <string name="down">Down</string>
games/voxels/src/main/rust/src/engine.rs
diff --git a/games/voxels/src/main/rust/src/engine.rs b/games/voxels/src/main/rust/src/engine.rsindex 069d3219f2..2e82da09de 100644--- a/games/voxels/src/main/rust/src/engine.rs+++ b/games/voxels/src/main/rust/src/engine.rs@@ -54,6 +54,10 @@ pub struct EngineState {     pub deepest_y: i32,     // Throttle for the Lu Ban mending blessing.     pub mend_cd: f32,+    // Which villager's trade list is open, and how many trades each profession has completed (the+    // latter is what levels them up, since villager mobs aren't persisted).+    pub trade_prof: u8,+    pub trades_done: [u32; crate::villager::ALL.len()], }  // One furnace job at a time, owned by the world rather than by a specific furnace block: the player@@ -148,6 +152,10 @@ pub fn init_engine(files_dir: String, seed: u32) -> bool {     let mut dim_visited = [false; 3];     for (i, v) in progress.dim_visited.iter().enumerate().take(3) { dim_visited[i] = *v; }     dim_visited[dim as usize] = true;+    // Trade counts are stored as a Vec so old saves load; a short or long one is padded/truncated.+    let mut trades_done = [0u32; crate::villager::ALL.len()];+    for (i, n) in progress.trades_done.iter().enumerate().take(trades_done.len()) { trades_done[i] = *n; }+     // Rewind the clock so the world resumes at the time of day it was saved at.     let start_time = Instant::now()         .checked_sub(std::time::Duration::from_secs_f32(progress.world_secs.clamp(0.0, 86_400.0)))@@ -191,6 +199,8 @@ pub fn init_engine(files_dir: String, seed: u32) -> bool {         best_beacon: progress.best_beacon,         deepest_y: if had_save { progress.deepest_y } else { py as i32 },         mend_cd: 0.0,+        trade_prof: 0,+        trades_done,     });     INIT_DONE.store(true, Ordering::SeqCst);     true@@ -246,6 +256,7 @@ pub fn destroy_engine() {                 best_beacon: state.best_beacon,                 deepest_y: state.deepest_y,                 blessings: state.player.blessings,+                trades_done: state.trades_done.to_vec(),             },         };         let _ = crate::world::save::save_player(&state.save_dir, &ps);@@ -729,12 +740,34 @@ pub fn get_smelt_json() -> String { cref(&SMELT_CACHE, "{}").lock().map(|c| c.cl pub fn inventory_move(from: usize, to: usize) { with_engine(|s| s.inventory.move_item(from, to)); } pub fn inventory_give(id: u8) { with_engine(|s| s.inventory.give(id)); } pub fn inventory_craft(recipe: usize) -> bool { with_engine(|s| s.inventory.craft(recipe)).unwrap_or(false) }-pub fn do_trade(idx: usize) -> bool { with_engine(|s| s.inventory.trade(idx)).unwrap_or(false) }+pub fn do_trade(idx: usize) -> bool {+    with_engine(|s| {+        let prof = crate::villager::Profession::from_index(s.trade_prof as usize);+        let level = crate::villager::level_for(s.trades_done[prof.index()]);+        let Some(offer) = crate::villager::offers(prof, level).get(idx).copied() else { return false; };+        if !s.inventory.trade_offer(&offer) { return false; }+        s.trades_done[prof.index()] = s.trades_done[prof.index()].saturating_add(1);+        true+    }).unwrap_or(false)+} pub fn get_trades_json() -> String {-    let items: Vec<_> = crate::inventory::TRADES.iter()-        .map(|(c, cn, g, gn)| serde_json::json!({"cost": c, "costN": cn, "give": g, "giveN": gn}))-        .collect();-    serde_json::json!(items).to_string()+    with_engine(|s| {+        let prof = crate::villager::Profession::from_index(s.trade_prof as usize);+        let done = s.trades_done[prof.index()];+        let level = crate::villager::level_for(done);+        let items: Vec<_> = crate::villager::offers(prof, level).iter().enumerate()+            .map(|(i, o)| serde_json::json!({+                "cost": o.cost, "costN": o.cost_n,+                "cost2": o.cost2, "cost2N": o.cost2_n,+                "give": o.give, "giveN": crate::villager::give_count(o),+                "level": crate::villager::level_of_offer(prof, i),+            }))+            .collect();+        serde_json::json!({+            "prof": prof.name(), "level": level, "maxLevel": crate::villager::MAX_LEVEL,+            "done": done, "nextAt": crate::villager::next_level_at(level), "trades": items,+        }).to_string()+    }).unwrap_or_else(|| "{}".to_string()) }  // The stonecutter's whole catalog; the UI filters it down to what the player is carrying.@@ -1511,7 +1544,10 @@ pub fn place_block_at(px: f32, py: f32) -> i32 {             let block_hit = crate::raycast::raycast(&state.chunks, o, d, reach);             let bdist = block_hit.as_ref().map(|h| (vec3(h.pos.0 as f32 + 0.5, h.pos.1 as f32 + 0.5, h.pos.2 as f32 + 0.5) - o).length()).unwrap_or(f32::INFINITY);             if let Some(idx) = nearest_mob_hit(state, o, d, reach - 1.5, bdist) {-                if state.mobs[idx].kind == MobKind::Villager { return 20; }+                if state.mobs[idx].kind == MobKind::Villager {+                    state.trade_prof = state.mobs[idx].profession;+                    return 20;+                }             }             if let Some(hit) = block_hit {                 let (x, y, z) = hit.pos;
games/voxels/src/main/rust/src/entity.rs
diff --git a/games/voxels/src/main/rust/src/entity.rs b/games/voxels/src/main/rust/src/entity.rsindex 3f29eaffdf..d0a6a71f53 100644--- a/games/voxels/src/main/rust/src/entity.rs+++ b/games/voxels/src/main/rust/src/entity.rs@@ -165,6 +165,9 @@ pub struct Mob {     anim: f32,     on_ground: bool,     rng: u32,+    /// Villagers only: which trade table this one keeps. Drawn from the spawn seed, so it's stable for+    /// the mob's lifetime even though mobs aren't saved.+    pub profession: u8, }  fn xorshift(s: &mut u32) -> f32 {@@ -183,7 +186,8 @@ pub struct Terrain<'a> { impl Mob {     pub fn new(kind: MobKind, pos: Vec3, seed: u32) -> Self {         Mob { kind, pos, vel: Vec3::ZERO, yaw: 0.0, health: kind.max_health(), attack_cd: 0.0, fuse: 0.0,-            target_yaw: 0.0, wander: 0.0, anim: 0.0, on_ground: false, rng: seed | 1 }+            target_yaw: 0.0, wander: 0.0, anim: 0.0, on_ground: false, rng: seed | 1,+            profession: crate::villager::Profession::from_seed(seed | 1).index() as u8 }     }      pub fn tick(&mut self, dt: f32, player: Vec3, terrain: &Terrain) {@@ -294,11 +298,21 @@ impl Mob {         Some(top)     } +    /// A villager wears its profession's colours; everything else uses its skin unmodified.+    fn tint(&self) -> [f32; 3] {+        if self.kind == MobKind::Villager {+            crate::villager::Profession::from_index(self.profession as usize).tint()+        } else {+            [1.0, 1.0, 1.0]+        }+    }+     fn append_mesh(&self, verts: &mut Vec<Vertex>, indices: &mut Vec<u32>) {         let col = (self.kind.cell() % 4) as f32 * CELL;         let row = (self.kind.cell() / 4) as f32 * CELL;         // Procedural skins are uniform, so sample the cell centre for every face.         let uniform = self.kind.uniform_skin();+        let tint = self.tint();         let (yc, ys) = (self.yaw.cos(), self.yaw.sin());         for part in self.kind.parts() {             let swing = if part.leg != 0.0 { self.anim.sin() * 0.55 * part.leg } else { 0.0 };@@ -349,7 +363,7 @@ impl Mob {                     wp = Vec3::new(rx, wp.y, rz) + self.pos;                     let uv = if uniform { [(col + 32.0) / ATLAS, (row + 32.0) / ATLAS] }                              else { [(col + uvc[c][0]) / ATLAS, (row + uvc[c][1]) / ATLAS] };-                    verts.push(Vertex { pos: [wp.x, wp.y, wp.z], uv, color: [1.0,1.0,1.0], ao: 1.0, tile_idx: 0.0, normal: nrm, light: 0.0 });+                    verts.push(Vertex { pos: [wp.x, wp.y, wp.z], uv, color: tint, ao: 1.0, tile_idx: 0.0, normal: nrm, light: 0.0 });                 }                 indices.extend_from_slice(&[base, base+1, base+2, base, base+2, base+3]);             }
games/voxels/src/main/rust/src/inventory.rs
diff --git a/games/voxels/src/main/rust/src/inventory.rs b/games/voxels/src/main/rust/src/inventory.rsindex e301c010e9..c23fb45813 100644--- a/games/voxels/src/main/rust/src/inventory.rs+++ b/games/voxels/src/main/rust/src/inventory.rs@@ -164,26 +164,7 @@ pub fn fuel_secs(id: u8) -> f32 { // Fuels with no use other than burning, tried before anything a player might be saving. const DEDICATED_FUELS: [u8; 3] = [157, 84, 192]; -// Villager trades: (cost_id, cost_count, give_id, give_count). Emerald = item 156.-pub const TRADES: [(u8, i32, u8, i32); 16] = [-    (156, 3, 168, 1),  // 3 Emerald -> Iron Sword-    (156, 6, 172, 1),  // 6 Emerald -> Iron Chestplate-    (156, 2, 133, 1),  // 2 Emerald -> Golden Apple-    (156, 1, 131, 6),  // 1 Emerald -> 6 Bread-    (156, 4, 128, 1),  // 4 Emerald -> Estus Flask-    (157, 12, 156, 1), // 12 Coal -> 1 Emerald-    (137, 6, 156, 2),  // 6 Leather -> 2 Emerald-    // The village market: produce and prepared dishes the player can't grow or catch themselves.-    (156, 1, 135, 4),  // 1 Emerald -> 4 Carrots-    (156, 1, 146, 4),  // 1 Emerald -> 4 Baked Potatoes-    (156, 1, 136, 3),  // 1 Emerald -> 3 Melon Slices-    (156, 2, 132, 4),  // 2 Emerald -> 4 Cooked Fish-    (156, 2, 148, 4),  // 2 Emerald -> 4 Cooked Salmon-    (156, 2, 150, 3),  // 2 Emerald -> 3 Cooked Rabbit-    (156, 2, 134, 3),  // 2 Emerald -> 3 Brownies-    (156, 2, 153, 4),  // 2 Emerald -> 4 Chocolate Chip Cookies-    (222, 8, 156, 1),  // 8 Raw Meat -> 1 Emerald (a butcher's price)-];+// Villager trades live in `villager.rs`, tiered per profession. Emerald = item 156.  // Which shelf of the crafting menu a recipe belongs on. Purely for the UI — the recipe table itself // stays a flat list so indices remain stable.@@ -346,13 +327,17 @@ impl Inventory {         self.armor[slot] = InvSlot { id, count: dur };         if old.id != 0 { Some(old) } else { None }     }-    // Execute a villager trade if the player can afford it.-    pub fn trade(&mut self, idx: usize) -> bool {-        let Some(&(c, cn, g, gn)) = TRADES.get(idx) else { return false; };-        if self.count_of(c) < cn { return false; }-        self.remove_count(c, cn);-        if crate::item::has_durability(g) { self.add_item_with_count(g, crate::item::max_durability(g)); }-        else { for _ in 0..gn { self.add_block(g); } }+    // Execute a villager trade if the player can afford it and has somewhere to put the goods.+    // Both costs are checked before either is taken, so a half-affordable trade consumes nothing.+    pub fn trade_offer(&mut self, o: &crate::villager::Offer) -> bool {+        let give_n = crate::villager::give_count(o);+        if self.count_of(o.cost) < o.cost_n { return false; }+        if o.cost2 != 0 && self.count_of(o.cost2) < o.cost2_n { return false; }+        if !crate::item::has_durability(o.give) && !self.has_room_for(o.give, give_n) { return false; }+        self.remove_count(o.cost, o.cost_n);+        if o.cost2 != 0 { self.remove_count(o.cost2, o.cost2_n); }+        if crate::item::has_durability(o.give) { self.add_item_with_count(o.give, give_n); }+        else { for _ in 0..give_n { self.add_block(o.give); } }         true     }     // Execute a stonecutter conversion if the player has the input and room for the output.@@ -632,4 +617,37 @@ mod tests {         assert_eq!(fuel_secs(155), 0.0); // diamonds are not firewood         assert_eq!(fuel_secs(0), 0.0);     }++    // A two-ingredient trade must be all-or-nothing: the emeralds can't disappear when the player is+    // short on the material half.+    #[test]+    fn a_half_affordable_trade_takes_nothing() {+        use crate::villager::{Offer, EMERALD};+        let forge = Offer { cost: EMERALD, cost_n: 4, cost2: 154, cost2_n: 2, give: 167, give_n: 1 };+        let mut inv = Inventory::default();+        inv.slots[0] = InvSlot { id: EMERALD, count: 8 };+        inv.slots[1] = InvSlot { id: 154, count: 1 };++        assert!(!inv.trade_offer(&forge), "one iron ingot short");+        assert_eq!(inv.count_of(EMERALD), 8, "the emeralds must survive a refused trade");+        assert_eq!(inv.count_of(154), 1);++        inv.slots[1].count = 2;+        assert!(inv.trade_offer(&forge));+        assert_eq!(inv.count_of(EMERALD), 4);+        assert_eq!(inv.count_of(154), 0);+        assert!(inv.count_of(167) > 0, "the pickaxe arrives with durability");+    }++    #[test]+    fn trading_into_a_full_inventory_is_refused() {+        use crate::villager::{Offer, EMERALD};+        let bulk = Offer { cost: EMERALD, cost_n: 1, cost2: 0, cost2_n: 0, give: Block::Stone as u8, give_n: 8 };+        let mut inv = Inventory::default();+        for s in inv.slots.iter_mut() { *s = InvSlot { id: Block::Dirt as u8, count: STACK }; }+        inv.slots[0] = InvSlot { id: EMERALD, count: 4 };++        assert!(!inv.trade_offer(&bulk), "nowhere to put the stone");+        assert_eq!(inv.count_of(EMERALD), 4, "the payment must survive a refused trade");+    } }
games/voxels/src/main/rust/src/item.rs
diff --git a/games/voxels/src/main/rust/src/item.rs b/games/voxels/src/main/rust/src/item.rsindex 76ff6a117f..6f65c8dde3 100644--- a/games/voxels/src/main/rust/src/item.rs+++ b/games/voxels/src/main/rust/src/item.rs@@ -167,7 +167,8 @@ mod tests {             let crafted = RECIPES.iter().any(|r| r.4 == id);             let smelted = SMELTING.iter().any(|s| s.out == id);             let dropped = crate::entity::MobKind::ALL.iter().any(|k| k.loot().contains(&id));-            let traded = crate::inventory::TRADES.iter().any(|t| t.2 == id);+            let traded = crate::villager::ALL.iter()+                .any(|&p| crate::villager::offers(p, crate::villager::MAX_LEVEL).iter().any(|o| o.give == id));             let foraged = id == 130; // apples fall out of leaves             let looted = (0..40).any(|i| {                 crate::container::roll_loot(i * 7, 40, i * 13, i as u8 % 3, false)
games/voxels/src/main/rust/src/lib.rs
diff --git a/games/voxels/src/main/rust/src/lib.rs b/games/voxels/src/main/rust/src/lib.rsindex a36339d2e1..a8d07b9225 100644--- a/games/voxels/src/main/rust/src/lib.rs+++ b/games/voxels/src/main/rust/src/lib.rs@@ -7,6 +7,7 @@ pub mod player; pub mod raycast; pub mod input; pub mod inventory;+pub mod villager; pub mod engine; pub mod texture_atlas; pub mod vulkan;
games/voxels/src/main/rust/src/villager.rs
diff --git a/games/voxels/src/main/rust/src/villager.rs b/games/voxels/src/main/rust/src/villager.rsnew file mode 100644index 0000000000..d9b5beaadd--- /dev/null+++ b/games/voxels/src/main/rust/src/villager.rs@@ -0,0 +1,347 @@+// Villager professions and their leveled trade tables.+//+// Matcha ships 14 professions across 235 trade files, tiered into 5 levels. Two of them (shepherd,+// fletcher) sell wool and arrows, which this game doesn't model, and the wandering trader isn't a+// village resident — so 11 professions are carried over here, each with 3 levels stocked from items+// the game actually has.+//+// Levels are earned **per profession, globally**, not per villager. Mobs aren't persisted (they're+// cleared on quit and respawned), so a per-villager level would silently reset every session and the+// player could never find "their" librarian again. A shared counter in `ProgressSave` keeps the+// progression real.++use crate::item::{has_durability, max_durability};++pub const EMERALD: u8 = 156;++/// One line on a villager's trade list. `cost2` of 0 means a single-ingredient trade.+#[derive(Clone, Copy)]+pub struct Offer {+    pub cost: u8,+    pub cost_n: i32,+    pub cost2: u8,+    pub cost2_n: i32,+    pub give: u8,+    pub give_n: i32,+}++// Constructors, so the tables below read as sentences and can't transpose a cost for a give.+const fn buy(emeralds: i32, give: u8, give_n: i32) -> Offer {+    Offer { cost: EMERALD, cost_n: emeralds, cost2: 0, cost2_n: 0, give, give_n }+}+const fn sell(cost: u8, cost_n: i32, emeralds: i32) -> Offer {+    Offer { cost, cost_n, cost2: 0, cost2_n: 0, give: EMERALD, give_n: emeralds }+}+/// Emeralds plus raw material for one finished piece — the smiths' signature trade.+const fn forge(emeralds: i32, mat: u8, mat_n: i32, give: u8) -> Offer {+    Offer { cost: EMERALD, cost_n: emeralds, cost2: mat, cost2_n: mat_n, give, give_n: 1 }+}++type Level = &'static [Offer];++pub const MAX_LEVEL: usize = 3;+// Trades with one profession needed to unlock its next tier.+const LEVEL_2_AT: u32 = 4;+const LEVEL_3_AT: u32 = 10;++#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub enum Profession {+    Farmer,+    Fisherman,+    Butcher,+    Toolsmith,+    Weaponsmith,+    Armorer,+    Mason,+    Leatherworker,+    Librarian,+    Cleric,+    Cartographer,+}++// The discriminant order is the save format for `ProgressSave.trades_done` — append, never reorder.+pub const ALL: [Profession; 11] = [+    Profession::Farmer,+    Profession::Fisherman,+    Profession::Butcher,+    Profession::Toolsmith,+    Profession::Weaponsmith,+    Profession::Armorer,+    Profession::Mason,+    Profession::Leatherworker,+    Profession::Librarian,+    Profession::Cleric,+    Profession::Cartographer,+];++// Produce: the things a player can't grow, since there's no farming yet.+const FARMER: &[Level] = &[+    &[buy(1, 135, 4), buy(1, 146, 4), sell(130, 8, 1)],+    &[buy(1, 136, 3), buy(1, 131, 6), buy(1, 58, 2)],+    &[buy(2, 152, 4), buy(3, 133, 1)],+];++// Matcha's fisherman lists 49 species; the game has two fish and the reef they came from.+const FISHERMAN: &[Level] = &[+    &[buy(2, 132, 4), buy(1, 66, 3)],+    &[buy(2, 148, 4), sell(132, 8, 2)],+    &[buy(3, 67, 2), buy(2, 68, 4)],+];++// The butcher sells prepared dishes, and will cook yours if you bring the meat. The counter also+// carries the baking Matcha's butcher does — brownies and cookies have no other source.+const BUTCHER: &[Level] = &[+    &[sell(222, 8, 1), buy(2, 223, 3), buy(2, 134, 3), buy(2, 153, 4)],+    &[buy(2, 150, 3), forge(3, 223, 2, 224)],+    &[forge(4, 223, 2, 235), buy(3, 225, 2)],+];++const TOOLSMITH: &[Level] = &[+    &[sell(157, 12, 1), buy(1, 159, 8)],+    &[forge(4, 154, 2, 167), buy(5, 154, 3)],+    &[forge(8, 155, 2, 169), forge(5, 238, 2, 239)],+];++const WEAPONSMITH: &[Level] = &[+    &[sell(138, 5, 1), buy(2, 166, 1)],+    &[forge(4, 154, 2, 168), forge(6, 238, 2, 240)],+    &[forge(9, 155, 2, 170)],+];++const ARMORER: &[Level] = &[+    &[sell(154, 4, 1), buy(3, 171, 1)],+    &[buy(6, 172, 1), buy(4, 173, 1), buy(3, 174, 1)],+    &[forge(7, 155, 2, 175), forge(10, 155, 3, 176)],+];++// Matcha's mason walks the player up a ladder of stone variants; the game's stonecutter turns each+// one into slabs and stairs, so selling the stonecutter itself is the level-3 prize.+const MASON: &[Level] = &[+    &[buy(1, 1, 8), buy(1, 16, 6), sell(8, 8, 1)],+    &[buy(1, 57, 6), buy(1, 38, 4), buy(1, 75, 4)],+    &[buy(2, 74, 4), buy(2, 53, 4), buy(4, 118, 1)],+];++const LEATHERWORKER: &[Level] = &[+    &[sell(137, 6, 2), buy(1, 4, 6)],+    &[buy(1, 26, 6), buy(1, 29, 6)],+    &[buy(1, 47, 4), buy(1, 51, 4), buy(2, 137, 3)],+];++// Matcha's librarian sells tomes; here the tomes are Blessings, priced steeply so crafting them stays+// the main route.+const LIBRARIAN: &[Level] = &[+    &[buy(3, 33, 1), buy(1, 7, 4)],+    &[buy(5, 191, 1), buy(9, 218, 1)],+    &[buy(10, 210, 1), buy(10, 203, 1)],+];++// Matcha's cleric deals in splash potions. This game has no potions, so the cleric deals in the+// things that keep you alive: Estus, golden apples, and the one merchant who will sell you a heart.+const CLERIC: &[Level] = &[+    &[buy(4, 128, 1), sell(158, 6, 1)],+    &[buy(3, 133, 2), buy(9, 160, 1)],+    &[forge(12, 155, 1, 129), buy(10, 205, 1)],+];++// Matcha's cartographer sells structure maps and a brush; without maps or archaeology this is the+// expedition outfitter instead — fire, throwables, and the obsidian for a portal.+const CARTOGRAPHER: &[Level] = &[+    &[buy(2, 186, 1), buy(2, 190, 6)],+    &[buy(6, 78, 2), forge(3, 138, 2, 189)],+    &[buy(10, 78, 4), buy(6, 191, 2)],+];++impl Profession {+    pub fn index(self) -> usize {+        ALL.iter().position(|&p| p == self).unwrap_or(0)+    }++    pub fn from_index(i: usize) -> Self {+        ALL.get(i).copied().unwrap_or(Profession::Farmer)+    }++    /// A villager's trade is fixed for its lifetime, drawn from its spawn seed.+    pub fn from_seed(seed: u32) -> Self {+        Self::from_index((seed >> 8) as usize % ALL.len())+    }++    pub fn name(self) -> &'static str {+        match self {+            Profession::Farmer => "Farmer",+            Profession::Fisherman => "Fisherman",+            Profession::Butcher => "Butcher",+            Profession::Toolsmith => "Toolsmith",+            Profession::Weaponsmith => "Weaponsmith",+            Profession::Armorer => "Armorer",+            Profession::Mason => "Mason",+            Profession::Leatherworker => "Leatherworker",+            Profession::Librarian => "Librarian",+            Profession::Cleric => "Cleric",+            Profession::Cartographer => "Cartographer",+        }+    }++    /// Robe colour, so a village reads at a glance instead of every resident looking identical.+    pub fn tint(self) -> [f32; 3] {+        match self {+            Profession::Farmer => [0.72, 0.85, 0.42],+            Profession::Fisherman => [0.42, 0.68, 0.85],+            Profession::Butcher => [0.90, 0.52, 0.48],+            Profession::Toolsmith => [0.80, 0.66, 0.38],+            Profession::Weaponsmith => [0.62, 0.62, 0.70],+            Profession::Armorer => [0.48, 0.52, 0.60],+            Profession::Mason => [0.78, 0.74, 0.66],+            Profession::Leatherworker => [0.70, 0.50, 0.32],+            Profession::Librarian => [0.86, 0.82, 0.60],+            Profession::Cleric => [0.72, 0.52, 0.86],+            Profession::Cartographer => [0.52, 0.80, 0.72],+        }+    }++    fn levels(self) -> &'static [Level] {+        match self {+            Profession::Farmer => FARMER,+            Profession::Fisherman => FISHERMAN,+            Profession::Butcher => BUTCHER,+            Profession::Toolsmith => TOOLSMITH,+            Profession::Weaponsmith => WEAPONSMITH,+            Profession::Armorer => ARMORER,+            Profession::Mason => MASON,+            Profession::Leatherworker => LEATHERWORKER,+            Profession::Librarian => LIBRARIAN,+            Profession::Cleric => CLERIC,+            Profession::Cartographer => CARTOGRAPHER,+        }+    }+}++/// How far a profession has been levelled by `done` completed trades.+pub fn level_for(done: u32) -> usize {+    if done >= LEVEL_3_AT { 3 } else if done >= LEVEL_2_AT { 2 } else { 1 }+}++/// The trade count that unlocks the tier after `level`, or None once it's maxed.+pub fn next_level_at(level: usize) -> Option<u32> {+    match level {+        1 => Some(LEVEL_2_AT),+        2 => Some(LEVEL_3_AT),+        _ => None,+    }+}++/// Everything a villager of this profession will offer at this level: earlier tiers stay on the list,+/// so unlocking a level only ever appends and never invalidates an index the UI is already holding.+pub fn offers(prof: Profession, level: usize) -> Vec<Offer> {+    prof.levels().iter().take(level.clamp(1, MAX_LEVEL)).flat_map(|l| l.iter().copied()).collect()+}++/// The level a given offer index belongs to, for grouping in the UI.+pub fn level_of_offer(prof: Profession, idx: usize) -> usize {+    let mut seen = 0;+    for (i, l) in prof.levels().iter().enumerate() {+        seen += l.len();+        if idx < seen { return i + 1; }+    }+    MAX_LEVEL+}++/// Tools and armour always arrive at full durability; stacks arrive as a count.+pub fn give_count(offer: &Offer) -> i32 {+    if has_durability(offer.give) { max_durability(offer.give) } else { offer.give_n }+}++#[cfg(test)]+mod tests {+    use super::*;+    use crate::world::block::MAX_BLOCK_ID;++    fn is_real_id(id: u8) -> bool {+        id != 0 && (id <= MAX_BLOCK_ID || crate::item::is_item(id))+    }++    // A typo in a trade table is invisible until a player taps it and receives Air, so every id in+    // every tier of every profession gets checked.+    #[test]+    fn every_trade_moves_real_goods() {+        for &p in ALL.iter() {+            let all = offers(p, MAX_LEVEL);+            assert!(!all.is_empty(), "{} has nothing to sell", p.name());+            for (i, o) in all.iter().enumerate() {+                let where_ = format!("{} offer {i}", p.name());+                assert!(is_real_id(o.cost), "{where_}: cost {} is not an id", o.cost);+                assert!(is_real_id(o.give), "{where_}: gives {} which is not an id", o.give);+                assert!(o.cost2 == 0 || is_real_id(o.cost2), "{where_}: second cost {} is not an id", o.cost2);+                assert!(o.cost_n > 0 && o.give_n > 0, "{where_}: a trade must cost and give something");+                assert!(o.cost2 == 0 || o.cost2_n > 0, "{where_}: a second cost needs a count");+                assert_ne!(o.cost, o.give, "{where_}: trades {} for itself", o.give);+                assert_ne!(o.cost2, o.give, "{where_}: trades {} for itself", o.give);+            }+        }+    }++    // The emerald economy needs a source as well as a sink, or the whole village is unreachable to a+    // player who has never found an emerald ore.+    #[test]+    fn emeralds_can_be_earned_and_spent() {+        let mut sellers = 0;+        for &p in ALL.iter() {+            let all = offers(p, MAX_LEVEL);+            assert!(all.iter().any(|o| o.cost == EMERALD), "{} gives nothing for emeralds", p.name());+            if all.iter().any(|o| o.give == EMERALD) { sellers += 1; }+            // Level 1 has to be usable on its own, since that's where every villager starts.+            assert!(!offers(p, 1).is_empty(), "{} is mute until it levels up", p.name());+        }+        assert!(sellers >= 5, "only {sellers} professions buy goods for emeralds");+    }++    // Levelling appends; it must never renumber an offer the trade screen is already showing.+    #[test]+    fn levelling_only_appends_offers() {+        for &p in ALL.iter() {+            let (l1, l2, l3) = (offers(p, 1), offers(p, 2), offers(p, 3));+            assert!(l1.len() <= l2.len() && l2.len() <= l3.len(), "{} shrinks as it levels", p.name());+            for (i, o) in l1.iter().enumerate() {+                assert_eq!(o.give, l3[i].give, "{} offer {i} moved when it levelled", p.name());+            }+            for (i, o) in l2.iter().enumerate() {+                assert_eq!(o.give, l3[i].give, "{} offer {i} moved when it levelled", p.name());+            }+            assert_eq!(level_of_offer(p, 0), 1);+            assert_eq!(level_of_offer(p, l1.len()), 2, "{} mislabels its first level-2 offer", p.name());+        }+    }++    #[test]+    fn levels_unlock_in_order() {+        assert_eq!(level_for(0), 1);+        assert_eq!(level_for(LEVEL_2_AT - 1), 1);+        assert_eq!(level_for(LEVEL_2_AT), 2);+        assert_eq!(level_for(LEVEL_3_AT), 3);+        assert_eq!(level_for(u32::MAX), MAX_LEVEL, "the level can't run past the table");+    }++    // Professions are drawn from the spawn seed, so a village has to end up mixed rather than eleven+    // farmers.+    #[test]+    fn spawn_seeds_spread_across_professions() {+        let mut seen = [0usize; ALL.len()];+        let mut s = 0x9E37_79B9u32;+        for _ in 0..4000 {+            s ^= s << 13; s ^= s >> 17; s ^= s << 5;+            seen[Profession::from_seed(s).index()] += 1;+        }+        for (i, n) in seen.iter().enumerate() {+            assert!(*n > 100, "{} almost never spawns ({n} of 4000)", Profession::from_index(i).name());+        }+    }++    #[test]+    fn professions_round_trip_through_their_index() {+        for (i, &p) in ALL.iter().enumerate() {+            assert_eq!(p.index(), i);+            assert_eq!(Profession::from_index(i), p);+        }+        assert_eq!(Profession::from_index(999), Profession::Farmer, "a corrupt save falls back, not panics");+    }+}
games/voxels/src/main/rust/src/world/save.rs
diff --git a/games/voxels/src/main/rust/src/world/save.rs b/games/voxels/src/main/rust/src/world/save.rsindex 2ec1a10d07..b4399cd7f8 100644--- a/games/voxels/src/main/rust/src/world/save.rs+++ b/games/voxels/src/main/rust/src/world/save.rs@@ -101,6 +101,9 @@ pub struct ProgressSave {     #[serde(default)] pub best_beacon: i32,     #[serde(default = "default_deepest")] pub deepest_y: i32,     #[serde(default)] pub blessings: crate::blessing::Attunement,+    // Completed trades per profession, indexed by `villager::ALL` order. Villager mobs aren't saved,+    // so levels are tracked against the profession rather than the individual.+    #[serde(default)] pub trades_done: Vec<u32>, } fn default_max_health() -> f32 { 20.0 } fn default_deepest() -> i32 { 128 }@@ -112,6 +115,7 @@ impl Default for ProgressSave {             end_dragon_dead: false, nether_wither_dead: false, world_secs: 0.0,             best_beacon: 0, deepest_y: default_deepest(),             blessings: crate::blessing::Attunement::default(),+            trades_done: Vec::new(),         }     } }@@ -262,6 +266,7 @@ mod tests {         ps.progress.respawn = Some([8.0, 70.0, 9.0]);         ps.progress.nether_wither_dead = true;         ps.progress.world_secs = 372.5;+        ps.progress.trades_done = vec![0, 7, 0, 0, 0, 0, 14, 0, 0, 0, 0];         let back: PlayerSave = serde_json::from_str(&serde_json::to_string(&ps).unwrap()).unwrap();         assert_eq!(back.progress.max_health, 34.0);         assert_eq!(back.progress.dim, 1);@@ -270,5 +275,7 @@ mod tests {         assert_eq!(back.progress.respawn, Some([8.0, 70.0, 9.0]));         assert!(back.progress.nether_wither_dead);         assert_eq!(back.progress.world_secs, 372.5);+        assert_eq!(back.progress.trades_done[1], 7, "villager levels have to survive a quit");+        assert_eq!(back.progress.trades_done[6], 14);     } }