331 lines
12 KiB
TypeScript
331 lines
12 KiB
TypeScript
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
// loot tables: rolling them, checking them, and the game using them for blocks, mobs and scripts
|
|
import { assert, assertEquals, assertThrows } from "@std/assert";
|
|
import { EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts";
|
|
import {
|
|
type BaseLootContext,
|
|
type LootEnvironment,
|
|
type LootTableJson,
|
|
number,
|
|
roll_loot,
|
|
validate_loot_table,
|
|
} from "$/common/loot.ts";
|
|
import { Tags } from "$/common/tags.ts";
|
|
import { load_and_check } from "$/tools/check_mods.ts";
|
|
import { create_entity } from "$/server/game/entity/entity_types.ts";
|
|
import type { LivingEntity } from "$/server/game/entity/living_entity.ts";
|
|
import { copy_dir, test_game } from "./helpers.ts";
|
|
|
|
// the tables, registered fresh, with a tool and a tag to match
|
|
function tables(...list: LootTableJson[]) {
|
|
EverythingRegistry.clear();
|
|
for (const table of list) EverythingRegistry.register("loot_tables", table.id, table);
|
|
EverythingRegistry.register<ItemRegistry>("items", "t:pick", {
|
|
texture_id: "t:pick",
|
|
tool: { type: "pickaxe", tier: 2, speed: 1, durability: 1 },
|
|
});
|
|
Tags.load(new Map([["items", new Map([["t:gems", ["t:ruby", "t:opal"]]])]]));
|
|
}
|
|
|
|
// random numbers from a list, round and round
|
|
const randoms = (...values: number[]): LootEnvironment<BaseLootContext> => {
|
|
let i = 0;
|
|
return { random: () => values[i++ % values.length] };
|
|
};
|
|
|
|
const roll = (id: string, context: BaseLootContext = {}, env = randoms(0)) => roll_loot(id, context, env);
|
|
|
|
Deno.test("a pool picks entries by weight, as many times as it rolls", () => {
|
|
tables({
|
|
id: "t:fish",
|
|
pools: [{ rolls: 2, entries: [{ item: "t:cod", weight: 3 }, { item: "t:salmon", weight: 1 }] }],
|
|
});
|
|
// 0.5 of 4 is in cod's 3, 0.9 of 4 in salmon's 1
|
|
assertEquals(roll("t:fish", {}, randoms(0.5, 0.9)), [{ id: "t:cod", count: 1 }, { id: "t:salmon", count: 1 }]);
|
|
});
|
|
|
|
Deno.test("counts come from a number, a range or tries at a chance", () => {
|
|
const env = { random: () => 0.5 };
|
|
assertEquals(number(3, env), 3);
|
|
assertEquals(number({ min: 1, max: 4 }, env), 3);
|
|
assertEquals(number({ n: 3, p: 0.6 }, env), 3);
|
|
assertEquals(number({ n: 3, p: 0.4 }, env), 0);
|
|
tables({
|
|
id: "t:seeds",
|
|
pools: [{
|
|
entries: [{
|
|
item: "t:seed",
|
|
count: 1,
|
|
functions: [{ function: "set_count", count: { n: 3, p: 0.6 }, add: true }, {
|
|
function: "limit_count",
|
|
max: 3,
|
|
}],
|
|
}],
|
|
}],
|
|
});
|
|
assertEquals(roll("t:seeds", {}, randoms(0.5)), [{ id: "t:seed", count: 3 }]);
|
|
});
|
|
|
|
Deno.test("conditions on tables, pools and entries: tools, block states, chance, who killed it", () => {
|
|
tables({
|
|
id: "t:ore",
|
|
pools: [
|
|
{
|
|
conditions: [{ condition: "match_tool", tool: "pickaxe", min_tier: 2 }],
|
|
entries: [{ item: "t:ruby" }],
|
|
},
|
|
{
|
|
entries: [
|
|
{ item: "t:ripe", conditions: [{ condition: "block_state", states: { age: { min: 3 } } }] },
|
|
{
|
|
item: "t:unripe",
|
|
conditions: [{
|
|
condition: "inverted",
|
|
term: { condition: "block_state", states: { age: { min: 3 } } },
|
|
}],
|
|
},
|
|
],
|
|
},
|
|
{
|
|
conditions: [{
|
|
condition: "any_of",
|
|
terms: [{ condition: "killed_by_player" }, { condition: "random_chance", chance: 0.25 }],
|
|
}],
|
|
entries: [{ item: "t:bonus" }],
|
|
},
|
|
],
|
|
});
|
|
const ids = (context: BaseLootContext, random = 0.5) =>
|
|
roll("t:ore", context, randoms(random)).map((item) => item.id);
|
|
assertEquals(ids({ tool: { id: "t:pick" }, block: { id: "t:ore", states: { age: 3 } } }), ["t:ruby", "t:ripe"]);
|
|
assertEquals(ids({ block: { id: "t:ore", states: { age: 1 } } }), ["t:unripe"]);
|
|
assertEquals(ids({ killed_by_player: true }), ["t:unripe", "t:bonus"]);
|
|
assertEquals(ids({}, 0.1), ["t:unripe", "t:bonus"]);
|
|
});
|
|
|
|
Deno.test("entries can be a tag's item, another table, or nothing, and set data", () => {
|
|
tables(
|
|
{
|
|
id: "t:chest",
|
|
pools: [{
|
|
rolls: 3,
|
|
entries: [
|
|
{ type: "tag", tag: "#t:gems" },
|
|
{ type: "loot_table", table: "t:inner" },
|
|
{ type: "empty" },
|
|
],
|
|
}],
|
|
},
|
|
{
|
|
id: "t:inner",
|
|
pools: [{ entries: [{ item: "t:map", functions: [{ function: "set_data", data: { to: "treasure" } }] }] }],
|
|
},
|
|
{ id: "t:loop", pools: [{ entries: [{ type: "loot_table", table: "t:loop" }] }] },
|
|
);
|
|
// each roll: 0.1 is the tag (then 0 its first item), 0.5 the table (then 0 its only entry), 0.9 nothing
|
|
assertEquals(roll("t:chest", {}, randoms(0.1, 0, 0.5, 0, 0.9)), [
|
|
{ id: "t:ruby", count: 1 },
|
|
{ id: "t:map", count: 1, data: { to: "treasure" } },
|
|
]);
|
|
assertThrows(() => roll("t:loop"), Error, "in itself");
|
|
assertThrows(() => roll("t:nope"), Error, "doesn't exist");
|
|
});
|
|
|
|
Deno.test("mods' conditions and functions are looked up by id", () => {
|
|
tables({
|
|
id: "t:magic",
|
|
pools: [{
|
|
conditions: [{ condition: "m:night" }],
|
|
entries: [{ item: "t:star", functions: [{ function: "m:double" }] }],
|
|
}],
|
|
});
|
|
const env = (night: boolean): LootEnvironment<BaseLootContext> => ({
|
|
random: () => 0,
|
|
conditions: new Map([["m:night", () => night]]),
|
|
functions: new Map([["m:double", (item) => ({ ...item, count: item.count * 2 })]]),
|
|
});
|
|
assertEquals(roll_loot("t:magic", {}, env(true)), [{ id: "t:star", count: 2 }]);
|
|
assertEquals(roll_loot("t:magic", {}, env(false)), []);
|
|
assertThrows(() => roll("t:magic"), Error, "m:night isn't registered");
|
|
});
|
|
|
|
Deno.test("a table's json says what's wrong with it", () => {
|
|
const table = { id: "t:x", pools: [{ entries: [{ item: "t:a" }] }] };
|
|
assertEquals(validate_loot_table(table), []);
|
|
const problems = (json: unknown) => validate_loot_table(json).join("\n");
|
|
assert(problems({ ...table, pools: [{ entries: [] }] }).includes("entries can't be empty"));
|
|
assert(problems({ ...table, pools: [{ rolls: -1, entries: [{ item: "t:a" }] }] }).includes("rolls"));
|
|
assert(problems({ ...table, pools: [{ entries: [{ type: "tag", tag: "t:gems" }] }] }).includes("#tag"));
|
|
assert(
|
|
problems({ ...table, pools: [{ entries: [{ type: "loot_table" }] }] }).includes(
|
|
"table must be a loot table id",
|
|
),
|
|
);
|
|
assert(problems({ ...table, conditions: [{ condition: "full_moon" }] }).includes("condition must be one of"));
|
|
assert(problems({ ...table, functions: [{ function: "enchant" }] }).includes("function must be one of"));
|
|
assert(
|
|
problems({ ...table, conditions: [{ condition: "random_chance", chance: 2 }] }).includes(
|
|
"chance must be at most 1",
|
|
),
|
|
);
|
|
// a mod's own are only checked once its script registers them
|
|
assertEquals(validate_loot_table({ ...table, conditions: [{ condition: "m:full_moon" }] }), []);
|
|
});
|
|
|
|
// a mod with loot tables for a block, a mob and a chest, and a script with its own condition, function and modifier
|
|
function loot_mod(dir: string) {
|
|
const mod = `${dir}/testloot`;
|
|
const write = (path: string, json: unknown) => {
|
|
Deno.mkdirSync(`${mod}/${path.split("/").slice(0, -1).join("/")}`, { recursive: true });
|
|
Deno.writeTextFileSync(`${mod}/${path}`, JSON.stringify(json));
|
|
};
|
|
write("manifest.json", {
|
|
format_version: 1,
|
|
id: "testloot",
|
|
name: "Test Loot",
|
|
version: "1.0.0",
|
|
dependencies: [{ id: "bworld", version: "*" }],
|
|
scripts: { server: "scripts/server.ts" },
|
|
});
|
|
for (const id of ["gem", "charm"]) {
|
|
write(`items/${id}.json`, { format_version: 1, item: { id: `testloot:${id}`, texture: `testloot:${id}` } });
|
|
}
|
|
write("blocks/ore.json", {
|
|
format_version: 1,
|
|
block: {
|
|
id: "testloot:ore",
|
|
textures: "bworld:stone",
|
|
mining: { toughness: 0 },
|
|
loot_table: "testloot:blocks/ore",
|
|
},
|
|
});
|
|
write("entities/golem.json", {
|
|
format_version: 1,
|
|
entity: {
|
|
id: "testloot:golem",
|
|
texture: "bworld:stone",
|
|
width: 1,
|
|
height: 2,
|
|
max_health: 10,
|
|
loot_table: "testloot:entities/golem",
|
|
},
|
|
});
|
|
const table = (path: string, loot_table: unknown) =>
|
|
write(`loot_tables/${path}.json`, { format_version: 1, loot_table });
|
|
// 2 gems for a pickaxe, doubled by the mod's function
|
|
table("blocks/ore", {
|
|
pools: [{
|
|
conditions: [{ condition: "match_tool", tool: "pickaxe" }],
|
|
entries: [{ item: "testloot:gem", count: 2, functions: [{ function: "testloot:double" }] }],
|
|
}],
|
|
});
|
|
// a gem when a player killed it, a charm when it died up high
|
|
table("entities/golem", {
|
|
pools: [
|
|
{ conditions: [{ condition: "killed_by_player" }], entries: [{ item: "testloot:gem" }] },
|
|
{ conditions: [{ condition: "testloot:high" }], entries: [{ item: "testloot:charm" }] },
|
|
],
|
|
});
|
|
table("chests/treasure", { pools: [{ rolls: 3, entries: [{ item: "testloot:gem" }] }] });
|
|
Deno.mkdirSync(`${mod}/scripts`);
|
|
Deno.writeTextFileSync(
|
|
`${mod}/scripts/server.ts`,
|
|
`import type { ServerContext } from "bworld/server";
|
|
export function setup(ctx: ServerContext) {
|
|
ctx.loot.register_condition("testloot:high", (_params, context) => (context.position?.y ?? 0) > 120);
|
|
ctx.loot.register_function("testloot:double", (item) => ({ ...item, count: item.count * 2 }));
|
|
ctx.loot.modify("testloot:chests/treasure", (items) => { items.push({ id: "testloot:charm", count: 1 }); });
|
|
ctx.events.after.chat_send.subscribe(({ message }) => {
|
|
if (message !== "treasure") return;
|
|
const container = ctx.containers.create(2);
|
|
const left = ctx.loot.fill(container, "testloot:chests/treasure");
|
|
const slots = [0, 1].map((slot) => container.get(slot)?.id ?? null).sort();
|
|
ctx.storage.set("filled", { slots, left: left.map((item) => item.id) });
|
|
});
|
|
}
|
|
`,
|
|
);
|
|
}
|
|
|
|
async function setup() {
|
|
const dir = Deno.makeTempDirSync({ prefix: "bworld_loot_" });
|
|
copy_dir("mods/bworld", `${dir}/bworld`);
|
|
loot_mod(dir);
|
|
const t = await test_game(dir);
|
|
t.join(1, "alice");
|
|
t.send(1, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0 });
|
|
return { ...t, dir };
|
|
}
|
|
|
|
Deno.test("check-mods catches loot tables that point at nothing", () => {
|
|
const dir = Deno.makeTempDirSync({ prefix: "bworld_loot_check_" });
|
|
copy_dir("mods/bworld", `${dir}/bworld`);
|
|
loot_mod(dir);
|
|
const ok = load_and_check(dir).find((mod) => mod.id === "testloot")!;
|
|
assertEquals(ok.report.errors, []);
|
|
assertEquals(ok.loot_tables.map((t) => t.json.id).sort(), [
|
|
"testloot:blocks/ore",
|
|
"testloot:chests/treasure",
|
|
"testloot:entities/golem",
|
|
]);
|
|
|
|
Deno.writeTextFileSync(
|
|
`${dir}/testloot/loot_tables/broken.json`,
|
|
JSON.stringify({
|
|
format_version: 1,
|
|
loot_table: {
|
|
pools: [{ entries: [{ item: "testloot:nothing" }, { type: "loot_table", table: "testloot:nowhere" }] }],
|
|
},
|
|
}),
|
|
);
|
|
const errors = load_and_check(dir).find((mod) => mod.id === "testloot")!.report.errors;
|
|
assert(errors.some((e) => e.includes("item testloot:nothing doesn't exist")), errors.join("\n"));
|
|
assert(errors.some((e) => e.includes("loot table testloot:nowhere doesn't exist")), errors.join("\n"));
|
|
Deno.removeSync(dir, { recursive: true });
|
|
});
|
|
|
|
Deno.test("a broken block drops from its loot table, with the tool it was broken with", async () => {
|
|
const t = await setup();
|
|
const dropped = () => t.game.item_entities().map((e) => e.item.to_data());
|
|
t.game.set_block(1, 100, 0, "testloot:ore");
|
|
t.send(1, { type: "break_block", x: 1, y: 100, z: 0 });
|
|
// broken by hand, it gives nothing
|
|
assertEquals(t.game.world.get_block_id(1, 100, 0), "cubi:air");
|
|
assertEquals(dropped(), []);
|
|
|
|
t.send(1, { type: "chat", text: "/give bworld:iron_pickaxe" });
|
|
t.game.set_block(1, 100, 0, "testloot:ore");
|
|
t.send(1, { type: "break_block", x: 1, y: 100, z: 0 });
|
|
assertEquals(dropped(), [{ id: "testloot:gem", count: 4 }]);
|
|
Deno.removeSync(t.dir, { recursive: true });
|
|
});
|
|
|
|
Deno.test("a mob drops its loot table when it dies, more when a player killed it", async () => {
|
|
const t = await setup();
|
|
const player = t.game.players()[0];
|
|
const kill = (y: number, by_player: boolean) => {
|
|
for (const item of t.game.item_entities()) item.remove();
|
|
const golem = create_entity(t.game.entities, "testloot:golem") as LivingEntity;
|
|
golem.set_position(0.5, y, 3.5);
|
|
t.game.entities.add_entity(golem);
|
|
golem.hurt(100, { type: "physical", cause: "test", attacker: by_player ? player : undefined, by_player });
|
|
return t.game.item_entities().map((e) => e.item.type_id).sort();
|
|
};
|
|
assertEquals(kill(100, false), []);
|
|
assertEquals(kill(100, true), ["testloot:gem"]);
|
|
assertEquals(kill(130, true), ["testloot:charm", "testloot:gem"]);
|
|
Deno.removeSync(t.dir, { recursive: true });
|
|
});
|
|
|
|
Deno.test("scripts fill containers from a table their modifier changes, and keep what doesn't fit", async () => {
|
|
const t = await setup();
|
|
t.send(1, { type: "chat", text: "treasure" });
|
|
// 3 gems and the modifier's charm, into 2 slots
|
|
const filled = t.game.mods.storage.testloot.filled as { slots: string[]; left: string[] };
|
|
assertEquals(filled.slots.length, 2);
|
|
assertEquals([...filled.slots, ...filled.left].sort(), ["testloot:charm", ...Array(3).fill("testloot:gem")]);
|
|
Deno.removeSync(t.dir, { recursive: true });
|
|
});
|