Improve commands

This commit is contained in:
2026-09-27 00:38:55 -03:00
parent 535bd36d91
commit 8c7ca92891
13 changed files with 1095 additions and 109 deletions
+62 -3
View File
@@ -382,7 +382,7 @@ and `items/cabbage_seeds.json` with `"places": "farmersdelight:cabbages"`.
| --------------- | ------------------------------------------------------------------------------------------------------------ |
| `days` | Watered mornings from planting to fully grown. |
| `stages` | How many ages it shows, 0 to `stages - 1`, spread evenly over `days`. The `age` state must fit them. |
| `drops` | Like a crop's loot table: `young` (not grown yet), `mature` (grown), and `bonus`, 0 to 3 more of an item when grown, like wheat's extra seeds. `young` and `mature` can be one id or a list. |
| `drops` | Like a crop's loot table: `young` (not grown yet), `mature` (grown), and `bonus`, 1 to 4 of an item when grown, like wheat's seeds (Minecraft's 1 plus 3 tries at 57%). `young` and `mature` can be one id or a list. |
| `fertilizer` | An item that grows it a day right away, like bone meal. |
| `regrow_days`, `harvest` | Picked by right clicking once grown, dropping `harvest.item` (`count` is `[min, max]`), then grown again after `regrow_days`, like tomatoes. |
| `water` | `"farmland"` (the default): needs watered farmland under it. `"always"`: grows every morning, like rice in water. |
@@ -790,6 +790,55 @@ as the clients. Blocks in unloaded chunks can't be read or changed, and don't ti
### Commands
Commands work like Fabric's, which are Minecraft's Brigadier: a tree of literal words and typed arguments. Each
argument type reads its text and suggests what could go there, and players see those suggestions above the chat box as
they type (Tab puts one in, Up and Down pick). The tree is in `common/commands.ts`.
```ts
const { literal, argument, types } = ctx.commands;
ctx.commands.register(
literal("heal")
.describe("Heals a player")
.requires((source) => source.player.name === ctx.storage.get("owner"))
.executes((context) => heal(context.source.player, 20))
.then(
argument("amount", types.integer(1, 20))
.executes((context) => heal(context.source.player, context.get<number>("amount")))
.then(
argument("target", types.player())
.executes((context) => heal(context.get<Player>("target"), context.get<number>("amount"))),
),
),
);
```
| Builder | What it does |
| --------------------------- | --------------------------------------------------------------------------------------------------- |
| `literal(name)` | A word that has to be typed as is. Words are tried before arguments. |
| `argument(name, type)` | A value read by `type`, then `context.get(name)` in `executes`. |
| `.then(node)` | What can come next. |
| `.executes(fn)` | Runs when the command ends here. Without it, ending here says what's missing. |
| `.requires(fn)` | Only for sources it's true for. Others can't run it, and don't see it suggested. |
| `.suggests(fn)` | `(partial, source) => [{ text, tooltip? }]` in place of the argument type's own suggestions. |
| `.describe(text)` | Shown by `/help`. |
`context.source` has the `player` who typed it and `send_message(text)` to answer them. Throwing
`new CommandError(message)` tells the player what's wrong. Any other error is logged with the mod's id and the player
is told something went wrong.
| `types.` | Reads | Suggests |
| ------------------------- | ------------------------------------------------------------------------------------------------ | ------------------------------ |
| `integer(min?, max?)` | a whole number | |
| `number(min?, max?)` | any number | |
| `boolean()` | `true` or `false` | both |
| `word()` | one word | |
| `greedy_string()` | the rest of the line, spaces and all. Nothing can come after it | |
| `choice([...])` | one of the given words | them |
| `item()` and `block()` | an id. `carrot` works too while only one mod has a `carrot` | ids, with the name as tooltip |
| `player()` | an online player's name, as a `Player` | online players |
The simple form is still there, it's a command taking the rest of the line split on spaces:
```ts
ctx.commands.register("heal", {
description: "Heal yourself",
@@ -800,8 +849,18 @@ ctx.commands.register("heal", {
});
```
Commands run on the server when a player types `/name` in chat. Two mods using the same name, or a mod using one of the
engine's (`give`, `time` and `tps`, until phase 5 moves `give` and `time` into `mods/bworld`), is a load error. `/copper_tools:heal` always works as the unambiguous form.
Commands run on the server when a player types `/name` in chat, and the client asks the server for suggestions. Two
mods using the same name, or a mod using one of the engine's (`give`, `time`, `tps` and `help`), is a load error.
`/copper_tools:heal` always works as the unambiguous form.
The engine's commands:
| Command | What it does |
| --------------------------------------------------------- | ----------------------------------------------------------------------- |
| `/give <item> [<count>]` | Gives you an item |
| `/time`, `/time set <day\|noon\|sunset\|night\|midnight\|ticks>`, `/time add <ticks>` | Shows or changes the time. Times of day are the next one, time never goes back |
| `/tps` | How the game loop keeps up |
| `/help [<command>]` | Every command's usage, or one's |
## Client scripts
+4
View File
@@ -185,6 +185,10 @@ export class Client {
if (InputManager.is_key_pressed(options.key_chat) && !this.screen) {
this.push_screen(new GuiChat(this));
}
// straight into a command, like minecraft
if (InputManager.is_key_pressed("Slash") && !this.screen) {
this.push_screen(new GuiChat(this, "/"));
}
// browsers eat the escape that lets go of the mouse, so losing the mouse pauses too
const lost_mouse = InputManager.take_lost_pointer_lock();
if (InputManager.is_key_pressed("Escape")) {
+133 -8
View File
@@ -1,32 +1,60 @@
import { GuiScreen } from "./gui_screen.ts";
import { canvas, draw_rect, draw_text } from "$/client/renderer/mod.ts";
import { canvas, draw_rect, draw_text, measure_text } from "$/client/renderer/mod.ts";
import { InputManager } from "../input_manager.ts";
import type { Client } from "../client.ts";
import { MAX_CHAT_LENGTH } from "$/common/protocol.ts";
import { TextInput } from "./widgets.ts";
import { MAX_CHAT_LENGTH, type ServerMessage } from "$/common/protocol.ts";
import type { Suggestion } from "$/common/commands.ts";
import { TEXT_HEIGHT, TextInput } from "./widgets.ts";
const SCALE = 2;
const INPUT_HEIGHT = 32;
// how many suggestions show at once, the list scrolls with the selection past that
const VISIBLE_SUGGESTIONS = 10;
const ROW_HEIGHT = TEXT_HEIGHT * SCALE + 2;
const PADDING = 4;
const TOOLTIP_GAP = 16;
const SELECTED: [number, number, number, number] = [1, 1, 0.33, 1];
const TOOLTIP_COLOR: [number, number, number, number] = [0.6, 0.6, 0.6, 1];
export class GuiChat extends GuiScreen {
client: Client;
input = new TextInput("", MAX_CHAT_LENGTH);
input: TextInput;
constructor(client: Client) {
// what the server suggests for the command being typed, like minecraft's CommandSuggestions. they replace the
// text from start up to the caret
suggestions: Suggestion[] = [];
suggestions_start = 0;
// highlighted with the arrows, tab puts it in. -1 is none yet
selected = -1;
// the text up to the caret suggestions were last asked for, and the id of that request. only its answer is used
#asked = "";
#request_id = 0;
// tab just put in a suggestion, so another tab goes to the next one instead of asking again
#cycling = false;
constructor(client: Client, text = "") {
super();
this.client = client;
this.input = new TextInput(text, MAX_CHAT_LENGTH);
}
override on_render(): void {
draw_rect(0, 0, canvas.width, canvas.height, [0, 0, 0, 0.8]);
const y = canvas.height - 32;
const y = canvas.height - INPUT_HEIGHT;
this.client.chat.render(true, y - 8);
draw_rect(0, y, canvas.width, canvas.height, [0, 0, 0, 0.4]);
draw_text(this.input.value, 0, y, 2, [1, 1, 1]);
draw_rect(this.input.caret_x(0, 2), y + 4, 1, 32 - 4);
draw_text(this.input.value, 0, y, SCALE, [1, 1, 1]);
draw_rect(this.input.caret_x(0, SCALE), y + 4, 1, INPUT_HEIGHT - 4);
this.#render_suggestions(y);
}
override on_tick(_delta: number): void {
this.#handle_suggestion_keys();
this.input.handle_keys();
this.#ask_for_suggestions();
if (InputManager.is_key_pressed("Enter")) {
this.submit();
}
@@ -41,4 +69,101 @@ export class GuiChat extends GuiScreen {
}
this.client.pop_screen();
}
// from the packet listener
receive_suggestions(message: Extract<ServerMessage, { type: "suggestions" }>) {
if (message.id !== this.#request_id) {
return;
}
this.suggestions = message.suggestions;
this.suggestions_start = message.start;
this.selected = -1;
this.#cycling = false;
}
#handle_suggestion_keys() {
const count = this.suggestions.length;
if (count === 0) {
return;
}
if (InputManager.is_key_pressed("ArrowUp")) {
this.selected = this.selected <= 0 ? count - 1 : this.selected - 1;
this.#cycling = false;
}
if (InputManager.is_key_pressed("ArrowDown")) {
this.selected = (this.selected + 1) % count;
this.#cycling = false;
}
if (InputManager.is_key_pressed("Tab")) {
const back = InputManager.is_key_down("ShiftLeft") || InputManager.is_key_down("ShiftRight");
if (this.selected === -1) {
this.selected = back ? count - 1 : 0;
} else if (this.#cycling) {
this.selected = (this.selected + (back ? count - 1 : 1)) % count;
}
this.#apply(this.suggestions[this.selected]);
this.#cycling = true;
}
}
// puts it in place of what's typed from start to the caret
#apply(suggestion: Suggestion) {
const value = this.input.value;
const caret = this.input.caret;
const start = Math.min(this.suggestions_start, caret);
this.input.value = (value.slice(0, start) + suggestion.text + value.slice(caret)).slice(0, MAX_CHAT_LENGTH);
this.input.caret = Math.min(start + suggestion.text.length, this.input.value.length);
// the list stays for tabbing through, it's asked for again once they type
this.#asked = this.input.value.slice(0, this.input.caret);
}
// only commands have suggestions, and only when what's before the caret changed
#ask_for_suggestions() {
const before_caret = this.input.value.slice(0, this.input.caret);
if (before_caret === this.#asked) {
return;
}
this.#asked = before_caret;
this.#request_id += 1;
this.suggestions = [];
this.selected = -1;
this.#cycling = false;
if (before_caret.startsWith("/")) {
this.client.connection.send({ type: "suggest", id: this.#request_id, text: before_caret });
}
}
// a list going up from the input, lined up under the word it replaces
#render_suggestions(input_y: number) {
const count = this.suggestions.length;
if (count === 0) {
return;
}
const first = Math.max(0, Math.min(this.selected - VISIBLE_SUGGESTIONS + 1, count - VISIBLE_SUGGESTIONS));
const shown = this.suggestions.slice(first, first + VISIBLE_SUGGESTIONS);
const text_width = Math.max(...shown.map((s) => measure_text(s.text, SCALE)));
const tooltip_width = Math.max(0, ...shown.map((s) => s.tooltip ? measure_text(s.tooltip, SCALE) : 0));
const width = text_width + (tooltip_width > 0 ? TOOLTIP_GAP + tooltip_width : 0) + PADDING * 2;
const height = shown.length * ROW_HEIGHT + PADDING * 2;
const start = Math.min(this.suggestions_start, this.input.value.length);
const x = Math.max(
0,
Math.min(measure_text(this.input.value.slice(0, start), SCALE) - PADDING, canvas.width - width),
);
const y = input_y - height;
draw_rect(x, y, width, height, [0, 0, 0, 0.9]);
shown.forEach((suggestion, i) => {
const row_y = y + PADDING + i * ROW_HEIGHT;
const selected = first + i === this.selected;
draw_text(suggestion.text, x + PADDING, row_y, SCALE, selected ? SELECTED : [0.8, 0.8, 0.8, 1]);
if (suggestion.tooltip) {
draw_text(suggestion.tooltip, x + PADDING + text_width + TOOLTIP_GAP, row_y, SCALE, TOOLTIP_COLOR);
}
});
// more above or below
if (first > 0) draw_rect(x, y, width, 1, [1, 1, 1, 0.6]);
if (first + shown.length < count) draw_rect(x, y + height - 1, width, 1, [1, 1, 1, 0.6]);
}
}
+1
View File
@@ -58,6 +58,7 @@ export type KeyCode =
| "Home"
| "End"
| "Backspace"
| "Slash"
| "Delete"
// f
| "F1"
+6
View File
@@ -2,6 +2,7 @@ import type { ServerMessage } from "$/common/protocol.ts";
import { Container, ItemStack } from "$/common/inventory.ts";
import type { Client } from "./client.ts";
import { GuiContainer } from "./gui/gui_container.ts";
import { GuiChat } from "./gui/gui_chat.ts";
import { RemotePlayer } from "./entity/remote_player.ts";
import { ItemEntity } from "./entity/item_entity.ts";
@@ -86,6 +87,11 @@ export class ClientPacketListener {
case "chat":
client.chat.add(message.from ? `<${message.from}> ${message.text}` : message.text);
break;
case "suggestions":
if (client.screen instanceof GuiChat) {
client.screen.receive_suggestions(message);
}
break;
case "container": {
let container = message.container === "screen" ? inventories.screen : inventories[message.container];
if (message.container === "screen" && container?.size !== message.items.length) {
+375
View File
@@ -0,0 +1,375 @@
// commands the way minecraft's brigadier (and so fabric's command api) does them: a tree of literal words and typed
// arguments, each argument type parsing its text and suggesting what could go there. the server runs them, and players
// get its suggestions as they type. see "Commands" in MODS.md
import { EverythingRegistry } from "./everything_registry.ts";
export interface Suggestion {
text: string;
// shown next to it, like an item's name
tooltip?: string;
}
// what went wrong, told to the player who typed it
export class CommandError extends Error {
constructor(message: string) {
super(message);
this.name = "CommandError";
}
}
// how an argument reads its text, and what could go there
export interface ArgumentType<T = unknown, S = unknown> {
// takes the rest of the line, spaces and all, like a chat message
readonly greedy?: boolean;
// throws CommandError when the text doesn't fit
parse(text: string, source: S): T;
suggest?(partial: string, source: S): Suggestion[];
}
export interface CommandContext<S> {
source: S;
// the value of an argument by its name, as its type parsed it
get<T>(name: string): T;
// what was typed, without the /
input: string;
}
export type CommandFunction<S> = (context: CommandContext<S>) => void;
// a word or an argument, and what can follow it. like brigadier's builders, the methods chain:
// literal("give").then(argument("item", item()).executes(...))
export class CommandNode<S = unknown> {
readonly children: CommandNode<S>[] = [];
command?: CommandFunction<S>;
requirement?: (source: S) => boolean;
suggestion_provider?: (partial: string, source: S) => Suggestion[];
// for /help
description?: string;
constructor(readonly name: string, readonly type?: ArgumentType<unknown, S>) {}
then(child: CommandNode<S>): this {
this.children.push(child);
// words before arguments, so a literal wins over an argument that would take the same word
this.children.sort((a, b) => Number(a.type !== undefined) - Number(b.type !== undefined));
return this;
}
executes(command: CommandFunction<S>): this {
this.command = command;
return this;
}
// only for sources this is true for, like operators. others can't run it or see it suggested
requires(requirement: (source: S) => boolean): this {
this.requirement = requirement;
return this;
}
// suggestions for this argument instead of its type's
suggests(provider: (partial: string, source: S) => Suggestion[]): this {
this.suggestion_provider = provider;
return this;
}
describe(description: string): this {
this.description = description;
return this;
}
get is_literal() {
return this.type === undefined;
}
}
export function literal<S = unknown>(name: string): CommandNode<S> {
return new CommandNode<S>(name);
}
export function argument<T, S = unknown>(name: string, type: ArgumentType<T, S>): CommandNode<S> {
return new CommandNode<S>(name, type as ArgumentType<unknown, S>);
}
interface Token {
text: string;
start: number;
}
interface Failure {
// how far it got, the error from the furthest attempt is the one worth showing
at: number;
message: string;
}
export class CommandDispatcher<S> {
readonly root = new CommandNode<S>("");
// adds a command at the top. a second one with the same name is an error, use then() to add to an existing one
register(node: CommandNode<S>): CommandNode<S> {
if (!node.is_literal) throw new Error("commands start with a word, use literal()");
if (this.get(node.name)) throw new Error(`/${node.name} already exists`);
this.root.then(node);
return node;
}
get(name: string): CommandNode<S> | undefined {
return this.root.children.find((child) => child.name === name);
}
// runs what was typed, without the /. throws CommandError saying what's wrong
execute(input: string, source: S) {
const tokens = tokenize(input);
const failures: Failure[] = [];
const found = this.#parse(this.root, tokens, 0, new Map(), source, input, failures);
if (!found) {
const failure = failures.sort((a, b) => b.at - a.at)[0];
throw new CommandError(failure?.message ?? `Unknown command /${tokens[0]?.text ?? ""}`);
}
const args = found.args;
found.command({
source,
input,
get<T>(name: string) {
if (!args.has(name)) throw new Error(`there's no argument "${name}"`);
return args.get(name) as T;
},
});
}
// what could come at the end of input, for the word being typed: start is where it begins in input
suggest(input: string, source: S): { start: number; suggestions: Suggestion[] } {
const tokens = tokenize(input);
const partial = tokens.pop() ?? { text: "", start: input.length };
const nodes = this.#walk(this.root, tokens, 0, source);
const seen = new Set<string>();
const suggestions: Suggestion[] = [];
for (const node of nodes) {
for (const child of node.children) {
if (child.requirement && !safe(() => child.requirement!(source), false)) continue;
let found: Suggestion[];
if (child.is_literal) {
found = child.name.startsWith(partial.text) ? [{ text: child.name }] : [];
} else {
const provider = child.suggestion_provider ?? child.type!.suggest?.bind(child.type);
found = provider ? safe(() => provider(partial.text, source), []) : [];
}
for (const suggestion of found) {
if (seen.has(suggestion.text)) continue;
seen.add(suggestion.text);
suggestions.push(suggestion);
}
}
}
suggestions.sort((a, b) => a.text.localeCompare(b.text));
return { start: partial.start, suggestions };
}
// how to use a command, like brigadier's smart usage: "give <item> [<count>]"
usage(node: CommandNode<S>, source: S): string {
const own = node.is_literal ? node.name : `<${node.name}>`;
const children = node.children.filter((child) =>
!child.requirement || safe(() => child.requirement!(source), false)
);
if (children.length === 0) return own;
const inner = children.length === 1
? this.usage(children[0], source)
: children.map((child) => child.is_literal ? child.name : `<${child.name}>`).join("|");
if (node.command) return `${own} [${inner}]`;
return children.length === 1 ? `${own} ${inner}` : `${own} (${inner})`;
}
#parse(
node: CommandNode<S>,
tokens: Token[],
index: number,
args: Map<string, unknown>,
source: S,
input: string,
failures: Failure[],
): { command: CommandFunction<S>; args: Map<string, unknown> } | undefined {
if (index === tokens.length) {
if (node.command) return { command: node.command, args };
failures.push({ at: index, message: `Not enough: /${this.usage(this.#top(node, tokens), source)}` });
return undefined;
}
const token = tokens[index];
for (const child of node.children) {
if (child.requirement && !safe(() => child.requirement!(source), false)) continue;
if (child.is_literal) {
if (child.name !== token.text) continue;
const found = this.#parse(child, tokens, index + 1, args, source, input, failures);
if (found) return found;
continue;
}
const type = child.type!;
const text = type.greedy ? input.slice(token.start) : token.text;
let value: unknown;
try {
value = type.parse(text, source);
} catch (e) {
failures.push({ at: index, message: e instanceof CommandError ? e.message : `Can't read "${text}"` });
continue;
}
const next = new Map(args).set(child.name, value);
const found = this.#parse(
child,
tokens,
type.greedy ? tokens.length : index + 1,
next,
source,
input,
failures,
);
if (found) return found;
}
if (index === 0) {
failures.push({ at: 0, message: `Unknown command /${token.text}` });
} else {
failures.push({
at: index,
message: `Didn't expect "${token.text}": /${this.usage(this.#top(node, tokens), source)}`,
});
}
return undefined;
}
// the nodes reachable after the whole tokens, where the next word could go
#walk(node: CommandNode<S>, tokens: Token[], index: number, source: S): CommandNode<S>[] {
if (index === tokens.length) return [node];
const reached: CommandNode<S>[] = [];
for (const child of node.children) {
if (child.requirement && !safe(() => child.requirement!(source), false)) continue;
if (child.is_literal) {
if (child.name === tokens[index].text) reached.push(...this.#walk(child, tokens, index + 1, source));
} else if (
!child.type!.greedy && safe(() => (child.type!.parse(tokens[index].text, source), true), false)
) {
reached.push(...this.#walk(child, tokens, index + 1, source));
}
}
return reached;
}
// the command a parse was in, for its usage
#top(node: CommandNode<S>, tokens: Token[]): CommandNode<S> {
return node === this.root ? node : this.get(tokens[0]?.text ?? "") ?? node;
}
}
// words split on single spaces, remembering where each starts. "a b" has an empty word between, which nothing matches
function tokenize(input: string): Token[] {
const tokens: Token[] = [];
let start = 0;
for (const text of input.split(" ")) {
tokens.push({ text, start });
start += text.length + 1;
}
return tokens;
}
function safe<T>(fn: () => T, fallback: T): T {
try {
return fn();
} catch {
return fallback;
}
}
// argument types, like brigadier's and minecraft's
export function integer(min = -Infinity, max = Infinity): ArgumentType<number> {
return {
parse(text) {
const value = Number(text);
if (!/^-?\d+$/.test(text) || !Number.isSafeInteger(value)) {
throw new CommandError(`"${text}" isn't a whole number`);
}
if (value < min) throw new CommandError(`${value} is too small, the least is ${min}`);
if (value > max) throw new CommandError(`${value} is too big, the most is ${max}`);
return value;
},
};
}
export function number(min = -Infinity, max = Infinity): ArgumentType<number> {
return {
parse(text) {
const value = Number(text);
if (text === "" || !Number.isFinite(value)) throw new CommandError(`"${text}" isn't a number`);
if (value < min) throw new CommandError(`${value} is too small, the least is ${min}`);
if (value > max) throw new CommandError(`${value} is too big, the most is ${max}`);
return value;
},
};
}
export function boolean(): ArgumentType<boolean> {
return {
parse(text) {
if (text === "true") return true;
if (text === "false") return false;
throw new CommandError(`"${text}" isn't true or false`);
},
suggest: (partial) => ["true", "false"].filter((b) => b.startsWith(partial)).map((text) => ({ text })),
};
}
// one word, anything without spaces
export function word(): ArgumentType<string> {
return {
parse(text) {
if (text === "") throw new CommandError("Expected a word");
return text;
},
};
}
// the rest of the line
export function greedy_string(): ArgumentType<string> {
return { greedy: true, parse: (text) => text };
}
// one of a few words, suggested
export function choice<T extends string>(options: readonly T[]): ArgumentType<T> {
return {
parse(text) {
if (!options.includes(text as T)) throw new CommandError(`"${text}" isn't one of ${options.join(", ")}`);
return text as T;
},
suggest: (partial) => options.filter((o) => o.startsWith(partial)).map((text) => ({ text })),
};
}
// an id from a registry. without a namespace it's whichever id has that name, as long as only one does
function registry_id(registry: string, what: string, names: (id: string) => string | undefined): ArgumentType<string> {
return {
parse(text) {
if (text.includes(":")) {
if (!EverythingRegistry.get(registry, text)) throw new CommandError(`There's no ${what} ${text}`);
return text;
}
const matches = EverythingRegistry.entries(registry).map(([id]) => id).filter((id) =>
id.endsWith(`:${text}`)
);
if (matches.length === 0) throw new CommandError(`There's no ${what} called ${text}`);
if (matches.length > 1) throw new CommandError(`Which one? ${matches.join(", ")}`);
return matches[0];
},
// full ids starting with it, or whose name part does, like minecraft
suggest(partial) {
return EverythingRegistry.entries(registry)
.map(([id]) => id)
.filter((id) => id !== "bworld:air" && (id.startsWith(partial) || id.split(":")[1].startsWith(partial)))
.map((id) => ({ text: id, tooltip: names(id) }));
},
};
}
export function item(names: (id: string) => string | undefined = () => undefined): ArgumentType<string> {
return registry_id("items", "item", names);
}
export function block(names: (id: string) => string | undefined = () => undefined): ArgumentType<string> {
return registry_id("blocks", "block", names);
}
+30 -1
View File
@@ -1,5 +1,8 @@
// what server scripts get, see "Server scripts" in MODS.md
import type { EventSignal, Face, Id, ItemStack, ModInfo, Position } from "./shared.ts";
import type { ArgumentType, CommandNode } from "../commands.ts";
export type { ArgumentType, CommandContext, CommandNode, Suggestion } from "../commands.ts";
export type { EventSignal, Face, Id, ItemStack, ModInfo, Position } from "./shared.ts";
@@ -58,8 +61,16 @@ export interface ComponentRegistry {
register_item<P>(id: Id, component: ItemComponent<P>): void;
}
// commands
// commands, fabric's (brigadier's) way: see common/commands.ts and "Commands" in MODS.md
// who ran a command
export interface CommandSource {
readonly player: Player;
// answers them in chat
send_message(text: string): void;
}
// the simple way: the words after the name, split on spaces
export interface Command {
description: string;
usage: string;
@@ -67,7 +78,25 @@ export interface Command {
}
export interface CommandRegistry {
// a tree of literal() and argument() nodes, like fabric's dispatcher.register(literal("heal").then(...))
register(node: CommandNode<CommandSource>): void;
register(name: string, command: Command): void;
literal(name: string): CommandNode<CommandSource>;
argument<T>(name: string, type: ArgumentType<T, CommandSource>): CommandNode<CommandSource>;
// argument types. they parse their text and suggest what could go there as players type
types: {
integer(min?: number, max?: number): ArgumentType<number, CommandSource>;
number(min?: number, max?: number): ArgumentType<number, CommandSource>;
boolean(): ArgumentType<boolean, CommandSource>;
word(): ArgumentType<string, CommandSource>;
greedy_string(): ArgumentType<string, CommandSource>;
choice<T extends string>(options: readonly T[]): ArgumentType<T, CommandSource>;
// an item or block id. without a namespace, whichever has that name
item(): ArgumentType<Id, CommandSource>;
block(): ArgumentType<Id, CommandSource>;
// an online player's name
player(): ArgumentType<Player, CommandSource>;
};
}
// events
+6 -2
View File
@@ -7,7 +7,7 @@ export const AIR_ID = "bworld:air";
// bump when a client and server of different versions can't play together.
// the server rejects a different version before the client downloads anything
export const PROTOCOL_VERSION = 5;
export const PROTOCOL_VERSION = 6;
export interface PlayerInfo {
id: string;
@@ -75,7 +75,9 @@ export type ClientMessage =
| { type: "drop_item"; container: ContainerKey; index: number; all: boolean }
// closes the open screen, including the player's own inventory screen
| { type: "close_screen" }
| { type: "chat"; text: string };
| { type: "chat"; text: string }
// what could come next in a command being typed, answered with suggestions. id matches them up
| { type: "suggest"; id: number; text: string };
export type ServerMessage =
// what to download before joining, see "Delivery to clients" in MODS.md
@@ -124,6 +126,8 @@ export type ServerMessage =
| { type: "close_screen" }
// the world time, every second and when it's changed. clients count ticks in between
| { type: "time"; time: number }
// answers suggest: start is where in the text the suggestions replace from, up to the caret
| { type: "suggestions"; id: number; start: number; suggestions: { text: string; tooltip?: string }[] }
// the player's own health, hunger and saturation, when they change
| { type: "vitals"; health: number; food: number; saturation: number };
+151 -78
View File
@@ -1,5 +1,4 @@
import {
AIR,
CHUNK_HEIGHT,
CHUNK_SIZE,
FACE_OFFSETS,
@@ -27,9 +26,19 @@ import {
import type { ModListing, RecipeBook } from "$/common/mod_loader.ts";
import type { WorldgenSetup } from "$/common/generation.ts";
import { CYCLE_TICKS, format_clock, time_of_day, TIMES_OF_DAY } from "$/common/time.ts";
import { can_place, can_stand_on, placement_target } from "$/common/utils.ts";
import { can_place, can_stand_on, display_name, placement_target } from "$/common/utils.ts";
import { EXHAUSTION, MAX_HEALTH } from "./vitals.ts";
import { ModRuntime, run_guarded } from "./mod_runtime.ts";
import { item_argument, ModRuntime, run_guarded, type ServerCommandSource } from "./mod_runtime.ts";
import {
argument,
choice,
type CommandContext,
CommandError,
type CommandNode,
integer,
literal,
word,
} from "$/common/commands.ts";
import type { GameLoop } from "./game_loop.ts";
import { consume_recipe_items, update_crafting_result } from "./crafting.ts";
import { OpenScreen, SavedPlayer, ServerPlayer } from "./player.ts";
@@ -53,6 +62,8 @@ const MERGE_DISTANCE = 0.5;
// tiles further than this many chunks from every player don't tick
const SIMULATION_DISTANCE = 6;
const MAX_GIVE = 64 * 36;
// the most suggestions sent for one request
const MAX_SUGGESTIONS = 100;
// falls up to this many blocks don't hurt, like minecraft
const SAFE_FALL = 3;
// faster than walking (4 blocks a second) and slower than sprinting (7)
@@ -160,6 +171,7 @@ export class GameServer {
}
this.#saved_players = saved?.players ?? {};
this.world.dirty = saved?.version !== 3;
this.#register_commands();
this.world.on_block_change = (x, y, z, id, state) =>
this.#broadcast(state ? { type: "set_block", x, y, z, id, state } : { type: "set_block", x, y, z, id });
@@ -661,6 +673,9 @@ export class GameServer {
case "chat":
this.#chat(player, message.text);
break;
case "suggest":
this.#suggest(player, message.id, message.text);
break;
}
}
@@ -890,85 +905,143 @@ export class GameServer {
this.mods.after.chat_send.emit({ player: before.player, message });
}
#command(player: ServerPlayer, text: string) {
const [command, ...args] = text.slice(1).split(/\s+/);
if (command === "give") {
// TODO: only let operators do this
let [item_id, count] = args;
if (!item_id) {
this.#send(player, { type: "chat", text: "Usage: /give <item> [count]" });
return;
}
// a name without a namespace works when only one mod has an item called that
if (!item_id.includes(":")) {
const matches = EverythingRegistry.entries("items").map(([id]) => id).filter((id) =>
id.endsWith(`:${item_id}`)
);
if (matches.length > 1) {
this.#send(player, { type: "chat", text: `Which one? ${matches.join(", ")}` });
return;
}
item_id = matches[0] ?? item_id;
}
const amount = count === undefined ? 1 : Number(count);
if (!EverythingRegistry.get("items", item_id)) {
this.#send(player, { type: "chat", text: `Unknown item ${item_id}` });
return;
}
if (!Number.isInteger(amount) || amount < 1 || amount > MAX_GIVE) {
this.#send(player, { type: "chat", text: `Count must be between 1 and ${MAX_GIVE}` });
return;
}
this.give(player, item_id, amount);
return;
}
if (command === "time") {
this.#time_command(player, args);
return;
}
if (command === "tps") {
if (!this.loop) {
this.#send(player, { type: "chat", text: "The game loop isn't running" });
return;
}
const { tps, mspt, skipped } = this.loop.stats;
this.#send(player, {
type: "chat",
text: `${tps} ticks per second (aiming for ${TICKS_PER_SECOND}), ${mspt.toFixed(1)} ms per tick, ` +
`${skipped} skipped since starting`,
});
return;
}
const mod_command = this.mods.commands.get(command);
if (mod_command) {
run_guarded(mod_command.mod, `/${command}`, () => mod_command.command.run(args, this.mods.player(player)));
return;
}
this.#send(player, { type: "chat", text: `Unknown command /${command}` });
// what typed commands run as
#command_source(player: ServerPlayer): ServerCommandSource {
const api = this.mods.player(player);
return { player: api, server_player: player, send_message: (text) => this.send_chat(player, text) };
}
// /time shows the time, /time set <ticks or day, noon, sunset, night, midnight> changes it, /time add <ticks>
#time_command(player: ServerPlayer, [action, value]: string[]) {
const usage = "Usage: /time [set <ticks|day|noon|sunset|night|midnight> | add <ticks>]";
if (action === undefined) {
this.#send(player, { type: "chat", text: `${format_clock(this.world.time)} (tick ${this.world.time})` });
#command(player: ServerPlayer, text: string) {
const input = text.slice(1);
try {
this.mods.commands.execute(input, this.#command_source(player));
} catch (e) {
if (e instanceof CommandError) {
this.send_chat(player, e.message);
return;
}
// a bug in whoever made the command, not something the player did
const name = input.split(" ")[0];
console.error(`[${this.mods.command_owners.get(name) ?? "?"}] /${name} threw:`, e);
this.send_chat(player, `Something went wrong running /${name}`);
}
}
// what could come next while they type a command, see common/commands.ts
#suggest(player: ServerPlayer, id: unknown, text: unknown) {
if (!is_int(id) || typeof text !== "string" || !text.startsWith("/") || text.length > MAX_CHAT_LENGTH) {
return;
}
const ticks = Number(value);
if (action === "set" && value !== undefined && value in TIMES_OF_DAY) {
// the next time it's that time of day, so days keep counting up
const now = this.world.time;
const target = now - time_of_day(now) + TIMES_OF_DAY[value];
this.set_time(target >= now ? target : target + CYCLE_TICKS);
} else if (action === "set" && Number.isInteger(ticks) && ticks >= 0) {
this.set_time(ticks);
} else if (action === "add" && Number.isInteger(ticks) && this.world.time + ticks >= 0) {
this.set_time(this.world.time + ticks);
} else {
this.#send(player, { type: "chat", text: usage });
return;
}
this.#broadcast({ type: "chat", text: `${player.name} set the time to ${format_clock(this.world.time)}` });
const { start, suggestions } = this.mods.commands.suggest(text.slice(1), this.#command_source(player));
this.#send(player, {
type: "suggestions",
id,
start: start + 1,
suggestions: suggestions.slice(0, MAX_SUGGESTIONS),
});
}
// the engine's own commands, registered like mods' so they're in /help and suggested the same way
#register_commands() {
const register = (node: CommandNode<ServerCommandSource>) => this.mods.register_command("engine", node);
// TODO: only let operators do this
const give = (context: CommandContext<ServerCommandSource>, count: number) => {
const id = context.get<string>("item");
this.give(context.source.server_player, id, count);
context.source.send_message(`Gave ${count} ${display_name(id)}`);
};
register(
literal<ServerCommandSource>("give").describe("Gives you an item").then(
argument<string, ServerCommandSource>("item", item_argument())
.executes((context) => give(context, 1))
.then(
argument<number, ServerCommandSource>("count", integer(1, MAX_GIVE))
.executes((context) => give(context, context.get<number>("count"))),
),
),
);
const set_time = (context: CommandContext<ServerCommandSource>, time: number) => {
this.set_time(time);
this.#broadcast({
type: "chat",
text: `${context.source.server_player.name} set the time to ${format_clock(this.world.time)}`,
});
};
register(
literal<ServerCommandSource>("time")
.describe("Shows or changes the time of day")
.executes((context) =>
context.source.send_message(`${format_clock(this.world.time)} (tick ${this.world.time})`)
)
.then(
literal<ServerCommandSource>("set")
.then(
argument<string, ServerCommandSource>("time_of_day", choice(Object.keys(TIMES_OF_DAY)))
.executes((context) => {
// the next time it's that time of day, so days keep counting up
const now = this.world.time;
const target = now - time_of_day(now) +
TIMES_OF_DAY[context.get<string>("time_of_day")];
set_time(context, target >= now ? target : target + CYCLE_TICKS);
}),
)
.then(
argument<number, ServerCommandSource>("ticks", integer(0))
.executes((context) => set_time(context, context.get<number>("ticks"))),
),
)
.then(
literal<ServerCommandSource>("add").then(
argument<number, ServerCommandSource>("ticks", integer())
.executes((context) =>
set_time(context, Math.max(0, this.world.time + context.get<number>("ticks")))
),
),
),
);
register(
literal<ServerCommandSource>("tps").describe("Shows how the game loop keeps up").executes((context) => {
if (!this.loop) {
context.source.send_message("The game loop isn't running");
return;
}
const { tps, mspt, skipped } = this.loop.stats;
context.source.send_message(
`${tps} ticks per second (aiming for ${TICKS_PER_SECOND}), ${mspt.toFixed(1)} ms per tick, ` +
`${skipped} skipped since starting`,
);
}),
);
// every command's usage, or one's. aliases like /mod:name aren't listed twice
const commands = this.mods.commands;
const help = (context: CommandContext<ServerCommandSource>, only?: string) => {
const nodes = commands.root.children.filter((node) =>
!node.name.includes(":") && (!only || node.name === only)
);
if (nodes.length === 0) throw new CommandError(`There's no command /${only}`);
for (const node of nodes) {
const usage = `/${commands.usage(node, context.source)}`;
context.source.send_message(node.description ? `${usage} - ${node.description}` : usage);
}
};
register(
literal<ServerCommandSource>("help")
.describe("Lists commands")
.executes((context) => help(context))
.then(
argument<string, ServerCommandSource>("command", word())
.suggests((partial) =>
commands.root.children
.filter((node) => !node.name.includes(":") && node.name.startsWith(partial))
.map((node) => ({ text: node.name }))
)
.executes((context) => help(context, context.get<string>("command"))),
),
);
}
#close_screen(player: ServerPlayer) {
+104 -16
View File
@@ -2,11 +2,13 @@
// see "Server scripts" in MODS.md. parts not built yet throw when used, saying so
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
import { Container as EngineContainer, ItemStack as EngineItemStack } from "$/common/inventory.ts";
import { get_state_value, set_state_value } from "$/common/utils.ts";
import { display_name, get_state_value, set_state_value } from "$/common/utils.ts";
import type {
BlockComponent,
BlockRef,
Command,
CommandRegistry,
CommandSource,
Container,
ContainerScreenOptions,
EventSignal,
@@ -19,6 +21,21 @@ import type {
ServerContext,
} from "$/common/mod_api/server.ts";
import { ModLoadError } from "$/common/mod_loader.ts";
import {
argument,
block as block_argument,
boolean,
choice,
CommandDispatcher,
CommandError,
CommandNode,
greedy_string,
integer,
item,
literal,
number,
word,
} from "$/common/commands.ts";
import { AIR_ID } from "$/common/protocol.ts";
import type { GameServer } from "./game_server.ts";
import type { OpenScreen, ServerPlayer } from "./player.ts";
@@ -83,7 +100,10 @@ interface Timer {
export class ModRuntime {
block_components = new Map<string, { mod: string; component: BlockComponent }>();
item_components = new Map<string, { mod: string; component: ItemComponent }>();
commands = new Map<string, { mod: string; name: string; command: Command }>();
// every command, the engine's and mods', see common/commands.ts
commands = new CommandDispatcher<ServerCommandSource>();
// who registered each command name: "engine" or a mod's id
command_owners = new Map<string, string>();
before: Before = {
block_break: new Signal(),
@@ -192,6 +212,32 @@ export class ModRuntime {
}
}
// adds a command, and for mods the same command as /mod:name so it can always be told apart
register_command(owner: string, node: CommandNode<ServerCommandSource>) {
if (!/^[a-z0-9_]+$/.test(node.name)) {
throw new Error(`command name "${node.name}" must be a-z, 0-9 and _`);
}
const existing = this.command_owners.get(node.name);
if (existing) {
throw new Error(
existing === "engine"
? `/${node.name} belongs to the engine`
: `/${node.name} is also registered by ${existing}`,
);
}
this.commands.register(node);
this.command_owners.set(node.name, owner);
if (owner !== "engine") {
const alias = new CommandNode<ServerCommandSource>(`${owner}:${node.name}`);
alias.children.push(...node.children);
alias.command = node.command;
alias.requirement = node.requirement;
alias.description = node.description;
this.commands.root.then(alias);
this.command_owners.set(alias.name, owner);
}
}
// components on a block, with their params from its json
components_of(block_id: string): { mod: string; id: string; component: BlockComponent; params: unknown }[] {
const block = EverythingRegistry.get<{ components?: Record<string, unknown> }>("blocks", block_id);
@@ -309,23 +355,39 @@ export class ModRuntime {
},
},
commands: {
register: (name, command) => {
register: (name_or_node: string | CommandNode<CommandSource>, command?: Command) => {
setup_only("commands");
if (!/^[a-z0-9_]+$/.test(name)) {
throw new ModLoadError(mod, `command name "${name}" must be a-z, 0-9 and _`);
const node = typeof name_or_node === "string"
? simple_command(name_or_node, command!)
: name_or_node as unknown as CommandNode<ServerCommandSource>;
try {
this.register_command(mod, node as CommandNode<ServerCommandSource>);
} catch (e) {
throw new ModLoadError(mod, (e as Error).message);
}
if (["give", "tps", "time"].includes(name)) {
throw new ModLoadError(mod, `/${name} belongs to the engine`);
}
const existing = this.commands.get(name);
if (existing) {
throw new ModLoadError(mod, `/${name} is also registered by ${existing.mod}`);
}
const entry = { mod, name, command };
this.commands.set(name, entry);
this.commands.set(`${mod}:${name}`, entry);
},
},
literal: (name) => literal<CommandSource>(name),
argument: (name, type) => argument(name, type),
types: {
integer,
number,
boolean,
word,
greedy_string,
choice,
item: () => item_argument(),
block: () => block_argument(display_name_of_block),
player: () => ({
parse: (text: string) => {
const found = game().players().find((p) => p.name === text);
if (!found) throw new CommandError(`${text} isn't online`);
return this.player(found);
},
suggest: (partial: string) =>
game().players().filter((p) => p.name.startsWith(partial)).map((p) => ({ text: p.name })),
}),
},
} as CommandRegistry,
events: {
before: map_signals(this.before, mod),
after: map_signals(this.after, mod),
@@ -587,6 +649,32 @@ function not_yet_object<T>(mod: string, name: string, where: string): T {
const MAX_CONTAINER_SIZE = 256;
// who ran a command, as the engine sees it: what mods see plus the engine's player
export interface ServerCommandSource extends CommandSource {
server_player: ServerPlayer;
}
// register(name, { run }): the words after the name go to run, split on spaces
function simple_command(name: string, command: Command): CommandNode<ServerCommandSource> {
const run = (args: string[], source: ServerCommandSource) => command.run(args, source.player);
return literal<ServerCommandSource>(name)
.describe(command.description)
.executes((context) => run([], context.source))
.then(
argument<string, ServerCommandSource>("args", greedy_string()).executes((context) =>
run(context.get<string>("args").split(/\s+/).filter((word) => word.length > 0), context.source)
),
);
}
export function item_argument() {
return item((id) => display_name(id));
}
function display_name_of_block(id: string) {
return display_name(id);
}
// the engine's item stacks as mods see them: { id, count, data }
export function item_api(stack: EngineItemStack): ItemStack {
return {
+162
View File
@@ -0,0 +1,162 @@
import { assert, assertEquals, assertThrows } from "@std/assert";
import {
argument,
boolean,
choice,
CommandDispatcher,
CommandError,
greedy_string,
integer,
literal,
word,
} from "$/common/commands.ts";
import { test_game } from "./helpers.ts";
interface Source {
admin: boolean;
said: string[];
}
function dispatcher() {
const commands = new CommandDispatcher<Source>();
commands.register(
literal<Source>("add").then(
argument<number, Source>("a", integer()).then(
argument<number, Source>("b", integer(0, 10))
.executes((c) => c.source.said.push(`${c.get<number>("a") + c.get<number>("b")}`)),
),
),
);
commands.register(
literal<Source>("say")
.executes((c) => c.source.said.push("..."))
.then(argument<string, Source>("text", greedy_string()).executes((c) => c.source.said.push(c.get("text")))),
);
commands.register(
literal<Source>("mode")
.then(literal<Source>("all").executes((c) => c.source.said.push("literal all")))
.then(argument<string, Source>("name", word()).executes((c) => c.source.said.push(`word ${c.get("name")}`)))
.then(
literal<Source>("flag").then(
argument<boolean, Source>("on", boolean()).executes((c) =>
c.source.said.push(`flag ${c.get("on")}`)
),
),
),
);
commands.register(
literal<Source>("secret").requires((s) => s.admin).executes((c) => c.source.said.push("secret")),
);
commands.register(
literal<Source>("color").then(
argument<string, Source>("color", choice(["red", "green", "blue"]))
.suggests((partial) => [{ text: `${partial}!`, tooltip: "custom" }])
.executes((c) => c.source.said.push(c.get("color"))),
),
);
return commands;
}
const run = (input: string, admin = false) => {
const source = { admin, said: [] as string[] };
dispatcher().execute(input, source);
return source.said;
};
const error = (input: string, admin = false) => assertThrows(() => run(input, admin), CommandError).message;
const suggest = (input: string, admin = false) => {
const { start, suggestions } = dispatcher().suggest(input, { admin, said: [] });
return { start, texts: suggestions.map((s) => s.text) };
};
Deno.test("commands run down the tree with typed arguments, words winning over arguments", () => {
assertEquals(run("add 2 3"), ["5"]);
assertEquals(run("add -2 3"), ["1"]);
assertEquals(run("say"), ["..."]);
assertEquals(run("say hello there, you"), ["hello there, you"]);
assertEquals(run("mode all"), ["literal all"]);
assertEquals(run("mode alls"), ["word alls"]);
assertEquals(run("mode flag true"), ["flag true"]);
assertEquals(run("secret", true), ["secret"]);
});
Deno.test("what went wrong is from the furthest the command got", () => {
assertEquals(error("nope"), "Unknown command /nope");
assertEquals(error(""), "Unknown command /");
assertEquals(error("add 2"), "Not enough: /add <a> <b>");
assertEquals(error("add 2 11"), "11 is too big, the most is 10");
assertEquals(error("add x 1"), `"x" isn't a whole number`);
assertEquals(error("add 1 2 3"), `Didn't expect "3": /add <a> <b>`);
assertEquals(error("mode flag maybe"), `"maybe" isn't true or false`);
assertEquals(error("color pink"), `"pink" isn't one of red, green, blue`);
// not allowed is the same as not there
assertEquals(error("secret"), "Unknown command /secret");
});
Deno.test("usage reads like brigadier's smart usage", () => {
const commands = dispatcher();
const source = { admin: false, said: [] };
assertEquals(commands.usage(commands.get("add")!, source), "add <a> <b>");
assertEquals(commands.usage(commands.get("say")!, source), "say [<text>]");
assertEquals(commands.usage(commands.get("mode")!, source), "mode (all|flag|<name>)");
assertThrows(() => commands.register(literal<Source>("add")), Error, "/add already exists");
});
Deno.test("suggestions are for the word being typed, from words, types and providers", () => {
assertEquals(suggest(""), { start: 0, texts: ["add", "color", "mode", "say"] });
assertEquals(suggest("", true).texts, ["add", "color", "mode", "say", "secret"]);
assertEquals(suggest("m"), { start: 0, texts: ["mode"] });
assertEquals(suggest("mode "), { start: 5, texts: ["all", "flag"] });
assertEquals(suggest("mode f"), { start: 5, texts: ["flag"] });
assertEquals(suggest("mode flag t"), { start: 10, texts: ["true"] });
assertEquals(suggest("color g").texts, ["g!"]);
// nothing fits after a bad argument, or in a greedy one
assertEquals(suggest("add x ").texts, []);
assertEquals(suggest("say a ").texts, []);
});
Deno.test("/give suggests items as they're typed, with their names", async () => {
const { join, take, send } = await test_game("mods");
join(1, "alice");
take(1);
const suggest = (text: string) => {
send(1, { type: "suggest", id: 3, text });
return take(1).find((m) => m.type === "suggestions");
};
const carrots = suggest("/give car");
assertEquals(carrots.id, 3);
assertEquals(carrots.start, 6);
assert(
carrots.suggestions.some((s: { text: string; tooltip: string }) =>
s.text === "bworld:carrot" && s.tooltip === "Carrot"
),
);
assert(carrots.suggestions.every((s: { text: string }) => s.text.split(":")[1].startsWith("car")));
// every item, but not air
const all = suggest("/give ").suggestions.map((s: { text: string }) => s.text);
assert(all.includes("bworld:stone") && all.includes("farmersdelight:cabbage"), String(all));
assert(!all.includes("bworld:air"));
assertEquals(suggest("/give farmersdelight:tom").suggestions.map((s: { text: string }) => s.text), [
"farmersdelight:tomato",
"farmersdelight:tomato_seeds",
]);
assertEquals(suggest("/gi").suggestions, [{ text: "give" }]);
assertEquals(suggest("/time set ").suggestions.map((s: { text: string }) => s.text), [
"day",
"midnight",
"night",
"noon",
"sunset",
]);
// only commands
assertEquals(suggest("hello"), undefined);
send(1, { type: "chat", text: "/give carrot 2" });
assertEquals(take(1).find((m) => m.type === "chat").text, "Gave 2 Carrot");
send(1, { type: "chat", text: "/give air" });
assertEquals(take(1).find((m) => m.type === "chat").text, "There's no item called air");
send(1, { type: "chat", text: "/give" });
assertEquals(take(1).find((m) => m.type === "chat").text, "Not enough: /give <item> [<count>]");
});
+60
View File
@@ -73,6 +73,25 @@ export function setup(ctx: ServerContext) {
}
},
});
// fabric's way
const { literal, argument, types } = ctx.commands;
ctx.commands.register(
literal("shout")
.describe("Says something to someone")
.requires((source) => source.player.name !== "bob")
.then(
argument("who", types.player()).then(
argument("mode", types.choice(["loud", "quiet"])).then(
argument("text", types.greedy_string()).executes((context) => {
const who = context.get<{ name: string }>("who").name;
context.source.send_message(\`\${who} \${context.get("mode")}: \${context.get("text")}\`);
}),
),
),
),
);
ctx.commands.register(literal("boom").executes(() => { throw new Error("kaboom"); }));
}
`;
@@ -254,6 +273,47 @@ Deno.test("/tps reports the loop, and mods can't take engine commands", async ()
Deno.removeSync(clash, { recursive: true });
});
Deno.test("mods build commands fabric's way: typed arguments, suggestions, requirements and aliases", async () => {
const { join, send, take, dir } = await setup();
join(2, "bob");
take(1);
const suggest = (id: number, text: string) => {
send(id, { type: "suggest", id: 7, text });
return take(id).find((m) => m.type === "suggestions");
};
send(1, { type: "chat", text: "/shout bob loud hi there" });
assertEquals(take(1).at(-1).text, "bob loud: hi there");
send(1, { type: "chat", text: "/testmod:shout alice quiet hey" });
assertEquals(take(1).at(-1).text, "alice quiet: hey");
send(1, { type: "chat", text: "/shout nobody loud hi" });
assertEquals(take(1).at(-1).text, "nobody isn't online");
send(1, { type: "chat", text: "/shout bob" });
assertEquals(take(1).at(-1).text, "Not enough: /shout <who> <mode> <text>");
assertEquals(suggest(1, "/shout b"), { type: "suggestions", id: 7, start: 7, suggestions: [{ text: "bob" }] });
assertEquals(suggest(1, "/shout bob ").suggestions.map((s: { text: string }) => s.text), ["loud", "quiet"]);
assertEquals(suggest(1, "/sh").suggestions.map((s: { text: string }) => s.text), ["shout"]);
// bob can't, so it isn't suggested to him either
assertEquals(suggest(2, "/sh").suggestions, []);
send(2, { type: "chat", text: "/shout alice loud hi" });
assertEquals(take(2).at(-1).text, "Unknown command /shout");
// a mod's bug isn't the player's fault
const error = console.error;
const logged: unknown[][] = [];
console.error = (...args: unknown[]) => logged.push(args);
send(1, { type: "chat", text: "/boom" });
console.error = error;
assertEquals(take(1).at(-1).text, "Something went wrong running /boom");
assert(String(logged[0]?.[0]).includes("[testmod]"), String(logged[0]));
// /help lists it with its usage
send(1, { type: "chat", text: "/help shout" });
assertEquals(take(1).at(-1).text, "/shout <who> <mode> <text> - Says something to someone");
Deno.removeSync(dir, { recursive: true });
});
Deno.test("container screens: filters, properties, closing, saving, and dropping what's inside", async () => {
const { game, send, take, log, dir } = await setup();
game.set_block(1, 100, 0, "testmod:coal_box");
+1 -1
View File
@@ -49,7 +49,7 @@ Deno.test("the server keeps the time, tells players, saves it, and /time changes
assertEquals(game.world.time, CYCLE_TICKS + 100);
send(1, { type: "chat", text: "/time set nope" });
messages = take(1);
assert(messages.at(-1).text.startsWith("Usage: /time"));
assertEquals(messages.at(-1).text, `"nope" isn't one of day, noon, sunset, night, midnight`);
const loaded = await test_game("mods", game.save());
assertEquals(loaded.game.world.time, CYCLE_TICKS + 100);