Files
bworld/mods/bworld/scripts/smithing.ts
T
2026-11-14 12:18:41 -03:00

70 lines
2.6 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// smithing recipes: the smithing table upgrades a tool with some of a material and maybe some of one more item. the
// type is registered by the shared phase, so the server's menu and anything on a client find them the same way
import type { ItemStack, RecipeReader, SharedContext } from "cubi/shared";
export const SMITHING = "bworld:smithing";
// the items any of which fit, from an item, a #tag or a list of them, and how many it takes
export interface SmithingIngredient {
items: string[];
count: number;
}
export interface SmithingRecipe {
tool: string[];
material: SmithingIngredient;
addition?: SmithingIngredient;
result: string;
}
// what's in the smithing table's input slots
export interface SmithingInput {
tool: ItemStack;
material: ItemStack;
addition?: ItemStack;
}
// { id, count }, where id is a choice like a shaped key's
function read_ingredient(read: RecipeReader, value: unknown, name: string): SmithingIngredient {
const json = value as { id?: unknown; count?: unknown } | undefined;
return { items: read.ingredient(json?.id, `${name} id`), count: read.positive_int(json?.count, `${name} count`) };
}
// whether stack is enough of ingredient. no ingredient fits only an empty slot
function fits(ingredient: SmithingIngredient | undefined, stack: ItemStack | undefined): boolean {
if (!ingredient) return !stack;
return !!stack && ingredient.items.includes(stack.id) && stack.count >= ingredient.count;
}
export function register_smithing(ctx: SharedContext) {
// two recipes for the same inputs would leave one that can never be made
const seen = new Set<string>();
ctx.recipes.register_type<SmithingRecipe, SmithingInput>(SMITHING, {
parse(json, read) {
const recipe: SmithingRecipe = {
tool: read.ingredient(json.tool, "tool"),
material: read_ingredient(read, json.material, "material"),
result: read.item(json.result, "result"),
};
if (json.addition !== undefined) recipe.addition = read_ingredient(read, json.addition, "addition");
for (const tool of recipe.tool) {
for (const material of recipe.material.items) {
for (const addition of recipe.addition?.items ?? [undefined]) {
const inputs = `${tool} ${material} ${addition}`;
if (seen.has(inputs)) throw new Error(`there's already one for ${tool} with ${material}`);
seen.add(inputs);
}
}
}
return recipe;
},
// with enough of the material and the addition
matches: (recipe, input) =>
recipe.tool.includes(input.tool.id) && fits(recipe.material, input.material) &&
fits(recipe.addition, input.addition),
});
}