Player api

This commit is contained in:
2026-10-13 22:59:48 -03:00
parent b34e97e487
commit a10b15a3fd
22 changed files with 581 additions and 89 deletions
+1 -1
View File
@@ -192,7 +192,7 @@ Deno.test("players hear their attack speed for the indicator, and any swing, eve
operation: "add_multiplied_base",
});
ticks(1);
assertEquals(take(1).filter((m) => m.type === "attack_speed").map((m) => m.value), [4 * 1.3]);
assertEquals(take(1).filter((m) => m.type === "attributes").map((m) => m.attack_speed), [4 * 1.3]);
// too far to hit, but the swing still counts, like the client's indicator shows
const far = spawn(0.5, 100, 20.5);
+31 -1
View File
@@ -12,7 +12,7 @@ type Blocks = (x: number, y: number, z: number) => boolean;
// a player on flat ground at y 0, maybe with a ceiling, and the positions it sends. or in a world of its own: what's
// solid and what's water
function setup(ceiling = Infinity, world?: { solid: Blocks; water: Blocks }) {
const sent: { y: number; swimming?: boolean }[] = [];
const sent: { y: number; swimming?: boolean; sneaking?: boolean }[] = [];
const client = {
level: {
collision_shape: world?.solid ?? ((_x: number, y: number) => y < 0 || y >= ceiling),
@@ -123,6 +123,36 @@ Deno.test("walking speeds up until friction evens it out, at minecraft's speeds"
}
});
Deno.test("using an item over time walks at a fifth of the speed, and doesn't sprint", () => {
for (const keys of [["KeyW"], ["KeyW", "ControlLeft"]]) {
const { player } = setup();
run(player, 1, () => false);
player.using_item = true;
for (const key of keys) InputManager.keys_down.add(key);
for (let tick = 0; tick < 40; tick++) player.tick();
const z = player.z;
player.tick();
InputManager.keys_down.clear();
assertAlmostEquals((z - player.z) * 20, 4.317 / 5, 0.01);
assertFalse(player.sprinting);
}
});
Deno.test("holding sneak tells the server right away, flying too", () => {
const { player, sent } = setup();
run(player, 1, () => false);
InputManager.keys_down.add("ShiftLeft");
player.tick();
assertEquals(sent.at(-1)?.sneaking, true);
player.flying = true;
player.tick();
assertFalse(player.sneaking);
assert(player.holding_sneak);
InputManager.keys_down.clear();
player.tick();
assertEquals(sent.at(-1)?.sneaking, undefined);
});
Deno.test("jumping while sprinting is faster, and turning while sprinting is slower", () => {
// average speed over 200 ticks holding w and ctrl, and maybe space, turning this much each tick
const average = (jump: boolean, turn: number) => {
+200
View File
@@ -0,0 +1,200 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// what players do with their hands: sneaking while placing and using, how far they reach, and using an item over time
import { assert, assertEquals } from "@std/assert";
import { ATTRIBUTES } from "$/server/game/entity/attributes.ts";
import { copy_dir, stone_floor, test_game } from "./helpers.ts";
const SERVER_SCRIPT = `
import type { ServerContext } from "bworld/server";
export function setup(ctx: ServerContext) {
const log = (key: string, value: unknown = 1) => {
const all = ctx.storage.get<Record<string, unknown[]>>("log") ?? {};
(all[key] ??= []).push(value);
ctx.storage.set("log", all);
};
ctx.components.register_block("testmod:box", {
on_interact(_block, _params, player) {
log("interact", player.is_sneaking());
return true;
},
});
ctx.components.register_item("testmod:wrench", {
on_use(_item, _params, player, target) {
const { block, face } = target ?? {};
log("wrench", block ? [block.id, block.x, block.y, block.z, face, player.is_sneaking()] : null);
},
});
ctx.components.register_item("testmod:bow", {
on_use(_item, params: { ticks: number }, player) {
player.start_using(params.ticks);
log("start");
},
on_use_tick(_item, _params, _player, ticks) { log("tick", ticks); },
on_release_using(_item, _params, _player, ticks) { log("release", ticks); },
on_finish_using() { log("finish"); },
});
}
`;
// a pillar placed upside down while sneaking, like a block whose placement reads sneaking
const SHARED_SCRIPT = `
import type { SharedContext } from "bworld/shared";
export function setup(ctx: SharedContext) {
ctx.components.register_block("testmod:pillar", {
state_for_placement(placement) { return { flipped: placement.sneaking ? 1 : 0 }; },
});
}
`;
function test_mods() {
const dir = Deno.makeTempDirSync({ prefix: "bworld_actions_" });
copy_dir("mods/bworld", `${dir}/bworld`);
const mod = `${dir}/testmod`;
for (const folder of ["blocks", "items", "scripts"]) Deno.mkdirSync(`${mod}/${folder}`, { recursive: true });
const write = (path: string, json: unknown) => Deno.writeTextFileSync(`${mod}/${path}`, JSON.stringify(json));
write("manifest.json", {
format_version: 1,
id: "testmod",
name: "Test",
version: "1.0.0",
dependencies: [{ id: "bworld", version: "*" }],
scripts: { server: "scripts/server.ts", shared: "scripts/shared.ts" },
});
const block = (id: string, extra: Record<string, unknown>) => ({
format_version: 1,
block: { id, textures: "bworld:stone", mining: { toughness: 1 }, ...extra },
});
write("blocks/box.json", block("testmod:box", { interactive: true, components: { "testmod:box": {} } }));
write(
"blocks/pillar.json",
block("testmod:pillar", {
states: [{ name: "flipped", bits: 1, default: 0 }],
components: { "testmod:pillar": {} },
}),
);
const item = (id: string, components: Record<string, unknown>) => ({
format_version: 1,
item: { id, texture: "bworld:stone", components },
});
write("items/wrench.json", item("testmod:wrench", { "testmod:wrench": {} }));
write("items/bow.json", item("testmod:bow", { "testmod:bow": { ticks: 5 } }));
Deno.writeTextFileSync(`${mod}/scripts/server.ts`, SERVER_SCRIPT);
Deno.writeTextFileSync(`${mod}/scripts/shared.ts`, SHARED_SCRIPT);
return dir;
}
async function setup() {
const dir = test_mods();
const { game, send, take, join } = await test_game(dir);
join(1, "alice");
stone_floor(game);
const move = (sneaking: boolean) =>
send(1, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0, ...(sneaking && { sneaking }) });
move(false);
// gives them one of id and selects its slot, or selects an empty slot without id
const hold = (id?: string) => {
if (id) send(1, { type: "chat", text: `/give ${id}` });
const inventory = take(1).filter((m) => m.container === "inventory").at(-1)?.items ??
game.players()[0].inventory.to_synced_data();
send(1, {
type: "select_slot",
slot: inventory.findIndex((i: { id: string } | null) => (i?.id ?? null) === (id ?? null)),
});
};
const log = () => (game.mods.storage.testmod?.log ?? {}) as Record<string, unknown[]>;
const cleanup = () => Deno.removeSync(dir, { recursive: true });
return { game, send, take, move, hold, log, cleanup };
}
Deno.test("sneaking with an item places it against a block that does something when used, like minecraft", async () => {
const { game, send, move, hold, log, cleanup } = await setup();
game.set_block(1, 99, 1, "testmod:box");
hold("testmod:pillar");
send(1, { type: "use_block", x: 1, y: 99, z: 1, face: "top" });
assertEquals(log()["interact"], [false]);
assertEquals(game.world.get_block_id(1, 100, 1), "bworld:air");
// the box isn't used, and the pillar's placement knows they were sneaking
move(true);
assert(game.mods.player(game.players()[0]).is_sneaking());
send(1, { type: "use_block", x: 1, y: 99, z: 1, face: "top" });
assertEquals(log()["interact"], [false]);
assertEquals(game.world.get_block_id(1, 100, 1), "testmod:pillar");
assertEquals(game.world.get_block_value(1, 100, 1) >>> 16, 1);
// with nothing in hand, sneaking still uses it
hold();
send(1, { type: "use_block", x: 1, y: 99, z: 1, face: "north" });
assertEquals(log()["interact"], [false, true]);
cleanup();
});
Deno.test("an item's on_use says which block it was used on", async () => {
const { send, move, hold, log, cleanup } = await setup();
hold("testmod:wrench");
move(true);
send(1, { type: "use_block", x: 1, y: 99, z: 0, face: "top", hit: [0.5, 1, 0.5] });
send(1, { type: "use_item" });
assertEquals(log()["wrench"], [["bworld:stone", 1, 99, 0, "top", true], null]);
cleanup();
});
Deno.test("an item used over time ticks while use is held, and is let go of or finishes", async () => {
const { game, send, take, hold, log, cleanup } = await setup();
hold("testmod:bow");
const using = () => take(1).filter((m) => m.type === "using_item").map((m) => m.using);
send(1, { type: "use_item" });
game.tick();
game.tick();
assertEquals(using(), [true]);
// clicking again while it's used doesn't use it again
send(1, { type: "use_item" });
send(1, { type: "release_use" });
game.tick();
assertEquals(log()["start"], [1]);
assertEquals(log()["tick"], [1, 2]);
assertEquals(log()["release"], [2]);
assertEquals(using(), [false]);
// held for its whole time, it finishes instead, and letting go after that does nothing
send(1, { type: "use_item" });
for (let i = 0; i < 8; i++) game.tick();
send(1, { type: "release_use" });
assertEquals(log()["tick"], [1, 2, 1, 2, 3, 4, 5]);
assertEquals(log()["finish"], [1]);
assertEquals(log()["release"], [2]);
// switching to another slot stops it without either
send(1, { type: "use_item" });
game.tick();
hold();
game.tick();
send(1, { type: "release_use" });
assertEquals(log()["tick"]?.length, 8);
assertEquals(log()["finish"], [1]);
assertEquals(log()["release"], [2]);
cleanup();
});
Deno.test("how far players reach is an attribute, which their client is sent", async () => {
const { game, send, take, cleanup } = await setup();
const [alice] = game.players();
game.set_block(0, 99, 9, "bworld:stone");
send(1, { type: "break_block", x: 0, y: 99, z: 9 });
assertEquals(game.world.get_block_id(0, 99, 9), "bworld:stone");
alice.attributes.get(ATTRIBUTES.block_interaction_range)!.add_modifier({
id: "extendo",
amount: 3,
operation: "add_value",
});
game.tick();
const sent = take(1).filter((m) => m.type === "attributes").at(-1);
assertEquals([sent.block_interaction_range, sent.entity_interaction_range], [9, 3]);
send(1, { type: "break_block", x: 0, y: 99, z: 9 });
assertEquals(game.world.get_block_id(0, 99, 9), "bworld:air");
cleanup();
});
+2 -2
View File
@@ -84,13 +84,13 @@ function client_of(t: Game) {
return {
// what game_mode does when this client places held against face of x y z, at hit
place(id: string, x: number, y: number, z: number, yaw: number, face: Face, hit: [number, number, number]) {
const value = rules.placement_value(info(id)!, yaw, { x, y, z, face, hit });
const value = rules.placement_value(info(id)!, yaw, { x, y, z, face, hit, sneaking: false });
copy.set(`${x} ${y} ${z}`, [id, value >>> 16]);
rules.notify_neighbors(world.get_block, x, y, z);
},
// what game_mode does when this client right clicks face of x y z, at hit. whether the rules did something
interact(x: number, y: number, z: number, yaw: number, face: Face, hit: [number, number, number]) {
return rules.interact(info(at(x, y, z)![0])!, x, y, z, { face, hit }, yaw);
return rules.interact(info(at(x, y, z)![0])!, x, y, z, { face, hit, sneaking: false }, yaw);
},
break(x: number, y: number, z: number) {
copy.set(`${x} ${y} ${z}`, [AIR_ID, 0]);