Files
bworld/mods/bworld/scripts/fishing.ts
T
2026-11-04 21:51:26 -03:00

317 lines
13 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// fishing, like minecraft's: right click with a rod to throw its hook forward. when it lands in a block with
// bworld:fishable, like water, it floats there until something bites, and right clicking again before it gets away
// reels it in. a hook that lands on anything else lies there until it's reeled in, with nothing on it
import type { EntityRef, ItemStack, Player, Season, ServerContext } from "cubi/server";
import type { Position } from "cubi/shared";
import { MINIGAMES } from "./minigames/mod.ts";
const FISHING_ROD = "bworld:fishing_rod";
const FISHING_HOOK = "bworld:fishing_hook";
const FISHABLE = "bworld:fishable";
const FISH = "bworld:fish";
// the menu a fish's minigame is played in. client.ts gives it the minigame's screen, see minigames/mod.ts
const MINIGAME_MENU = "bworld:fishing_minigame";
// what's caught in a fishable block whose bworld:fishable doesn't name a table, like water. each table is built from
// the items with bworld:fish that live in its fluid, see register_fishing
const FISHING_TABLE = "bworld:gameplay/fishing";
// the fluid a fish lives in when it doesn't say
const WATER = "bworld:water";
// further than this from the hook, the line snaps
const LINE_LENGTH = 16;
// blocks per tick it's thrown at, and how it falls and slows down in the air each tick, like minecraft's hook
const THROW_SPEED = 1;
const GRAVITY = 0.03;
const DRAG = 0.92;
// it's reeled in if it's still flying after this many ticks
const MAX_FLIGHT = 100;
// half the hook's 0.25 block box: the hook's middle flies along the line, its feet are this much under it
const HOOK_HALF = 0.125;
// the hook's feet under the water's surface, so its red stripe floats right on it (the hook's sprite is 16 pixels
// around the middle of its 0.25 block box, the stripe is 1.5 pixels above that)
const HOOK_DEPTH = 0.125 + 1.5 / 16;
// how far it bobs up and down, and how far under it goes with a bite
const HOOK_BOB = 0.03;
const HOOK_DIP = 0.15;
interface FishingRodParams {
// ticks until something bites, the shortest and longest, like minecraft's 5 to 30 seconds
wait: [number, number];
// ticks it stays on the hook before it gets away
bite: [number, number];
}
// a block the hook floats on, like water and lava
interface FishableParams {
// what's caught in it, FISHING_TABLE when not given. bworld:season, bworld:time and bworld:biome pick fish by where
// and when it's reeled in
loot_table?: string;
}
// an item that's caught by fishing
interface FishParams {
// how often it's caught against the other fish, 1 when not given
weight?: number;
// the seasons it's caught in, every one when not given
seasons?: Season[];
// the hours it's caught at, like bworld:time's, all day when not given
time?: { from: number; to: number };
// the biomes and #biome tags it's caught in, every one when not given
biomes?: string[];
// the minigame that lands it, one of MINIGAMES in minigames/mod.ts. caught right away when not given
minigame?: string;
// how hard its minigame is, 10 when not given. what it changes is up to the minigame
difficulty?: number;
// the fishable block it's caught in, bworld:water when not given. it's in that block's loot table
fluid?: string;
}
interface Cast {
// the hotbar slot the rod is in, switching away reels it in
slot: number;
params: FishingRodParams;
hook: EntityRef;
// the hook's middle
position: Position;
// blocks per tick while it's flying, undefined once it has landed
velocity?: Position;
thrown_at: number;
// the fishable block it floats on, once it lands in one. the line comes out when it's gone
water?: { x: number; y: number; z: number; block: string };
// ticks, when something bites and when it gets away
bite_at?: number;
escape_at?: number;
}
export function register_fishing(ctx: ServerContext) {
// by player id
const casts = new Map<string, Cast>();
const between = ([min, max]: [number, number]) => min + Math.floor(Math.random() * (max - min + 1));
const fishable = new Map<string, boolean>();
const is_fishable = (id: string) => {
let result = fishable.get(id);
if (result === undefined) fishable.set(id, result = FISHABLE in ctx.blocks.components(id));
return result;
};
// takes the line in, the rod in the slot looks uncast again
const stop = (player: Player | undefined, id: string) => {
const cast = casts.get(id);
casts.delete(id);
cast?.hook.remove();
const rod = cast && player?.inventory.get(cast.slot);
if (rod?.id === FISHING_ROD) rod.data = undefined;
};
// moves the hook along its flight for a tick, until it hits something
const fly = (cast: Cast, velocity: Position, now: number) => {
const from = cast.position;
const to = { x: from.x + velocity.x, y: from.y + velocity.y, z: from.z + velocity.z };
const hit = ctx.world.raycast(from, to, { fluids: "any" });
if (!hit) {
cast.position = to;
velocity.x *= DRAG;
velocity.y = velocity.y * DRAG - GRAVITY;
velocity.z *= DRAG;
cast.hook.teleport(to.x, to.y - HOOK_HALF, to.z);
return;
}
cast.velocity = undefined;
cast.position = { ...hit.position };
if (is_fishable(hit.id)) {
// it floats on top, even when it went in by a side under the surface
let y = hit.y;
while (ctx.world.get_block(hit.x, y + 1, hit.z) === hit.id) y++;
cast.water = { x: hit.x, y, z: hit.z, block: hit.id };
cast.position.y = y + 1;
cast.bite_at = now + between(cast.params.wait);
} else {
cast.hook.teleport(hit.position.x, hit.position.y - HOOK_HALF, hit.position.z);
}
};
// fishable blocks are found by their components, see is_fishable
ctx.components.register_block<FishableParams>(FISHABLE, {});
// what's caught in a fishable block
const table_of = (block: string) =>
(ctx.blocks.components(block)[FISHABLE] as FishableParams | undefined)?.loot_table ?? FISHING_TABLE;
// "seasons": ["summer", "autumn"], holds in any of them, at the loot's position. without a position, like a
// table rolled from a command, it holds
ctx.loot.register_condition("bworld:season", (params, context) => {
const seasons = params.seasons as string[];
if (!context.position) return true;
return seasons.includes(ctx.world.season_at(context.position.x, context.position.z));
});
// "biomes": ["bworld:swamp", "#bworld:is_ocean"], holds in any of the biomes or biome tags at the loot's
// position. without a position it holds, like bworld:season
ctx.loot.register_condition("bworld:biome", (params, context) => {
if (!context.position) return true;
const biome = ctx.world.biome_at(context.position.x, context.position.z);
return (params.biomes as string[]).some((entry) =>
entry.startsWith("#") ? ctx.tags.has("biomes", entry, biome) : entry === biome
);
});
// "from": 20, "to": 4, hours on a 24 hour clock, from inclusive and to exclusive. from past to wraps around
// midnight, and fractions are minutes, like 6.5 for 06:30
ctx.loot.register_condition("bworld:time", (params) => {
const from = params.from as number;
const to = params.to as number;
const hour = ctx.world.hour;
return from <= to ? hour >= from && hour < to : hour >= from || hour < to;
});
// every item with bworld:fish is in its fluid's fishing table, caught in its seasons, at its hours and in its
// biomes
ctx.components.register_item<FishParams>(FISH, {});
const tables = new Map<string, { item: string; weight: number; conditions: { condition: string }[] }[]>([
[FISHING_TABLE, []],
]);
const entries = ctx.items.ids().flatMap((id) => {
const fish = ctx.items.components(id)[FISH] as FishParams | undefined;
if (!fish) return [];
if (fish.difficulty !== undefined && !(typeof fish.difficulty === "number" && fish.difficulty >= 0)) {
throw new Error(`${id}'s fishing difficulty must be a number, 0 or more`);
}
if (fish.minigame !== undefined && !(fish.minigame in MINIGAMES)) {
throw new Error(`${id}'s fishing minigame ${fish.minigame} doesn't exist`);
}
const conditions = [];
if (fish.seasons) conditions.push({ condition: "bworld:season", seasons: fish.seasons });
if (fish.time) conditions.push({ condition: "bworld:time", ...fish.time });
if (fish.biomes) conditions.push({ condition: "bworld:biome", biomes: fish.biomes });
const fluid = fish.fluid ?? WATER;
if (!ctx.blocks.exists(fluid) || !(FISHABLE in ctx.blocks.components(fluid))) {
throw new Error(`${id} is caught in ${fluid}, which isn't a block with ${FISHABLE}`);
}
const entry = { item: id, weight: fish.weight ?? 1, conditions };
const table = table_of(fluid);
tables.set(table, [...tables.get(table) ?? [], entry]);
return [entry];
});
for (const [table, entries] of tables) {
ctx.loot.register_table(table, { pools: entries.length > 0 ? [{ entries }] : [] });
}
// holds the fish until its minigame is won, and closes then. closing it before lets the fish get away
const minigame_menu = ctx.menus.register<{ minigame: string; fish: ItemStack; difficulty: number }>(
MINIGAME_MENU,
(menu, { minigame, fish, difficulty }, player) => {
menu.title = "Reel it in!";
menu.open_data = { minigame, fish, difficulty };
new MINIGAMES[minigame].minigame(menu, fish, player, difficulty);
},
);
// what's reeled in: a fish with a minigame opens it, anything else is given right away
const land = (player: Player, item: ItemStack) => {
const fish = ctx.items.components(item.id)[FISH] as FishParams | undefined;
if (fish?.minigame) {
minigame_menu.open(player, { minigame: fish.minigame, fish: item, difficulty: fish.difficulty ?? 10 });
} else {
player.give_item(item.id, item.count, item.data);
}
};
// /fish reels in what the fishing table gives where you stand, /fish <fish> reels in that fish, its minigame and
// all, for trying minigames out
const fishes = entries.map((entry) => entry.item);
const { literal, argument, types } = ctx.commands;
ctx.commands.register(
literal("fish")
.describe("Reels in a fish, like a bite on your rod")
.executes(({ source }) => {
const { player } = source;
for (const item of ctx.loot.roll(FISHING_TABLE, { position: player.position, player })) {
land(player, item);
}
})
.then(
argument("fish", types.item())
.suggests((partial) =>
fishes
.filter((id) => id.startsWith(partial) || id.split(":")[1].startsWith(partial))
.map((id) => ({ text: id }))
)
.executes((context) => {
const id = context.get<string>("fish");
if (!fishes.includes(id)) {
context.source.send_message(`${id} isn't a fish`);
return;
}
land(context.source.player, { id, count: 1 });
}),
),
);
ctx.components.register_item<FishingRodParams>(FISHING_ROD, {
on_use(rod, params, player) {
const cast = casts.get(player.id);
if (cast) {
if (cast.escape_at !== undefined) {
// a table no fish lives in isn't made, and nothing's caught there
const table = table_of(cast.water!.block);
const loot = ctx.loot.exists(table)
? ctx.loot.roll(table, { position: cast.position, player, tool: rod })
: [];
for (const item of loot) land(player, item);
}
stop(player, player.id);
return;
}
const eye = player.eye_position;
const look = player.look_direction;
const position = { x: eye.x + look.x * 0.5, y: eye.y + look.y * 0.5, z: eye.z + look.z * 0.5 };
casts.set(player.id, {
slot: player.selected_slot,
params,
hook: ctx.world.spawn_entity(FISHING_HOOK, position.x, position.y - HOOK_HALF, position.z),
position,
velocity: { x: look.x * THROW_SPEED, y: look.y * THROW_SPEED, z: look.z * THROW_SPEED },
thrown_at: ctx.system.current_tick,
});
rod.data = { cast: true };
},
});
ctx.events.after.tick.subscribe(() => {
const now = ctx.system.current_tick;
for (const [id, cast] of casts) {
const player = ctx.players.get(id);
const { x, y, z } = player?.position ?? cast.position;
const distance = Math.hypot(x - cast.position.x, y - cast.position.y, z - cast.position.z);
const water = cast.water;
if (
!player || player.selected_slot !== cast.slot || player.held_item?.id !== FISHING_ROD ||
distance > LINE_LENGTH || cast.hook.removed ||
(water && ctx.world.get_block(water.x, water.y, water.z) !== water.block) ||
(cast.velocity && (now - cast.thrown_at > MAX_FLIGHT || cast.position.y < 0))
) {
stop(player, id);
continue;
}
if (cast.velocity) {
fly(cast, cast.velocity, now);
}
if (!cast.water || cast.bite_at === undefined) {
continue;
}
if (cast.escape_at === undefined && now >= cast.bite_at) {
cast.escape_at = now + between(cast.params.bite);
} else if (cast.escape_at !== undefined && now >= cast.escape_at) {
// it got away, wait for another
cast.escape_at = undefined;
cast.bite_at = now + between(cast.params.wait);
}
const bob = cast.escape_at === undefined ? Math.sin(now / 40 * Math.PI * 2) * HOOK_BOB : -HOOK_DIP;
cast.hook.teleport(cast.position.x, cast.position.y - HOOK_DEPTH + bob, cast.position.z);
}
});
}