Files
bworld/templates/mod/scripts/main.ts
T
2026-11-14 12:18:41 -03:00

66 lines
2.3 KiB
TypeScript

import type { ClientContext } from "cubi/client";
import type { ServerContext } from "cubi/server";
import type { WorldgenContext } from "cubi/worldgen";
// the mod's script. each export is a phase, called where and when it runs. this file goes to the server and to every
// player, and each runs only its own phases, so keep the top level free of anything only one side has
// called once when the server starts. players never run it, so game rules belong here
export function server(ctx: ServerContext) {
// used by blocks/example_block.json, which passes { message } as params
ctx.components.register_block<{ message: string }>("example_mod:announce", {
// block data is saved with the world. on_tick and on_second only run for blocks that have some
on_create(block) {
block.data = { age: 0 };
},
// on_tick runs 20 times a second, on_second once, while a player is nearby
on_second(block) {
block.data.age += 1;
},
on_interact(block, params, player) {
player.send_message(`${params.message} It's been here for ${block.data?.age ?? 0} seconds.`);
// handled, so right clicking it doesn't place a block
return true;
},
});
// /example_mod:hello, or /hello when no other mod uses that name
ctx.commands.register("hello", {
description: "Say hello",
usage: "/hello",
run(_args, player) {
player.send_message(`Hello ${player.name}!`);
},
});
ctx.events.after.player_join.subscribe(({ player }) => {
ctx.log(`${player.name} joined`);
});
}
// called on every player's client after the mod is downloaded, before the world shows up
export function client(ctx: ClientContext) {
ctx.log("loaded");
// a HUD element, drawn every frame
// ctx.hud.register("example_mod:hint", {
// on_render(g) {
// g.text("example mod is here", 8, 8);
// },
// });
}
// runs wherever the server generates chunks, which must always give the same world. only use chunk.rng and the noise
// helpers, never Math.random or the time
export function worldgen(gen: WorldgenContext) {
// a boulder on one chunk in ten
gen.register_feature("example_mod:boulders", (chunk) => {
if (chunk.rng.next() > 0.1) {
return;
}
const x = chunk.x * 16 + Math.floor(chunk.rng.next() * 16);
const z = chunk.z * 16 + Math.floor(chunk.rng.next() * 16);
chunk.set_block(x, chunk.height_at(x, z) + 1, z, "bworld:stone");
});
}