From c71584eeea55e22fd8d5e3757aba94e37a09fe5d Mon Sep 17 00:00:00 2001 From: Paula Date: Sun, 11 Oct 2026 14:58:01 -0300 Subject: [PATCH] Hold and valley minigames --- client/gui/gui_mod_screens.ts | 8 + client/gui/gui_screen.ts | 13 +- common/mod_api/client.ts | 5 + docs/modding/gui/index.md | 3 +- docs/modding/inventories/menus.md | 14 +- docs/modding/resources/loot_tables.md | 17 +- mods/bworld/items/cod.json | 4 +- mods/bworld/scripts/client.ts | 96 +++++++++- mods/bworld/scripts/fishing.ts | 253 +++++++++++++++++++++++++- tests/fishing_test.ts | 234 ++++++++++++++++++++++-- 10 files changed, 617 insertions(+), 30 deletions(-) diff --git a/client/gui/gui_mod_screens.ts b/client/gui/gui_mod_screens.ts index 19cdca6..8befa22 100644 --- a/client/gui/gui_mod_screens.ts +++ b/client/gui/gui_mod_screens.ts @@ -75,6 +75,14 @@ export class GuiModMenuScreen extends GuiMenuScreen { if (tick) this.#ticker.run(delta, () => this.#guarded("on_tick", () => tick.call(this.#screen))); } + override get dim_background(): boolean { + return this.#screen.dim_background !== false; + } + + override get inventory_overlays(): boolean { + return this.#screen.inventory_overlays !== false; + } + render_background(g: ModGraphics): void { const render = this.#screen.on_render_background; if (render) this.#guarded("on_render_background", () => render.call(this.#screen, g)); diff --git a/client/gui/gui_screen.ts b/client/gui/gui_screen.ts index 77deac5..06df1e7 100644 --- a/client/gui/gui_screen.ts +++ b/client/gui/gui_screen.ts @@ -78,13 +78,21 @@ export abstract class GuiMenuScreen extends GuiScreen { this.y = Math.floor((canvas.height - this.height * GUI_SCALE) / 2); } + // whether the world behind it is darkened, and mods' inventory overlays show on it + get dim_background(): boolean { + return true; + } + get inventory_overlays(): boolean { + return true; + } + // under the slots, from the screen's top left abstract render_background(g: ModGraphics): void; // over the slots abstract render_labels(g: ModGraphics): void; on_render(): void { - draw_rect(0, 0, canvas.width, canvas.height, [0, 0, 0, 0.8]); + if (this.dim_background) draw_rect(0, 0, canvas.width, canvas.height, [0, 0, 0, 0.8]); const g = this.graphics; g.begin(); g.origin_x = this.x; @@ -95,7 +103,7 @@ export abstract class GuiMenuScreen extends GuiScreen { // mods' overlays go on top and get the mouse first, then the slots get what they left g.origin_x = g.origin_y = 0; - this.#render_overlays(); + if (this.inventory_overlays) this.#render_overlays(); if (g.mouse_blocked()) { this.hovering = undefined; } else { @@ -173,6 +181,7 @@ export abstract class GuiMenuScreen extends GuiScreen { } override on_removed(): void { + if (!this.inventory_overlays) return; for (const entry of [...inventory_overlays]) { try { entry.overlay.on_close?.(); diff --git a/common/mod_api/client.ts b/common/mod_api/client.ts index 937f3dd..d80d75f 100644 --- a/common/mod_api/client.ts +++ b/common/mod_api/client.ts @@ -103,6 +103,11 @@ export interface MenuScreen { on_render_labels?(g: Graphics): void; // 20 times a second, like containerTick on_tick?(): void; + // darkens the world behind it, true when not set. false draws it right over the world, like stardew valley's + // fishing minigame + dim_background?: boolean; + // mods' inventory overlays, like the recipe viewer's item list, show on it. true when not set + inventory_overlays?: boolean; } export type Color = [number, number, number, number]; diff --git a/docs/modding/gui/index.md b/docs/modding/gui/index.md index 925acf6..5d33ca4 100644 --- a/docs/modding/gui/index.md +++ b/docs/modding/gui/index.md @@ -49,7 +49,8 @@ throws is closed, with the error in the console. ## Inventory Overlays An inventory overlay draws on every menu's screen (the player's inventory, chests, furnaces and every mod's menus), over -the screen, like Just Enough Items' item list. `mods/recipe_viewer` is one. +the screen, like Just Enough Items' item list. A menu screen with `inventory_overlays: false` has none, like the base +game's fishing minigame. `mods/recipe_viewer` is one. ```ts import type { ClientContext } from "bworld/client"; diff --git a/docs/modding/inventories/menus.md b/docs/modding/inventories/menus.md index df0176e..8e203c2 100644 --- a/docs/modding/inventories/menus.md +++ b/docs/modding/inventories/menus.md @@ -157,12 +157,14 @@ export function setup(ctx: ClientContext) { The engine puts the screen in the middle of the window, and draws the menu's slots, the item on the cursor and item tooltips. The screen draws everything else with [`Graphics`](../gui/index.md#graphics), from its own top left: -| Field | Meaning | -| ---------------------- | ------------------------------------------------------------------ | -| `width`, `height` | Its size in GUI pixels, like `imageWidth` and `imageHeight`. | -| `on_render_background` | Every frame, under the slots: a panel, textures, progress bars. | -| `on_render_labels` | Every frame, over the slots: the title, labels, buttons. | -| `on_tick` | 20 times a second while it's open, like `containerTick`. Optional. | +| Field | Meaning | +| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------- | +| `width`, `height` | Its size in GUI pixels, like `imageWidth` and `imageHeight`. | +| `on_render_background` | Every frame, under the slots: a panel, textures, progress bars. | +| `on_render_labels` | Every frame, over the slots: the title, labels, buttons. | +| `on_tick` | 20 times a second while it's open, like `containerTick`. Optional. | +| `dim_background` | `false` draws it right over the world, without darkening it. Optional. | +| `inventory_overlays` | `false` keeps [inventory overlays](../gui/index.md#inventory-overlays), like the recipe viewer's item list, off it. Optional. | The menu it gets: diff --git a/docs/modding/resources/loot_tables.md b/docs/modding/resources/loot_tables.md index ce5741b..cf8731a 100644 --- a/docs/modding/resources/loot_tables.md +++ b/docs/modding/resources/loot_tables.md @@ -147,15 +147,20 @@ The fishing table, `bworld:gameplay/fishing`, isn't a file: the base game builds } ``` -| Field | What | -| --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `weight` | How often it's caught against the other fish, 1 when not given. | -| `seasons` | The [seasons](../worldgen/biomes.md#seasons) it's caught in where the hook is, every one when not given. | -| `biomes` | The [biomes](../worldgen/biomes.md#biome-ids) and [biome tags](../worldgen/biomes.md#biome-tags) it's caught in where the hook is, every one when not given. | -| `time` | The hours it's caught at on a 24 hour clock, from `from` up to `to`, like `6.5` for 06:30. When `from` is past `to` it wraps around midnight. All day when not given. | +| Field | What | +| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `weight` | How often it's caught against the other fish, 1 when not given. | +| `seasons` | The [seasons](../worldgen/biomes.md#seasons) it's caught in where the hook is, every one when not given. | +| `biomes` | The [biomes](../worldgen/biomes.md#biome-ids) and [biome tags](../worldgen/biomes.md#biome-tags) it's caught in where the hook is, every one when not given. | +| `time` | The hours it's caught at on a 24 hour clock, from `from` up to `to`, like `6.5` for 06:30. When `from` is past `to` it wraps around midnight. All day when not given. | +| `minigame` | What the player does to land it once it's reeled in, in a screen that holds the fish until they win. Closing it lets the fish get away. Caught right away when not given. The base game's are `"test"`, a Catch button, `"hold"`, a bar that fills while the mouse is held and empties while it isn't: full lands the fish, empty loses it, and `"valley"`, Stardew Valley's, where holding the mouse lifts a bar to keep the fish in it. | +| `difficulty` | How hard its minigame is, 10 when not given. In `"hold"`, the bar empties `1 + difficulty / 100` times as fast as it fills: 1.1 at 10, 2 at 100. In `"valley"`, it's Stardew Valley's fish difficulty: the higher, the more the fish darts around. | When every fish can be ruled out, nothing is caught, so keep one that's always caught. +`/fish` reels in what the table gives where you stand, without casting, and `/fish ` reels in that fish, minigame +and all, for trying them out. + Those become the `bworld:season`, `bworld:biome` and `bworld:time` conditions, which any table can use too: | `condition` | Fields | Holds when | diff --git a/mods/bworld/items/cod.json b/mods/bworld/items/cod.json index cadae9d..00a98a1 100644 --- a/mods/bworld/items/cod.json +++ b/mods/bworld/items/cod.json @@ -11,7 +11,9 @@ "bworld:fish": { "weight": 25, "seasons": ["spring", "summer", "autumn", "winter"], - "biomes": ["#bworld:is_ocean"] + "biomes": ["#bworld:is_ocean"], + "minigame": "valley", + "difficulty": 100 } }, "base_sell_value": 30 diff --git a/mods/bworld/scripts/client.ts b/mods/bworld/scripts/client.ts index 53450f2..7ef0367 100644 --- a/mods/bworld/scripts/client.ts +++ b/mods/bworld/scripts/client.ts @@ -1,5 +1,5 @@ // the screens of the base game's menus, see scripts/server.ts for their slots. in gui pixels, like minecraft's -import type { ClientContext, ClientMenu, Graphics, MenuScreen } from "bworld/client"; +import type { ClientContext, ClientMenu, Graphics, ItemStack, MenuScreen } from "bworld/client"; const WIDTH = 176; // like minecraft's 176x166 container screens @@ -9,6 +9,7 @@ export function setup(ctx: ClientContext) { ctx.ui.register_menu_screen("bworld:storage", chest_screen); ctx.ui.register_menu_screen("bworld:furnace", furnace_screen); ctx.ui.register_menu_screen("bworld:smithing_table", smithing_screen); + ctx.ui.register_menu_screen("bworld:fishing_minigame", fishing_minigame_screen); } // a panel with the menu's title and the inventory's label over its rows, drawing anything else over it @@ -66,3 +67,96 @@ function bar( g.texture(full, x, y + size * (1 - done), size, size * done, [0, 1 - done, 1, done]); } } + +// a fishing minigame's screen, by the minigame's name. see the minigames at the end of scripts/fishing.ts +function fishing_minigame_screen(menu: ClientMenu): MenuScreen { + const { minigame, fish } = menu.open_data as { minigame: string; fish: ItemStack }; + const screen = MINIGAME_SCREENS[minigame]; + if (!screen) throw new Error(`the fishing minigame ${minigame} has no screen`); + return screen(menu, fish); +} + +const MINIGAME_SCREENS: Record MenuScreen> = { + // the fish, and a button in the middle that catches it + test: (menu, fish) => { + const width = 120; + const height = 80; + return { + width, + height, + dim_background: false, + inventory_overlays: false, + on_render_background(g) { + g.panel(0, 0, width, height); + }, + on_render_labels(g) { + g.text(menu.title, 8, 6); + g.item(fish.id, width / 2 - 8, 18); + if (g.button("Catch", width / 2 - 25, height / 2, 50, 18)) { + menu.click_button(0); + } + }, + }; + }, + // "Hold !" and a bar under it, filling while the mouse is held. the server counts, this sends when the mouse is + // pressed (button 1) and let go (button 0) + hold: (menu) => { + const width = 120; + const height = 44; + const send_mouse = mouse_sender(menu); + return { + width, + height, + dim_background: false, + inventory_overlays: false, + on_render_background(g) { + g.panel(0, 0, width, height); + }, + on_render_labels(g) { + send_mouse(g); + const text = "Reel !"; + g.text(text, (width - g.measure_text(text)) / 2, 8); + const done = menu.data.progress / menu.data.max || 0; + g.rect(10, 26, width - 20, 8, [0.15, 0.1, 0.05, 1]); + g.rect(10, 26, (width - 20) * done, 8, [0.3, 0.8, 0.3, 1]); + }, + }; + }, + // stardew valley's: a track with the fish and the green bar the mouse lifts, and how close it is to landing on the + // right. laid out like ports/stardewfishing's screen, in its gui pixels: positions are from the track's bottom + valley: (menu, fish) => { + const width = 38; + const height = 152; + const send_mouse = mouse_sender(menu); + return { + width, + height, + dim_background: false, + inventory_overlays: false, + on_render_background(g) { + g.panel(0, 0, width, height); + g.rect(14, 4, 16, 144, [0.2, 0.35, 0.6, 1]); + }, + on_render_labels(g) { + send_mouse(g); + const { bar, bar_size, points, max_points } = menu.data; + g.rect(14, 4 + 142 - bar - bar_size, 16, bar_size, [0.4, 0.85, 0.3, 0.8]); + g.item(fish.id, 14, 4 + 142 - menu.data.fish - 16); + const done = points / max_points || 0; + g.rect(32, 4, 4, 144, [0.15, 0.1, 0.05, 1]); + g.rect(32, 148 - done * 144, 4, done * 144, [1 - done, done, 0.2, 1]); + }, + }; + }, +}; + +// sends the server button 1 when the mouse is pressed and 0 when it's let go, for minigames you hold the mouse in. +// call it every frame +function mouse_sender(menu: ClientMenu): (g: Graphics) => void { + let holding = false; + return (g) => { + if (g.mouse.down === holding) return; + holding = g.mouse.down; + menu.click_button(holding ? 1 : 0); + }; +} diff --git a/mods/bworld/scripts/fishing.ts b/mods/bworld/scripts/fishing.ts index d66bf8c..bc530d7 100644 --- a/mods/bworld/scripts/fishing.ts +++ b/mods/bworld/scripts/fishing.ts @@ -1,13 +1,15 @@ // 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, Player, Season, ServerContext } from "bworld/server"; +import type { EntityRef, ItemStack, MenuBuilder, Player, Season, ServerContext } from "bworld/server"; import type { Position } from "bworld/shared"; 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, with a screen in client.ts +const MINIGAME_MENU = "bworld:fishing_minigame"; // built from every item with bworld:fish, see register_fishing const FISHING_TABLE = "bworld:gameplay/fishing"; // further than this from the hook, the line snaps @@ -46,6 +48,10 @@ interface FishParams { 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 at the end of this file. 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; } interface Cast { @@ -149,6 +155,12 @@ export function register_fishing(ctx: ServerContext) { 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 }); @@ -157,13 +169,64 @@ export function register_fishing(ctx: ServerContext) { }); ctx.loot.register_table(FISHING_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](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 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("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(FISHING_ROD, { on_use(rod, params, player) { const cast = casts.get(player.id); if (cast) { if (cast.escape_at !== undefined) { const loot = ctx.loot.roll(params.loot_table, { position: cast.position, player, tool: rod }); - for (const item of loot) player.give_item(item.id, item.count, item.data); + for (const item of loot) land(player, item); } stop(player, player.id); return; @@ -217,3 +280,189 @@ export function register_fishing(ctx: ServerContext) { } }); } + +// fishing minigames: what a player does to land a fish whose bworld:fish names one. its menu holds the fish until the +// minigame is won, and each has a screen of the same name in client.ts that presses its buttons + +type MinigameArgs = [menu: MenuBuilder, fish: ItemStack, player: Player, difficulty: number]; + +// a minigame builds its menu with the menu's own on_button, on_tick and add_data, and calls win or lose once it's over +abstract class FishingMinigame { + #over = false; + + constructor( + protected readonly menu: MenuBuilder, + readonly fish: ItemStack, + readonly player: Player, + // the fish's bworld:fish difficulty, 10 when it has none + readonly difficulty: number, + ) { + menu.still_valid(() => !this.#over); + } + + // gives the player the fish and closes it + protected win() { + if (this.#over) return; + this.#over = true; + this.player.give_item(this.fish.id, this.fish.count, this.fish.data); + } + + // the fish gets away, and it closes + protected lose() { + this.#over = true; + } + + // keeps holding up to date with the mouse: the screen presses button 1 when it's pressed and 0 when it's let go + protected holding = false; + protected listen_for_mouse() { + this.menu.on_button((_player, id) => { + if (id === 0 || id === 1) { + this.holding = id === 1; + } + }); + } +} + +// a "Catch" button in the middle of the screen, button 0 +class TestMinigame extends FishingMinigame { + constructor(...args: MinigameArgs) { + super(...args); + this.menu.on_button((_player, id) => { + if (id === 0) this.win(); + }); + } +} + +// "Hold !" and a bar from 0 to 10 seconds, starting half full. while the mouse is held (button 1, and 0 when it's let +// go) it fills a second a second, otherwise it empties faster the harder the fish is: 1 + difficulty / 100 seconds a +// second, 1.1 at 10 and 2 at 100. full lands the fish, empty loses it +const HOLD_MAX = 10 * 20; +class HoldMinigame extends FishingMinigame { + #progress = HOLD_MAX / 2; + + constructor(...args: MinigameArgs) { + super(...args); + this.menu.add_data("progress", () => this.#progress); + this.menu.add_data("max", () => HOLD_MAX); + this.listen_for_mouse(); + this.menu.on_tick(() => { + this.#progress += this.holding ? 1 : -(1 + this.difficulty / 100); + if (this.#progress >= HOLD_MAX) { + this.win(); + } else if (this.#progress <= 0) { + this.lose(); + } + }); + } +} + +// stardew valley's, ported from ports/stardewfishing's FishingMinigame: holding the mouse lifts a green bar up a track +// and letting go drops it, while the fish darts up and down. points go up 1 a tick while the bar is on the fish and +// down 1 while it isn't, starting at a fifth: all of them lands it, none loses it. the bar and points are in the +// port's gui pixels, from the track's bottom +const VALLEY_POINTS = 120; +const VALLEY_UP_ACCELERATION = 0.7; +const VALLEY_GRAVITY = -0.7; +const VALLEY_BAR_SIZE = 36; +const VALLEY_MAX_BAR = 142 - VALLEY_BAR_SIZE; +const VALLEY_MAX_FISH = 127; +// the fish moves like stardew's own BobberBar.update with the "dart" motion type, in its units: a 548 tall track, +// from the top, with the fish kept above 532. stardew runs it 60 times a second, so it runs 3 times a tick +const STARDEW_TRACK = 548; +const STARDEW_MAX_FISH = 532; +const STARDEW_STEPS_PER_TICK = 3; +class ValleyMinigame extends FishingMinigame { + #points = VALLEY_POINTS / 5; + #bar = 0; + #bar_velocity = 0; + // in stardew's units, starting at the bottom + #fish = STARDEW_MAX_FISH; + #fish_speed = 0; + #fish_target = -1; + + constructor(...args: MinigameArgs) { + super(...args); + this.menu.add_data("bar", () => this.#bar); + this.menu.add_data("bar_size", () => VALLEY_BAR_SIZE); + this.menu.add_data("fish", () => this.#fish_height()); + this.menu.add_data("points", () => this.#points); + this.menu.add_data("max_points", () => VALLEY_POINTS); + this.listen_for_mouse(); + this.menu.on_tick(() => this.#tick()); + } + + // the fish in the port's units, from the track's bottom + #fish_height() { + return (STARDEW_MAX_FISH - this.#fish) / STARDEW_MAX_FISH * VALLEY_MAX_FISH; + } + + #tick() { + // the bar: up while held, falling otherwise, bouncing a little off the bottom + if (this.holding) { + if (this.#bar_velocity < 0) this.#bar_velocity *= 0.9; + this.#bar_velocity += VALLEY_UP_ACCELERATION; + } else if (this.#bar > 0) { + this.#bar_velocity += VALLEY_GRAVITY; + } + this.#bar += this.#bar_velocity; + if (this.#bar > VALLEY_MAX_BAR) { + this.#bar_velocity = 0; + this.#bar = VALLEY_MAX_BAR; + } else if (this.#bar <= 0) { + this.#bar = 0; + this.#bar_velocity = this.#bar_velocity < 2 * VALLEY_GRAVITY ? this.#bar_velocity * -0.4 : 0; + } + + for (let i = 0; i < STARDEW_STEPS_PER_TICK; i++) this.#move_fish(); + + // the points + const fish = this.#fish_height(); + const on_fish = fish >= Math.floor(this.#bar) - 2 && fish <= Math.ceil(this.#bar) + VALLEY_BAR_SIZE - 12; + this.#points += on_fish ? 1 : -1; + if (this.#points >= VALLEY_POINTS) this.win(); + else if (this.#points <= 0) this.lose(); + } + + // a step of stardew's fish: the harder it is, the more often it picks somewhere new, the further it goes and the + // faster it gets there. darters also jump a long way now and then, further the harder they are + #move_fish() { + const difficulty = this.difficulty; + if (Math.random() < difficulty / 4000) { + const below = STARDEW_TRACK - this.#fish; + const above = this.#fish; + const percent = Math.min(99, difficulty + random_int(10, 45)) / 100; + this.#fish_target = this.#fish + random_int(Math.min(-above, below), below) * percent; + } + if (Math.abs(this.#fish - this.#fish_target) > 3 && this.#fish_target !== -1) { + const acceleration = (this.#fish_target - this.#fish) / + (random_int(10, 30) + (100 - Math.min(100, difficulty))); + this.#fish_speed += (acceleration - this.#fish_speed) / 5; + } else if (Math.random() < difficulty / 2000) { + this.#fish_target = this.#fish + (Math.random() < 0.5 ? random_int(-100, -51) : random_int(50, 101)); + } else { + this.#fish_target = -1; + } + // darting + if (Math.random() < difficulty / 1000) { + this.#fish_target = this.#fish + + (Math.random() < 0.5 ? random_int(-100 - difficulty * 2, -51) : random_int(50, 101 + difficulty * 2)); + } + this.#fish_target = clamp(this.#fish_target, -1, STARDEW_TRACK); + this.#fish = clamp(this.#fish + this.#fish_speed, 0, STARDEW_MAX_FISH); + } +} + +// from min up to but not including max, like c#'s Random.Next. min when there's nothing between +function random_int(min: number, max: number) { + return max <= min ? min : Math.floor(min + Math.random() * (max - min)); +} + +function clamp(value: number, min: number, max: number) { + return Math.min(Math.max(value, min), max); +} + +const MINIGAMES: Record FishingMinigame> = { + test: TestMinigame, + hold: HoldMinigame, + valley: ValleyMinigame, +}; diff --git a/tests/fishing_test.ts b/tests/fishing_test.ts index ed2b19b..7572253 100644 --- a/tests/fishing_test.ts +++ b/tests/fishing_test.ts @@ -1,12 +1,12 @@ // fishing: throw the hook into water, wait for a bite, reel it in before it gets away -import { assert, assertEquals } from "@std/assert"; +import { assert, assertAlmostEquals, assertEquals } from "@std/assert"; import { EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts"; import { ItemStack } from "$/common/inventory.ts"; import { item_texture } from "$/common/utils.ts"; import { tag_api } from "$/common/tags.ts"; import { CYCLE_TICKS } from "$/common/time.ts"; import { biome_season } from "$/common/worldgen/biomes.ts"; -import { test_game } from "./helpers.ts"; +import { menu_data, opened_menu, test_game } from "./helpers.ts"; // deno-lint-ignore no-explicit-any type Msg = any; @@ -77,15 +77,17 @@ Deno.test("the hook flies forward from the player and floats where it lands in w Deno.test("cast into water, reel in a fish once something bites", async () => { const t = await setup(); - t.cast(); - const floating = t.hooks()[0].y; - assert(t.wait_for_bite()); - assert(t.hooks()[0].y < floating - 0.1, String(t.hooks()[0].y)); - t.reel(); - assertEquals(t.fish().length, 1); - assertEquals(t.rod()?.data, undefined); - t.game.tick(); - assertEquals(t.hooks().length, 0); + await with_minigames(async () => { + t.cast(); + const floating = t.hooks()[0].y; + assert(t.wait_for_bite()); + assert(t.hooks()[0].y < floating - 0.1, String(t.hooks()[0].y)); + t.reel(); + assertEquals(t.fish().length, 1); + assertEquals(t.rod()?.data, undefined); + t.game.tick(); + assertEquals(t.hooks().length, 0); + }, null); }); Deno.test("right clicking a block throws the hook too", async () => { @@ -177,3 +179,213 @@ Deno.test("a fish with biomes is only caught in them, by id or #tag", async () = .has("bworld:salmon"), ); }); + +// every fish plays the minigame until the test is done, or none with null +async function with_minigames(test: () => Promise, minigame: string | null = "test") { + const fishes = EverythingRegistry.entries("items") + .map(([, item]) => item.components?.["bworld:fish"] as { minigame?: string } | undefined) + .filter((fish) => fish !== undefined); + const before = fishes.map((fish) => fish.minigame); + const set = (fish: { minigame?: string }, value: string | undefined) => { + if (value === undefined) delete fish.minigame; + else fish.minigame = value; + }; + fishes.forEach((fish) => set(fish, minigame ?? undefined)); + try { + await test(); + } finally { + fishes.forEach((fish, i) => set(fish, before[i])); + } +} + +Deno.test("a fish with a minigame is caught once it's won, in its menu", async () => { + const t = await setup(); + await with_minigames(async () => { + t.cast(); + assert(t.wait_for_bite()); + t.take(1); + t.reel(); + const opened = opened_menu(t.take(1)); + assertEquals(opened?.menu_type, "bworld:fishing_minigame"); + assertEquals(opened.open_data.minigame, "test"); + assertEquals(t.fish().length, 0); + t.send(1, { type: "menu_button", menu: opened.id, button: 1 }); + assertEquals(t.fish().length, 0); + t.send(1, { type: "menu_button", menu: opened.id, button: 0 }); + assertEquals(t.fish().length, 1); + assertEquals(t.fish()[0]?.id, opened.open_data.fish.id); + t.game.tick(); + assert(t.take(1).some((m: Msg) => m.type === "close_menu")); + // once + t.send(1, { type: "menu_button", menu: opened.id, button: 0 }); + assertEquals(t.fish().length, 1); + }); +}); + +Deno.test("closing a fish's minigame lets it get away", async () => { + const t = await setup(); + await with_minigames(async () => { + t.cast(); + assert(t.wait_for_bite()); + t.take(1); + t.reel(); + const opened = opened_menu(t.take(1)); + t.send(1, { type: "close_menu", menu: opened.id }); + t.send(1, { type: "menu_button", menu: opened.id, button: 0 }); + assertEquals(t.fish().length, 0); + }); +}); + +Deno.test("/fish reels in a fish without casting, its minigame and all", async () => { + const t = await setup(); + await with_minigames(async () => { + t.send(1, { type: "chat", text: "/fish bworld:cod" }); + assertEquals(t.fish().map((i: Msg) => i.id), ["bworld:cod"]); + }, null); + t.send(1, { type: "chat", text: "/fish stone" }); + assertEquals(t.fish().length, 1); + assert(t.take(1).some((m: Msg) => JSON.stringify(m).includes("bworld:stone isn't a fish"))); + await with_minigames(async () => { + t.send(1, { type: "chat", text: "/fish salmon" }); + const opened = opened_menu(t.take(1)); + assertEquals(opened?.menu_type, "bworld:fishing_minigame"); + assertEquals(opened.open_data.fish, { id: "bworld:salmon", count: 1 }); + t.send(1, { type: "menu_button", menu: opened.id, button: 0 }); + assertEquals(t.fish().map((i: Msg) => i.id).sort(), ["bworld:cod", "bworld:salmon"]); + }); +}); + +// cod's bworld:fish difficulty until the test is done, or none with undefined +async function with_difficulty(difficulty: number | undefined, test: () => Promise) { + const fish = EverythingRegistry.get("items", "bworld:cod")!.components!["bworld:fish"] as { + difficulty?: number; + }; + const before = fish.difficulty; + if (difficulty === undefined) delete fish.difficulty; + else fish.difficulty = difficulty; + try { + await test(); + } finally { + if (before === undefined) delete fish.difficulty; + else fish.difficulty = before; + } +} + +Deno.test("the hold minigame fills while the mouse is held and empties by the fish's difficulty, landing it when full", async () => { + const t = await setup(); + const progress = () => menu_data(t.take(1))?.progress; + await with_minigames(() => + with_difficulty(100, async () => { + t.send(1, { type: "chat", text: "/fish cod" }); + const opened = opened_menu(t.take(1)); + assertEquals(opened.data, { progress: 100, max: 200 }); + assertEquals(opened.open_data.difficulty, 100); + t.send(1, { type: "menu_button", menu: opened.id, button: 1 }); + for (let i = 0; i < 50; i++) t.game.tick(); + assertEquals(progress(), 150); + // let go for a bit: at 100 it empties twice as fast as it fills + t.send(1, { type: "menu_button", menu: opened.id, button: 0 }); + for (let i = 0; i < 10; i++) t.game.tick(); + assertEquals(progress(), 130); + t.send(1, { type: "menu_button", menu: opened.id, button: 1 }); + for (let i = 0; i < 69; i++) t.game.tick(); + assertEquals(t.fish().length, 0); + t.game.tick(); + assertEquals(t.fish().map((i: Msg) => i.id), ["bworld:cod"]); + t.game.tick(); + assert(t.take(1).some((m: Msg) => m.type === "close_menu")); + }), "hold"); +}); + +Deno.test("the hold minigame empties 1.1 seconds a second at the default difficulty, losing the fish when empty", async () => { + const t = await setup(); + await with_minigames(() => + with_difficulty(undefined, async () => { + t.send(1, { type: "chat", text: "/fish cod" }); + const opened = opened_menu(t.take(1)); + assertEquals(opened.open_data.difficulty, 10); + for (let i = 0; i < 10; i++) t.game.tick(); + assertAlmostEquals(menu_data(t.take(1))?.progress, 89); + // 100 / 1.1 is 90.9 ticks + for (let i = 0; i < 80; i++) t.game.tick(); + assert(!t.take(1).some((m: Msg) => m.type === "close_menu")); + for (let i = 0; i < 2; i++) t.game.tick(); + assert(t.take(1).some((m: Msg) => m.type === "close_menu")); + t.send(1, { type: "menu_button", menu: opened.id, button: 1 }); + for (let i = 0; i < 200; i++) t.game.tick(); + assertEquals(t.fish().length, 0); + }), "hold"); +}); + +// with Math.random at 0.99, the valley minigame's fish never moves, staying at the bottom +async function with_still_fish(test: () => Promise) { + const random = Math.random; + Math.random = () => 0.99; + try { + await test(); + } finally { + Math.random = random; + } +} + +Deno.test("the valley minigame loses the fish while the bar is off it", async () => { + const t = await setup(); + await with_minigames(() => + with_still_fish(async () => { + t.send(1, { type: "chat", text: "/fish cod" }); + const opened = opened_menu(t.take(1)); + assertEquals(opened.data, { bar: 0, bar_size: 36, fish: 0, points: 24, max_points: 120 }); + // the bar goes up to the top, away from the fish + t.send(1, { type: "menu_button", menu: opened.id, button: 1 }); + let closed = false; + for (let i = 0; i < 200 && !closed; i++) { + t.game.tick(); + closed = t.take(1).some((m: Msg) => m.type === "close_menu"); + } + assert(closed); + assertEquals(t.fish().length, 0); + }), "valley"); +}); + +Deno.test("the valley minigame lands the fish when the bar stays on it", async () => { + const t = await setup(); + await with_minigames(() => + with_still_fish(async () => { + t.send(1, { type: "chat", text: "/fish cod" }); + // the bar stays at the bottom with the fish. 96 points to go, one a tick + for (let i = 0; i < 95; i++) t.game.tick(); + assertEquals(t.fish().length, 0); + t.game.tick(); + assertEquals(t.fish().map((i: Msg) => i.id), ["bworld:cod"]); + }), "valley"); +}); + +Deno.test("harder valley fish move around more", async () => { + const t = await setup(); + // how far the fish moves a tick on average at a difficulty, over a few minigames of up to 10 seconds + const speed = async (difficulty: number) => { + let moved = 0; + let ticks = 0; + await with_difficulty(difficulty, async () => { + for (let game = 0; game < 5; game++) { + t.send(1, { type: "chat", text: "/fish cod" }); + let fish = opened_menu(t.take(1)).data.fish; + for (let i = 0; i < 200; i++) { + t.game.tick(); + const messages = t.take(1); + const now = menu_data(messages)?.fish ?? fish; + moved += Math.abs(now - fish); + fish = now; + ticks++; + if (messages.some((m: Msg) => m.type === "close_menu")) break; + } + } + }); + return moved / ticks; + }; + await with_minigames(async () => { + const easy = await speed(5); + const hard = await speed(100); + assert(hard > easy * 2, `${hard} isn't much more than ${easy}`); + }, "valley"); +});