62 lines
2.7 KiB
TypeScript
62 lines
2.7 KiB
TypeScript
// the base game's block rules: how blocks are placed and how they change with the blocks beside them. they run on the
|
|
// server and on every client, so players see a fence join or a trapdoor turn the moment they place it
|
|
import type { SharedBlock, SharedContext } from "bworld/shared";
|
|
|
|
export function setup(ctx: SharedContext) {
|
|
register_fence(ctx);
|
|
register_trapdoor(ctx);
|
|
}
|
|
|
|
// the sides a fence connects on, and the face of the block there it connects to
|
|
const FENCE_SIDES = [
|
|
{ state: "north", dx: 0, dz: -1, face: "south" },
|
|
{ state: "east", dx: 1, dz: 0, face: "west" },
|
|
{ state: "south", dx: 0, dz: 1, face: "north" },
|
|
{ state: "west", dx: -1, dz: 0, face: "east" },
|
|
] as const;
|
|
|
|
// a fence joins the fences beside it and the full sides of solid blocks, like minecraft's FenceBlock.connectsTo.
|
|
// "connects_to" is the tag of fences it joins, so wooden fences don't join other kinds. leaves are full blocks but
|
|
// fences don't join them, like minecraft
|
|
function register_fence(ctx: SharedContext) {
|
|
const sides = (x: number, y: number, z: number, params: { connects_to: string }) => {
|
|
const states: Record<string, number> = {};
|
|
for (const side of FENCE_SIDES) {
|
|
const [nx, nz] = [x + side.dx, z + side.dz];
|
|
const id = ctx.world.get_block(nx, y, nz);
|
|
const joins = id !== undefined && (
|
|
ctx.tags.has("blocks", params.connects_to, id) ||
|
|
(!ctx.tags.has("blocks", "bworld:leaves", id) && ctx.world.is_face_sturdy(nx, y, nz, side.face))
|
|
);
|
|
states[side.state] = joins ? 1 : 0;
|
|
}
|
|
return states;
|
|
};
|
|
ctx.components.register_block<{ connects_to: string }>("bworld:fence", {
|
|
state_for_placement: (placement, params) => sides(placement.x, placement.y, placement.z, params),
|
|
on_neighbor_change(block: SharedBlock, params) {
|
|
for (const [state, value] of Object.entries(sides(block.x, block.y, block.z, params))) {
|
|
ctx.world.set_state(block.x, block.y, block.z, state, value);
|
|
}
|
|
},
|
|
});
|
|
}
|
|
|
|
// the facing state's values, the way a block's y turns it
|
|
const FACINGS = ["north", "east", "south", "west"];
|
|
|
|
// placed against the side of a block, a trapdoor hangs from that block, in the half of the side that was clicked.
|
|
// placed on top of a block it lies in the bottom half, and under one in the top half, swinging open away from the
|
|
// player, like minecraft's TrapDoorBlock
|
|
function register_trapdoor(ctx: SharedContext) {
|
|
ctx.components.register_block("bworld:trapdoor", {
|
|
state_for_placement(placement): Record<string, number> {
|
|
if (placement.face !== "top" && placement.face !== "bottom") {
|
|
return { facing: FACINGS.indexOf(placement.face), half: placement.hit[1] > 0.5 ? 1 : 0 };
|
|
}
|
|
// facing already faces the player
|
|
return { half: placement.face === "top" ? 0 : 1 };
|
|
},
|
|
});
|
|
}
|