Recipe viewer for crabpots

This commit is contained in:
2026-10-12 02:39:25 -03:00
parent 726a52b91a
commit 2ebcf55ad3
9 changed files with 201 additions and 13 deletions
+12
View File
@@ -18,6 +18,7 @@ import { clear_hooks, expose_engine, loading_mod } from "$/common/hooks.ts";
import { common_engine } from "$/common/engine_modules.ts";
import { client_engine } from "./engine_modules.ts";
import { biome_season } from "$/common/worldgen/biomes.ts";
import type { LootTableJson } from "$/common/loot.ts";
// each loaded mod's credits file, for the credits screen
export const mod_credits: { name: string; version: string; text: string }[] = [];
@@ -309,6 +310,17 @@ function client_context(listing: ModListing): ClientContext {
EverythingRegistry.get<ItemRegistry>("items", id)?.components ?? {},
)),
},
blocks: {
exists: (id) => EverythingRegistry.get("blocks", id) !== undefined,
components(id) {
const block = EverythingRegistry.get<BlockRegistry>("blocks", id);
if (!block) throw new Error(`[${mod}] unknown block ${id}`);
return structuredClone(block.components ?? {});
},
},
loot: {
table: (id) => structuredClone(EverythingRegistry.get<LootTableJson>("loot_tables", id)),
},
recipes: {
list: (type) =>
structuredClone(type ? recipe_book.all.filter((recipe) => recipe.type === type) : recipe_book.all),
+14
View File
@@ -1,5 +1,6 @@
// what client scripts get, see docs/modding/gui/index.md
import type { Id, ItemStack, KeyCode, ModInfo, Position, Season, TagApi } from "./shared.ts";
import type { LootTableJson } from "../loot.ts";
export type { Id, ItemStack, KeyCode, ModInfo, Position, Season, TagApi, TagRegistry } from "./shared.ts";
@@ -42,6 +43,19 @@ export interface ClientContext {
// what a component means, like when a fish can be caught
components(id: Id): Record<Id, unknown>;
};
// every block any mod registered
blocks: {
exists(id: Id): boolean;
// the components its json lists and their params, a copy, like the server's ctx.blocks.components. for showing
// what a component does, like what a crab pot catches
components(id: Id): Record<Id, unknown>;
};
// the mods' loot table files (see docs/modding/resources/loot_tables.md), to show what they give. tables server
// scripts make with ctx.loot.register_table aren't here
loot: {
// the table's json, a copy, or undefined when no mod has a file for it
table(id: Id): LootTableJson | undefined;
};
// every recipe as its json (see docs/modding/resources/recipes.md), including mods' own types, in load order. copies
recipes: {
// deno-lint-ignore no-explicit-any
+3
View File
@@ -151,6 +151,9 @@ ctx.items.exists(id);
ctx.items.name(id); // "Cooked Rice"
ctx.items.mod(id); // the name of the mod that added it
ctx.items.components(id); // its components and their params, like the server's, to show what they mean
ctx.blocks.exists(id);
ctx.blocks.components(id); // the same for a block, like what a crab pot catches with each bait
ctx.loot.table(id); // a loot table file's JSON, or undefined. tables server scripts make aren't here
ctx.recipes.list(type?); // every recipe as its JSON, including mods' own types
ctx.options.key_inventory; // the key the player has bound, like Minecraft's Options key mappings
```
+12 -1
View File
@@ -32,7 +32,18 @@
"waterloggable": "bworld:water",
"interactive": true,
"components": {
"bworld:crabpot": {}
"bworld:crabpot": {
"baits": {
"bworld:worms": {
"freshwater": "bworld:gameplay/crabpot_worms_freshwater",
"saltwater": "bworld:gameplay/crabpot_worms_saltwater"
},
"bworld:grubs": {
"freshwater": "bworld:gameplay/crabpot_grubs_freshwater",
"saltwater": "bworld:gameplay/crabpot_grubs_saltwater"
}
}
}
}
}
}
+10 -8
View File
@@ -274,8 +274,11 @@ const RESULT = 3;
// bait
const CRABPOT_BAIT = 0;
const CRABPOT_OUTPUT = 9;
// each bait's loot tables, bworld:gameplay/crabpot_<name>_saltwater and _freshwater
const CRABPOT_BAITS: Record<string, string> = { "bworld:worms": "worms", "bworld:grubs": "grubs" };
// the bworld:crabpot component's params: each bait's loot tables, read by the recipe viewer too
interface CrabpotParams {
baits: Record<string, { freshwater: string; saltwater: string }>;
}
function register_crabpot(ctx: ServerContext) {
const menu_type = ctx.menus.register<BlockRef>("bworld:crabpot", (menu, block) => {
@@ -289,7 +292,7 @@ function register_crabpot(ctx: ServerContext) {
menu.still_valid_near(block);
});
ctx.components.register_block("bworld:crabpot", {
ctx.components.register_block<CrabpotParams>("bworld:crabpot", {
on_interact(block, _params, player) {
menu_type.open(player, block);
return true;
@@ -297,7 +300,7 @@ function register_crabpot(ctx: ServerContext) {
on_break(block) {
drop_contents(ctx, block);
},
on_new_day(block) {
on_new_day(block, params) {
const { x, y, z } = block;
if (ctx.world.get_state(x, y, z, "waterlogged") !== 1) {
return;
@@ -305,13 +308,12 @@ function register_crabpot(ctx: ServerContext) {
// one that's never been opened has nothing in it
const container = block.data?.container && ctx.containers.get(block.data.container);
const bait = container && container.get(CRABPOT_BAIT);
const bait_name = bait && CRABPOT_BAITS[bait.id];
if (!bait || !bait_name) {
const tables = bait && params.baits[bait.id];
if (!bait || !tables) {
return;
}
const water = ctx.tags.has("biomes", "bworld:is_ocean", block.biome) ? "saltwater" : "freshwater";
const table = `bworld:gameplay/crabpot_${bait_name}_${water}`;
const table = ctx.tags.has("biomes", "bworld:is_ocean", block.biome) ? tables.saltwater : tables.freshwater;
const position = { x: x + 0.5, y: y + 0.5, z: z + 0.5 };
for (const item of ctx.loot.roll(table, { position })) {
// onto a stack of it with room, or into an empty output slot
+3 -1
View File
@@ -13,7 +13,9 @@ them, Backspace goes back, and Escape or the inventory key (E) returns to the in
It reads every mod's recipes with `ctx.recipes.list()`. Fish, the items with the base game's `bworld:fish` component,
get a Fishing category too: clicking one shows its seasons, biomes, hours and the liquid it's caught in, read with
`ctx.items.components`, and the fishing rod's uses are every fish.
`ctx.items.components`, and the fishing rod's uses are every fish. The crab pot gets one too: a recipe for each bait in
its `bworld:crabpot` component and each kind of water, showing everything that water's loot table can catch and how
likely each is, read with `ctx.blocks.components` and `ctx.loot.table`.
- `scripts/categories.ts` has a category for each recipe type, like JEI's `IRecipeCategory`: its title, size, where it's
made (`MOD_CATALYSTS` for mods' types) and where its items go. Types without one are drawn from their JSON: the items
+83
View File
@@ -120,6 +120,28 @@ function base_categories(tags: TagApi): RecipeCategory[] {
lines.forEach((line, i) => layout.text(line, 24, 1 + i * 13));
},
},
{
// what a crab pot catches with a bait in one kind of water, see crabpot_recipes
type: CRABPOT,
title: "Crab Pot",
width: 168,
height: 54,
catalysts: [CRABPOT_BLOCK],
draw(recipe, layout) {
const { water, catches } = recipe.crabpot as { water: string; catches: Catch[] };
layout.slot({ ids: [recipe.bait], count: 1 }, 0, 0, ["Bait"]);
layout.text(title_case(water), 0, 23);
layout.texture("bworld:arrow_full", 34, 1, ARROW, ARROW);
catches.slice(0, CATCH_COLUMNS * 3).forEach(({ id, chance }, i) =>
layout.slot(
{ ids: [id], count: 1 },
60 + (i % CATCH_COLUMNS) * SLOT,
Math.floor(i / CATCH_COLUMNS) * SLOT,
[`${percent(chance)} chance`],
)
);
},
},
];
}
@@ -141,6 +163,66 @@ export function fishing_recipes(ctx: ClientContext): Recipe[] {
});
}
// the base game's crab pot, from its bworld:crabpot component's params: a recipe of its own type for each bait and
// kind of water, that makes everything that water's loot table can give. the bait is an input like any recipe's, the
// catches and their chances are under "crabpot", which reading a recipe's inputs skips
const CRABPOT = "bworld:crabpot";
const CRABPOT_BLOCK = "bworld:crabpot";
const CATCH_COLUMNS = 6;
interface CrabpotParams {
baits?: Record<string, { freshwater: string; saltwater: string }>;
}
// one item a loot table can give, and how likely it is to be the one
interface Catch {
id: string;
chance: number;
}
export function crabpot_recipes(ctx: ClientContext): Recipe[] {
if (!ctx.blocks.exists(CRABPOT_BLOCK)) return [];
const params = ctx.blocks.components(CRABPOT_BLOCK)[CRABPOT_BLOCK] as CrabpotParams | undefined;
return Object.entries(params?.baits ?? {}).flatMap(([bait, tables]) =>
(["freshwater", "saltwater"] as const).map((water) => {
const caught = catches(ctx, tables[water]);
return { type: CRABPOT, bait, result: caught.map((c) => c.id), crabpot: { water, catches: caught } };
})
);
}
// what one roll of a table's pools gives, by its entries' weights, most likely first. nested tables are worked
// through, a tag's items share its chance, and conditions and functions aren't shown
function catches(ctx: ClientContext, id: string, seen = new Set<string>()): Catch[] {
const table = ctx.loot.table(id);
if (!table || seen.has(id)) return [];
seen.add(id);
const chances = new Map<string, number>();
const add = (item: string, chance: number) => chances.set(item, (chances.get(item) ?? 0) + chance);
for (const pool of table.pools) {
const total = pool.entries.reduce((sum, entry) => sum + (entry.weight ?? 1), 0);
for (const entry of pool.entries) {
const chance = (entry.weight ?? 1) / total;
const type = entry.type ?? "item";
if (type === "item" && entry.item) {
add(entry.item, chance);
} else if (type === "tag" && entry.tag) {
const items = ctx.tags.expand(entry.tag);
for (const item of items) add(item, chance / items.length);
} else if (type === "loot_table" && entry.table) {
for (const inner of catches(ctx, entry.table, seen)) add(inner.id, chance * inner.chance);
}
}
}
return [...chances].map(([id, chance]) => ({ id, chance })).sort((a, b) => b.chance - a.chance);
}
// 0.0625 is "6.3%", 0.5 is "50%"
function percent(chance: number): string {
const value = chance * 100;
return `${Number.isInteger(value) ? value : value.toFixed(1)}%`;
}
// "autumn" is "Autumn", "dark_oak" is "Dark Oak"
function title_case(name: string): string {
return name.split("_").map((word) => word[0].toUpperCase() + word.slice(1)).join(" ");
@@ -201,6 +283,7 @@ export function category_name(type: string): string {
fuel: "Fuel",
smithing: "Smithing",
[FISHING]: "Fishing",
[CRABPOT]: "Crab Pot",
};
if (base[type]) return base[type];
const name = type.split(":")[1] ?? type;
+9 -2
View File
@@ -3,7 +3,14 @@
// many recipes as fit, one under the other. the item list stays on the right. escape or the inventory key go back to
// the inventory, and backspace to what was shown before
import type { ClientContext, Graphics, Screen } from "bworld/client";
import { fishing_recipes, make_categories, type RecipeCategory, type RecipeLayout, SLOT } from "./categories.ts";
import {
crabpot_recipes,
fishing_recipes,
make_categories,
type RecipeCategory,
type RecipeLayout,
SLOT,
} from "./categories.ts";
import { BUTTON, item_cell, ItemList, LABEL_COLOR, type Mode, SLOT_COLOR } from "./item_list.ts";
import { type Ingredient, inputs, outputs, type Recipe } from "./recipes.ts";
@@ -32,7 +39,7 @@ export class RecipeIndex {
get categories(): RecipeCategory[] {
if (!this.#categories) {
this.#recipes = [...this.ctx.recipes.list(), ...fishing_recipes(this.ctx)];
this.#recipes = [...this.ctx.recipes.list(), ...fishing_recipes(this.ctx), ...crabpot_recipes(this.ctx)];
this.#categories = make_categories(this.ctx, this.#recipes);
}
return this.#categories;
+55 -1
View File
@@ -4,7 +4,7 @@ import { category_name } from "../mods/recipe_viewer/scripts/categories.ts";
import { inputs as recipe_inputs, outputs } from "../mods/recipe_viewer/scripts/recipes.ts";
import { RecipeIndex } from "../mods/recipe_viewer/scripts/recipes_screen.ts";
import { tag_api } from "$/common/tags.ts";
import { EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts";
import { type BlockRegistry, EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts";
import type { ClientContext } from "bworld/client";
import { test_game } from "./helpers.ts";
@@ -21,6 +21,15 @@ function client_items() {
};
}
// and of ctx.blocks and ctx.loot
function client_blocks() {
return {
exists: (id: string) => EverythingRegistry.get("blocks", id) !== undefined,
components: (id: string) => EverythingRegistry.get<BlockRegistry>("blocks", id)?.components ?? {},
};
}
const client_loot = () => ({ table: (id: string) => EverythingRegistry.get("loot_tables", id) });
Deno.test("the recipe viewer finds what makes and uses an item, in any recipe type", async () => {
const { game } = await test_game("mods");
const all = game.recipes.all;
@@ -62,6 +71,8 @@ Deno.test("recipes are found by category in jei's order, and a catalyst's uses a
recipes: { list: () => game.recipes.all },
tags: tag_api(),
items: client_items(),
blocks: client_blocks(),
loot: client_loot(),
} as unknown as ClientContext;
const index = new RecipeIndex(ctx);
@@ -85,6 +96,8 @@ Deno.test("clicking a fish shows when and where it bites, and the fishing rod's
recipes: { list: () => [] },
tags: tag_api(),
items: client_items(),
blocks: client_blocks(),
loot: client_loot(),
} as unknown as ClientContext;
const index = new RecipeIndex(ctx);
const [fishing] = index.find("bworld:red_mullet", "recipes");
@@ -110,3 +123,44 @@ Deno.test("clicking a fish shows when and where it bites, and the fishing rod's
// a fish isn't a use of the water it lives in
assertEquals(index.find("bworld:water", "uses"), []);
});
Deno.test("a crab pot's recipes are what each bait catches in fresh and salt water, with their chances", async () => {
await test_game("mods");
const ctx = {
recipes: { list: () => [] },
tags: tag_api(),
items: client_items(),
blocks: client_blocks(),
loot: client_loot(),
} as unknown as ClientContext;
const index = new RecipeIndex(ctx);
// grubs are bait for both waters, under the crab pot's tab
const [grubs] = index.find("bworld:grubs", "uses");
assertEquals(grubs.category.title, "Crab Pot");
assertEquals(grubs.category.catalysts, ["bworld:crabpot"]);
assertEquals(grubs.recipes.map((recipe) => recipe.crabpot.water), ["freshwater", "saltwater"]);
// a seashroom comes from grubs in salt water, one in 16
const [seashroom] = index.find("bworld:red_seashroom", "recipes");
assertEquals(seashroom.recipes.length, 1);
const recipe = seashroom.recipes[0];
assertEquals(recipe.bait, "bworld:grubs");
const slots: [string, string[] | undefined][] = [];
const lines: string[] = [];
seashroom.category.draw(recipe, {
slot: (ingredient, _x, _y, tooltip) => slots.push([ingredient!.ids[0], tooltip]),
texture: () => {},
text: (text) => lines.push(text),
});
assertEquals(lines, ["Saltwater"]);
assertEquals(slots[0], ["bworld:grubs", ["Bait"]]);
assertEquals(slots.length, 1 + 16);
assertEquals(slots.find(([id]) => id === "bworld:red_seashroom")?.[1], ["6.3% chance"]);
// worms in fresh water catch a third each of three things
const worms = index.find("bworld:worms", "uses").find((found) => found.category.title === "Crab Pot")!;
const freshwater = worms.recipes.find((r) => r.crabpot.water === "freshwater");
assertEquals(freshwater.result.toSorted(), ["bworld:chorus_snail", "bworld:crayfish", "bworld:leech"]);
assertEquals(freshwater.crabpot.catches.map((c: { chance: number }) => c.chance), [1 / 3, 1 / 3, 1 / 3]);
});