Health and hunger system
This commit is contained in:
@@ -364,6 +364,7 @@ block is lit evenly with the block's own light.
|
||||
| `tool` | none | `tool_type` | Tool type used by blocks' `mining.tool`. |
|
||||
| `places` | none | `block_id` | Block placed when used on a block face. |
|
||||
| `max_stack` | `64` | new | Largest stack size. |
|
||||
| `food` | none | `food` | Makes it edible: `{ "nutrition": 3, "saturation_modifier": 0.6 }`, with Minecraft's meanings (hunger points out of 20, and saturation of nutrition × modifier × 2). Optional `always_edible` (eaten even when full) and `returns` (an item left in the hand, like a bowl). Players eat it by right clicking while hungry. |
|
||||
| `lore` | none | `lore` | Tooltip text under the name. `\n` starts a new line. |
|
||||
| `components` | none | `on_create` / `get_lore` | Custom item components, handled by server scripts. |
|
||||
|
||||
@@ -645,6 +646,8 @@ events** fire once it has happened.
|
||||
| `block_place` | ✓ | ✓ | `player`, `block`, `face`, `item` |
|
||||
| `block_interact` | ✓ | ✓ | `player`, `block`, `item` |
|
||||
| `chat_send` | ✓ | ✓ | `player`, `message` (before events can change `message`) |
|
||||
| `player_damage` | ✓ | | `player`, `amount`, `cause` (before events can change `amount`) |
|
||||
| `player_death` | | ✓ | `player`, `cause`. They've dropped what they carried and respawn right after |
|
||||
| `player_join` | | ✓ | `player` |
|
||||
| `player_leave` | | ✓ | `player` |
|
||||
| `server_start` | | ✓ | none |
|
||||
@@ -682,6 +685,14 @@ interface Player {
|
||||
give_item(id: string, count?: number, data?: unknown): void;
|
||||
send_message(text: string): void;
|
||||
teleport(x: number, y: number, z: number): void;
|
||||
readonly health: number; // out of max_health, 20
|
||||
readonly max_health: number;
|
||||
readonly food: number; // hunger, out of 20
|
||||
readonly saturation: number; // never above food
|
||||
damage(amount: number, cause?: string): void; // cause shows in events and the death message
|
||||
heal(amount: number): void;
|
||||
feed(nutrition: number, saturation_modifier: number): void; // like eating
|
||||
add_exhaustion(amount: number): void; // 4 costs a point of saturation, or of hunger once it's gone
|
||||
}
|
||||
|
||||
interface PlayerList {
|
||||
@@ -705,6 +716,13 @@ interface ModStorage {
|
||||
}
|
||||
```
|
||||
|
||||
**Health and hunger** follow Minecraft's rules (`server/game/vitals.ts`). Sprinting, swimming, jumping, breaking blocks,
|
||||
taking damage and healing add exhaustion, and every 4 of it costs a point of saturation, or of hunger once saturation
|
||||
is gone. A full stomach heals: quickly while there's saturation, slowly with at least 18 hunger. At 0 hunger players
|
||||
lose health every 4 seconds, down to half a heart. Falls hurt 1 per block after the first 3, unless they land in water,
|
||||
and below the world players die. Dying drops everything they carried and respawns them at spawn with full health and
|
||||
hunger.
|
||||
|
||||
**World time** counts ticks since 06:00 of day 1 and never wraps around. A day (06:00 to 18:00) is 36000 ticks, 30
|
||||
minutes, and a night (18:00 to 06:00) is 12000 ticks, 10 minutes, so in game hours are shorter at night. Dusk is the
|
||||
first minute of the night and dawn the last, so it's bright all day. `common/time.ts` has `clock`, `format_clock`,
|
||||
|
||||
@@ -10,6 +10,10 @@ const SEND_POSITION_TICKS = 2;
|
||||
export class LocalPlayer extends Player {
|
||||
client: Client;
|
||||
inventories = new ClientInventories();
|
||||
// what the server says, see server/game/vitals.ts. out of 20
|
||||
health = 20;
|
||||
food = 20;
|
||||
saturation = 5;
|
||||
|
||||
move_speed = 4;
|
||||
// blocks per second, peaks about 1.25 blocks up with the entity's gravity and drag
|
||||
|
||||
+43
-3
@@ -3,7 +3,7 @@ import { AssetManager } from "$/client/assets.ts";
|
||||
import type { Client } from "$/client/client.ts";
|
||||
import type { ClientInventories } from "$/client/inventory.ts";
|
||||
import { draw_item, draw_nine_slice } from "$/client/rendering/render_utils.ts";
|
||||
import { canvas, draw_rect_stroke, draw_text, measure_text, Texture } from "$/client/renderer/mod.ts";
|
||||
import { canvas, draw_rect, draw_rect_stroke, draw_text, measure_text, Texture } from "$/client/renderer/mod.ts";
|
||||
import { display_name } from "$/common/utils.ts";
|
||||
import { TEXT_HEIGHT, TEXT_SCALE } from "./widgets.ts";
|
||||
|
||||
@@ -13,6 +13,16 @@ const CROSSHAIR_SIZE = 8;
|
||||
const HELD_NAME_MS = 2000;
|
||||
const HELD_NAME_FADE_MS = 500;
|
||||
const HELD_NAME_GAP = 12;
|
||||
// the health and hunger bars, side by side just above the hotbar
|
||||
const BAR_HEIGHT = 14;
|
||||
const BAR_GAP = 8;
|
||||
const BAR_BORDER = 2;
|
||||
const MAX_VITAL = 20;
|
||||
const HEALTH_COLOR: [number, number, number, number] = [0.84, 0.12, 0.12, 1];
|
||||
const FOOD_COLOR: [number, number, number, number] = [0.55, 0.33, 0.14, 1];
|
||||
const SATURATION_COLOR: [number, number, number, number] = [1, 0.84, 0.25, 1];
|
||||
const BAR_BACKGROUND: [number, number, number, number] = [0.1, 0.08, 0.08, 0.75];
|
||||
const BAR_OUTLINE: [number, number, number, number] = [0, 0, 0, 0.8];
|
||||
|
||||
// what's drawn over the world while playing, like minecraft's Gui: hotbar, crosshair and chat
|
||||
export class Hud {
|
||||
@@ -22,6 +32,7 @@ export class Hud {
|
||||
|
||||
render(client: Client) {
|
||||
this.#render_hotbar(client.player.inventories);
|
||||
this.#render_vitals(client);
|
||||
this.#render_held_name(client.player.inventories);
|
||||
this.#render_crosshair();
|
||||
client.chat.render(false);
|
||||
@@ -81,14 +92,43 @@ export class Hud {
|
||||
}
|
||||
const alpha = Math.min(1, (HELD_NAME_MS - shown_for) / HELD_NAME_FADE_MS);
|
||||
const name = display_name(item.type_id);
|
||||
const hotbar_top = canvas.height - (PADDING * 2 + SLOT_SIZE);
|
||||
const bars_top = canvas.height - (PADDING * 2 + SLOT_SIZE) - BAR_GAP - BAR_HEIGHT;
|
||||
const x = (canvas.width - measure_text(name, TEXT_SCALE)) / 2;
|
||||
const y = hotbar_top - HELD_NAME_GAP - TEXT_HEIGHT * TEXT_SCALE;
|
||||
const y = bars_top - HELD_NAME_GAP - TEXT_HEIGHT * TEXT_SCALE;
|
||||
// a shadow so it reads over bright sky and snow
|
||||
draw_text(name, x + TEXT_SCALE, y + TEXT_SCALE, TEXT_SCALE, [0.15, 0.15, 0.15, alpha]);
|
||||
draw_text(name, x, y, TEXT_SCALE, [1, 1, 1, alpha]);
|
||||
}
|
||||
|
||||
// health on the left, hunger on the right, like minecraft's hearts and drumsticks. saturation is a gold border
|
||||
// around as much of the hunger bar as there's saturation, it's never more than the hunger
|
||||
#render_vitals(client: Client) {
|
||||
const player = client.player;
|
||||
const hotbar_width = PADDING * 2 + SLOT_SIZE * 9;
|
||||
const bar_width = (hotbar_width - BAR_GAP) / 2;
|
||||
const left = canvas.width / 2 - hotbar_width / 2;
|
||||
const y = canvas.height - (PADDING * 2 + SLOT_SIZE) - BAR_GAP - BAR_HEIGHT;
|
||||
|
||||
this.#bar(left, y, bar_width, player.health / MAX_VITAL, HEALTH_COLOR);
|
||||
|
||||
const food_x = left + bar_width + BAR_GAP;
|
||||
this.#bar(food_x, y, bar_width, player.food / MAX_VITAL, FOOD_COLOR);
|
||||
const saturation = Math.min(player.saturation, player.food) / MAX_VITAL;
|
||||
if (saturation > 0) {
|
||||
const width = Math.max(BAR_BORDER * 2, bar_width * saturation);
|
||||
draw_rect(food_x, y, width, BAR_BORDER, SATURATION_COLOR);
|
||||
draw_rect(food_x, y + BAR_HEIGHT - BAR_BORDER, width, BAR_BORDER, SATURATION_COLOR);
|
||||
draw_rect(food_x, y, BAR_BORDER, BAR_HEIGHT, SATURATION_COLOR);
|
||||
draw_rect(food_x + width - BAR_BORDER, y, BAR_BORDER, BAR_HEIGHT, SATURATION_COLOR);
|
||||
}
|
||||
}
|
||||
|
||||
#bar(x: number, y: number, width: number, fraction: number, color: [number, number, number, number]) {
|
||||
draw_rect(x - 1, y - 1, width + 2, BAR_HEIGHT + 2, BAR_OUTLINE);
|
||||
draw_rect(x, y, width, BAR_HEIGHT, BAR_BACKGROUND);
|
||||
draw_rect(x, y, width * Math.max(0, Math.min(1, fraction)), BAR_HEIGHT, color);
|
||||
}
|
||||
|
||||
#render_crosshair() {
|
||||
draw_rect_stroke(
|
||||
(canvas.width - CROSSHAIR_SIZE) / 2,
|
||||
|
||||
@@ -9,6 +9,7 @@ type Color = [number, number, number, number];
|
||||
|
||||
const NAME_COLOR: Color = [1, 1, 1, 1];
|
||||
const LORE_COLOR: Color = [0.66, 0.66, 0.66, 1];
|
||||
const FOOD_COLOR: Color = [0.85, 0.6, 0.35, 1];
|
||||
const BACKGROUND: Color = [0.06, 0.02, 0.1, 0.94];
|
||||
const BORDER: Color = [0.31, 0.1, 0.6, 1];
|
||||
const BORDER_WIDTH = 2;
|
||||
@@ -25,7 +26,11 @@ export interface TooltipLine {
|
||||
// its name, the item's lore from its json, then what the server's scripts said about this stack
|
||||
export function item_tooltip(item: ItemStack): TooltipLine[] {
|
||||
const lines: TooltipLine[] = [{ text: display_name(item.type_id), color: NAME_COLOR }];
|
||||
const static_lore = EverythingRegistry.get<ItemRegistry>("items", item.type_id)?.lore;
|
||||
const info = EverythingRegistry.get<ItemRegistry>("items", item.type_id);
|
||||
if (info?.food) {
|
||||
lines.push({ text: `Restores ${info.food.nutrition} hunger`, color: FOOD_COLOR });
|
||||
}
|
||||
const static_lore = info?.lore;
|
||||
for (const lore of [static_lore, item.lore]) {
|
||||
for (const text of lore?.split("\n") ?? []) {
|
||||
lines.push({ text, color: LORE_COLOR });
|
||||
|
||||
@@ -34,6 +34,11 @@ export class ClientPacketListener {
|
||||
case "time":
|
||||
level.time = message.time;
|
||||
break;
|
||||
case "vitals":
|
||||
client.player.health = message.health;
|
||||
client.player.food = message.food;
|
||||
client.player.saturation = message.saturation;
|
||||
break;
|
||||
case "player_leave":
|
||||
level.remove_entity(message.id);
|
||||
break;
|
||||
|
||||
@@ -138,6 +138,18 @@ export interface BlockRegistry {
|
||||
compiled_states?: CompiledStateDefinition[];
|
||||
}
|
||||
|
||||
// what eating an item does, like minecraft's food properties
|
||||
export interface FoodProperties {
|
||||
// hunger points it restores, a bar is 20
|
||||
nutrition: number;
|
||||
// saturation it gives is nutrition * saturation_modifier * 2, like minecraft. bread's is 0.6
|
||||
saturation_modifier: number;
|
||||
// can be eaten when not hungry
|
||||
always_edible?: boolean;
|
||||
// what's left in the hand after, like a bowl after soup
|
||||
returns?: string;
|
||||
}
|
||||
|
||||
export interface ItemRegistry<T = unknown | undefined> {
|
||||
texture_id: string | ((item: ItemStack<T>) => string);
|
||||
// what players see, like "Iron Ingot". made from the id when not set, see display_name in common/utils.ts
|
||||
@@ -146,6 +158,7 @@ export interface ItemRegistry<T = unknown | undefined> {
|
||||
tool_type?: string;
|
||||
max_stack?: number;
|
||||
lore?: string;
|
||||
food?: FoodProperties;
|
||||
components?: Record<string, unknown>;
|
||||
|
||||
on_create?(item: ItemStack<T>): void;
|
||||
|
||||
@@ -95,6 +95,19 @@ export interface BlockInteractEvent {
|
||||
readonly item: ItemStack | undefined;
|
||||
}
|
||||
|
||||
export interface PlayerDamageEvent {
|
||||
readonly player: Player;
|
||||
// before events can change it
|
||||
amount: number;
|
||||
// what hurt them: "fall", "void", "starve", or what a mod passed to damage
|
||||
readonly cause: string;
|
||||
}
|
||||
|
||||
export interface PlayerDeathEvent {
|
||||
readonly player: Player;
|
||||
readonly cause: string;
|
||||
}
|
||||
|
||||
export interface ChatSendEvent {
|
||||
readonly player: Player;
|
||||
message: string;
|
||||
@@ -105,6 +118,7 @@ export interface ServerBeforeEvents {
|
||||
block_place: EventSignal<BlockPlaceEvent & Cancelable>;
|
||||
block_interact: EventSignal<BlockInteractEvent & Cancelable>;
|
||||
chat_send: EventSignal<ChatSendEvent & Cancelable>;
|
||||
player_damage: EventSignal<PlayerDamageEvent & Cancelable>;
|
||||
}
|
||||
|
||||
export interface ServerAfterEvents {
|
||||
@@ -114,6 +128,8 @@ export interface ServerAfterEvents {
|
||||
chat_send: EventSignal<Readonly<ChatSendEvent>>;
|
||||
player_join: EventSignal<{ readonly player: Player }>;
|
||||
player_leave: EventSignal<{ readonly player: Player }>;
|
||||
// they drop what they carried and respawn right after
|
||||
player_death: EventSignal<PlayerDeathEvent>;
|
||||
server_start: EventSignal<Record<never, never>>;
|
||||
tick: EventSignal<{ readonly dt: number }>;
|
||||
// 06:00, after every block's on_new_day
|
||||
@@ -150,6 +166,18 @@ export interface Player {
|
||||
give_item(id: Id, count?: number, data?: unknown): void;
|
||||
send_message(text: string): void;
|
||||
teleport(x: number, y: number, z: number): void;
|
||||
// health and hunger, like minecraft: 20 each, saturation is never above hunger
|
||||
readonly health: number;
|
||||
readonly max_health: number;
|
||||
readonly food: number;
|
||||
readonly saturation: number;
|
||||
// cause is for events and the death message, like "fall"
|
||||
damage(amount: number, cause?: string): void;
|
||||
heal(amount: number): void;
|
||||
// like eating: nutrition in hunger points, saturation_modifier like minecraft's (bread's is 0.6)
|
||||
feed(nutrition: number, saturation_modifier: number): void;
|
||||
// tires them out: 4 costs a point of saturation, or of hunger once it's gone
|
||||
add_exhaustion(amount: number): void;
|
||||
}
|
||||
|
||||
export interface PlayerList {
|
||||
|
||||
@@ -128,6 +128,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
|
||||
}
|
||||
uses(file, json.texture, "texture");
|
||||
if (json.places) uses(file, json.places, "block");
|
||||
if (json.food?.returns) uses(file, json.food.returns, "item");
|
||||
}
|
||||
for (const { file, json } of mod.recipes) {
|
||||
switch (json.type) {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import {
|
||||
type BlockRegistry,
|
||||
type BlockStateDefinition,
|
||||
type FoodProperties,
|
||||
type ItemRegistry,
|
||||
RENDER_LAYERS,
|
||||
type RenderLayer,
|
||||
@@ -68,6 +69,7 @@ export interface ItemJson {
|
||||
tool?: string;
|
||||
places?: string;
|
||||
max_stack?: number;
|
||||
food?: FoodProperties;
|
||||
name?: string;
|
||||
lore?: string;
|
||||
components?: Record<string, unknown>;
|
||||
@@ -166,6 +168,7 @@ export function item_to_json(id: string, item: ItemRegistry): ItemJson {
|
||||
if (item.tool_type !== undefined) json.tool = item.tool_type;
|
||||
if (item.block_id !== undefined) json.places = item.block_id;
|
||||
if (item.max_stack !== undefined) json.max_stack = item.max_stack;
|
||||
if (item.food !== undefined) json.food = item.food;
|
||||
if (item.name !== undefined) json.name = item.name;
|
||||
if (item.lore !== undefined) json.lore = item.lore;
|
||||
if (item.components) json.components = item.components;
|
||||
@@ -177,6 +180,7 @@ export function item_from_json(json: ItemJson): ItemRegistry {
|
||||
if (json.tool !== undefined) item.tool_type = json.tool;
|
||||
if (json.places !== undefined) item.block_id = json.places;
|
||||
if (json.max_stack !== undefined) item.max_stack = json.max_stack;
|
||||
if (json.food !== undefined) item.food = json.food;
|
||||
if (json.name !== undefined) item.name = json.name;
|
||||
if (json.lore !== undefined) item.lore = json.lore;
|
||||
if (json.components) item.components = json.components;
|
||||
@@ -434,6 +438,20 @@ export function validate_item(json: unknown): Problems {
|
||||
if (json.max_stack !== undefined && (!Number.isInteger(json.max_stack) || (json.max_stack as number) < 1)) {
|
||||
problems.push("max_stack must be a positive whole number");
|
||||
}
|
||||
if (json.food !== undefined) {
|
||||
const food = json.food;
|
||||
if (
|
||||
!is_object(food) || !Number.isInteger(food.nutrition) || (food.nutrition as number) < 0 ||
|
||||
typeof food.saturation_modifier !== "number" || food.saturation_modifier < 0
|
||||
) {
|
||||
problems.push("food must be { nutrition, saturation_modifier }, nutrition a whole number");
|
||||
} else {
|
||||
if (food.always_edible !== undefined && typeof food.always_edible !== "boolean") {
|
||||
problems.push("food.always_edible must be true or false");
|
||||
}
|
||||
if (food.returns !== undefined) problems.push(...validate_id(food.returns, "food.returns"));
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
|
||||
+4
-2
@@ -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 = 4;
|
||||
export const PROTOCOL_VERSION = 5;
|
||||
|
||||
export interface PlayerInfo {
|
||||
id: string;
|
||||
@@ -123,7 +123,9 @@ export type ServerMessage =
|
||||
| { type: "screen_properties"; properties: Record<string, number> }
|
||||
| { type: "close_screen" }
|
||||
// the world time, every second and when it's changed. clients count ticks in between
|
||||
| { type: "time"; time: number };
|
||||
| { type: "time"; time: number }
|
||||
// the player's own health, hunger and saturation, when they change
|
||||
| { type: "vitals"; health: number; food: number; saturation: number };
|
||||
|
||||
export const MAX_NAME_LENGTH = 16;
|
||||
export const MAX_CHAT_LENGTH = 256;
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"format_version": 1,
|
||||
"item": {
|
||||
"id": "bworld:carrot",
|
||||
"texture": "bworld:carrot",
|
||||
"food": {
|
||||
"nutrition": 3,
|
||||
"saturation_modifier": 0.6
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"format_version": 1,
|
||||
"item": {
|
||||
"id": "bworld:potato",
|
||||
"texture": "bworld:potato",
|
||||
"food": {
|
||||
"nutrition": 1,
|
||||
"saturation_modifier": 0.3
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,7 @@ 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_stand_on } from "$/common/utils.ts";
|
||||
import { EXHAUSTION, MAX_HEALTH } from "./vitals.ts";
|
||||
import { ModRuntime, run_guarded } from "./mod_runtime.ts";
|
||||
import type { GameLoop } from "./game_loop.ts";
|
||||
import { consume_recipe_items, update_crafting_result } from "./crafting.ts";
|
||||
@@ -52,6 +53,18 @@ 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;
|
||||
// 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)
|
||||
const SPRINT_SPEED = 5.5;
|
||||
// moving further than this at once is a teleport, not a fall
|
||||
const TELEPORT_DISTANCE = 20;
|
||||
// how close feet have to be to a block's top to stand on it
|
||||
const GROUND_EPSILON = 0.02;
|
||||
// below the world, players take VOID_DAMAGE every VOID_DAMAGE_TICKS until they die
|
||||
const VOID_Y = -64;
|
||||
const VOID_DAMAGE = 4;
|
||||
const VOID_DAMAGE_TICKS = 10;
|
||||
// the most mornings run at once after time jumps forward, the rest are skipped
|
||||
const MAX_CATCH_UP_DAYS = 64;
|
||||
// how long a client gets between welcome and ready to download and load everything
|
||||
@@ -226,6 +239,7 @@ export class GameServer {
|
||||
}
|
||||
|
||||
this.#new_days();
|
||||
this.#tick_vitals();
|
||||
this.#tick_items();
|
||||
|
||||
this.mods.tick();
|
||||
@@ -353,6 +367,7 @@ export class GameServer {
|
||||
|
||||
teleport(player: ServerPlayer, x: number, y: number, z: number) {
|
||||
Object.assign(player, { x, y, z });
|
||||
player.fall_distance = 0;
|
||||
this.#send(player, { type: "teleport", x, y, z });
|
||||
this.#broadcast({ type: "player_move", id: player.id, x, y, z, yaw: player.yaw, pitch: player.pitch }, player);
|
||||
}
|
||||
@@ -606,6 +621,7 @@ export class GameServer {
|
||||
if (![x, y, z, yaw, pitch].every(is_number)) {
|
||||
return;
|
||||
}
|
||||
this.#on_move(player, x, y, z);
|
||||
Object.assign(player, { x, y, z, yaw, pitch });
|
||||
this.#broadcast({ type: "player_move", id: player.id, x, y, z, yaw, pitch }, player);
|
||||
break;
|
||||
@@ -669,6 +685,7 @@ export class GameServer {
|
||||
}
|
||||
|
||||
this.destroy_block(x, y, z, player);
|
||||
player.vitals.add_exhaustion(EXHAUSTION.break_block);
|
||||
this.mods.after.block_break.emit(event);
|
||||
}
|
||||
|
||||
@@ -694,6 +711,9 @@ export class GameServer {
|
||||
if (!held) {
|
||||
return false;
|
||||
}
|
||||
if (this.#eat(player)) {
|
||||
return true;
|
||||
}
|
||||
const components = this.mods.item_components_of(held.type_id).filter(({ component }) => component.on_use);
|
||||
if (components.length === 0) {
|
||||
return false;
|
||||
@@ -970,6 +990,145 @@ export class GameServer {
|
||||
}
|
||||
}
|
||||
|
||||
// health and hunger, see vitals.ts
|
||||
|
||||
// hurts a player, killing them at 0. cause is for mods and the death message, like "fall"
|
||||
damage_player(player: ServerPlayer, amount: number, cause: string) {
|
||||
if (amount <= 0 || player.vitals.health <= 0) {
|
||||
return;
|
||||
}
|
||||
const before = { player: this.mods.player(player), amount, cause, cancel: false };
|
||||
this.mods.before.player_damage.emit(before);
|
||||
const final = Number(before.amount);
|
||||
if (before.cancel || !(final > 0)) {
|
||||
return;
|
||||
}
|
||||
player.vitals.health = Math.max(0, player.vitals.health - final);
|
||||
player.vitals.add_exhaustion(EXHAUSTION.damage);
|
||||
if (player.vitals.health <= 0) {
|
||||
this.#kill(player, cause);
|
||||
}
|
||||
}
|
||||
|
||||
heal_player(player: ServerPlayer, amount: number) {
|
||||
if (amount > 0 && player.vitals.health > 0) {
|
||||
player.vitals.health = Math.min(MAX_HEALTH, player.vitals.health + amount);
|
||||
}
|
||||
}
|
||||
|
||||
// like minecraft: everything they carried falls out where they died, and they start over at spawn
|
||||
#kill(player: ServerPlayer, cause: string) {
|
||||
const { x, y, z } = player;
|
||||
this.close_screen(player);
|
||||
for (let i = 0; i < player.inventory.size; i++) {
|
||||
const item = player.inventory.get_item(i);
|
||||
if (item) {
|
||||
player.inventory.set_item(i, undefined);
|
||||
this.pop_item(Math.floor(x), Math.floor(Math.max(y, 0)), Math.floor(z), item);
|
||||
}
|
||||
}
|
||||
this.mods.after.player_death.emit({ player: this.mods.player(player), cause });
|
||||
this.#broadcast({ type: "chat", text: death_message(player.name, cause) });
|
||||
player.vitals.reset();
|
||||
const spawn = this.world.spawn_point();
|
||||
this.teleport(player, spawn.x, spawn.y, spawn.z);
|
||||
this.world.dirty = true;
|
||||
}
|
||||
|
||||
#tick_vitals() {
|
||||
for (const player of this.#players.values()) {
|
||||
player.vitals.tick(
|
||||
(amount) => this.heal_player(player, amount),
|
||||
(amount) => this.damage_player(player, amount, "starve"),
|
||||
);
|
||||
// out of the world, like minecraft's void
|
||||
if (player.y < VOID_Y && this.#tick % VOID_DAMAGE_TICKS === 0) {
|
||||
this.damage_player(player, VOID_DAMAGE, "void");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// what moving costs and does: sprinting and swimming tire, jumping too, and landing after a fall hurts
|
||||
#on_move(player: ServerPlayer, x: number, y: number, z: number) {
|
||||
const dx = x - player.x;
|
||||
const dy = y - player.y;
|
||||
const dz = z - player.z;
|
||||
const ticks = Math.max(1, this.#tick - player.last_move_tick);
|
||||
player.last_move_tick = this.#tick;
|
||||
const horizontal = Math.hypot(dx, dz);
|
||||
// teleports and the first move after joining aren't walking
|
||||
if (horizontal > TELEPORT_DISTANCE || Math.abs(dy) > TELEPORT_DISTANCE) {
|
||||
player.fall_distance = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
const vitals = player.vitals;
|
||||
const in_liquid = this.#in_liquid(x, y, z);
|
||||
const sprinting = horizontal / (ticks * TICK_DELTA) > SPRINT_SPEED;
|
||||
if (in_liquid) {
|
||||
vitals.add_exhaustion(EXHAUSTION.swim_per_block * (horizontal + Math.abs(dy)));
|
||||
player.fall_distance = 0;
|
||||
} else if (sprinting) {
|
||||
vitals.add_exhaustion(EXHAUSTION.sprint_per_block * horizontal);
|
||||
}
|
||||
if (dy > 0 && !in_liquid && this.#on_ground(player.x, player.y, player.z)) {
|
||||
vitals.add_exhaustion(sprinting ? EXHAUSTION.sprint_jump : EXHAUSTION.jump);
|
||||
}
|
||||
|
||||
if (dy < 0 && !in_liquid) {
|
||||
player.fall_distance -= dy;
|
||||
}
|
||||
if (this.#on_ground(x, y, z)) {
|
||||
const damage = Math.ceil(player.fall_distance - SAFE_FALL);
|
||||
player.fall_distance = 0;
|
||||
if (damage > 0) {
|
||||
this.damage_player(player, damage, "fall");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// feet on top of something solid, anywhere under the player's box
|
||||
#on_ground(x: number, y: number, z: number) {
|
||||
const fraction = y - Math.floor(y);
|
||||
if (fraction > GROUND_EPSILON && fraction < 1 - GROUND_EPSILON) {
|
||||
return false;
|
||||
}
|
||||
const below = Math.floor(y - GROUND_EPSILON);
|
||||
const half = PLAYER_WIDTH / 2;
|
||||
for (const [ox, oz] of [[-half, -half], [half, -half], [-half, half], [half, half]]) {
|
||||
if (this.world.has_collision(Math.floor(x + ox), below, Math.floor(z + oz))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// in a block entities pass through and players can place into, like water
|
||||
#in_liquid(x: number, y: number, z: number) {
|
||||
const info = this.world.get_block_info(Math.floor(x), Math.floor(y), Math.floor(z));
|
||||
return info !== undefined && !info.has_collision && info.replaceable === true;
|
||||
}
|
||||
|
||||
// right click with food: it's eaten if they're hungry, or it's always edible
|
||||
#eat(player: ServerPlayer): boolean {
|
||||
const slot = player.inventory.get_slot(player.selected_slot);
|
||||
const food = EverythingRegistry.get<ItemRegistry>("items", slot.type_id ?? "")?.food;
|
||||
if (!food || (!food.always_edible && !player.vitals.can_eat())) {
|
||||
return false;
|
||||
}
|
||||
player.vitals.eat(food.nutrition, food.saturation_modifier);
|
||||
slot.amount = slot.amount! - 1;
|
||||
if (food.returns) {
|
||||
const left = new ItemStack(food.returns);
|
||||
if (slot.has_item()) {
|
||||
this.give_stack(player, left);
|
||||
} else {
|
||||
slot.set_item(left);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// items on the ground
|
||||
|
||||
#new_entity_id() {
|
||||
@@ -1104,6 +1263,9 @@ export class GameServer {
|
||||
const cursor = player.cursor.item?.to_synced_data() ?? null;
|
||||
sync("cursor", cursor, () => ({ type: "cursor", item: cursor }));
|
||||
|
||||
const { health, food, saturation } = player.vitals;
|
||||
sync("vitals", [health, food, saturation], () => ({ type: "vitals", health, food, saturation }));
|
||||
|
||||
if (player.screen) {
|
||||
const items = player.screen.container.to_synced_data();
|
||||
sync("screen", items, () => ({ type: "container", container: "screen", items }));
|
||||
@@ -1186,3 +1348,17 @@ function is_block_position(x: unknown, y: unknown, z: unknown): boolean {
|
||||
return is_int(x) && is_int(y) && is_int(z) && y >= 0 && y < CHUNK_HEIGHT &&
|
||||
Math.abs(x) < 30000 * CHUNK_SIZE && Math.abs(z) < 30000 * CHUNK_SIZE;
|
||||
}
|
||||
|
||||
// what everyone's told when someone dies
|
||||
function death_message(name: string, cause: string) {
|
||||
switch (cause) {
|
||||
case "fall":
|
||||
return `${name} hit the ground too hard`;
|
||||
case "void":
|
||||
return `${name} fell out of the world`;
|
||||
case "starve":
|
||||
return `${name} starved to death`;
|
||||
default:
|
||||
return `${name} died`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ import { ModLoadError } from "$/common/mod_loader.ts";
|
||||
import { AIR_ID } from "$/common/protocol.ts";
|
||||
import type { GameServer } from "./game_server.ts";
|
||||
import type { OpenScreen, ServerPlayer } from "./player.ts";
|
||||
import { MAX_HEALTH } from "./vitals.ts";
|
||||
import type { ScreenLayout } from "$/common/protocol.ts";
|
||||
|
||||
// a list of handlers that can't break each other: one throwing is logged under its mod and the rest still run
|
||||
@@ -89,6 +90,7 @@ export class ModRuntime {
|
||||
block_place: new Signal(),
|
||||
block_interact: new Signal(),
|
||||
chat_send: new Signal(),
|
||||
player_damage: new Signal(),
|
||||
};
|
||||
after: After = {
|
||||
block_break: new Signal(),
|
||||
@@ -97,6 +99,7 @@ export class ModRuntime {
|
||||
chat_send: new Signal(),
|
||||
player_join: new Signal(),
|
||||
player_leave: new Signal(),
|
||||
player_death: new Signal(),
|
||||
server_start: new Signal(),
|
||||
tick: new Signal(),
|
||||
new_day: new Signal(),
|
||||
@@ -662,5 +665,35 @@ function player_api(game: GameServer, player: ServerPlayer): Player {
|
||||
teleport(x, y, z) {
|
||||
game.teleport(player, x, y, z);
|
||||
},
|
||||
get health() {
|
||||
return player.vitals.health;
|
||||
},
|
||||
max_health: MAX_HEALTH,
|
||||
get food() {
|
||||
return player.vitals.food;
|
||||
},
|
||||
get saturation() {
|
||||
return player.vitals.saturation;
|
||||
},
|
||||
damage(amount, cause = "script") {
|
||||
if (typeof amount !== "number" || !Number.isFinite(amount)) throw new Error(`damage must be a number`);
|
||||
game.damage_player(player, amount, String(cause));
|
||||
},
|
||||
heal(amount) {
|
||||
if (typeof amount !== "number" || !Number.isFinite(amount)) throw new Error(`heal must be a number`);
|
||||
game.heal_player(player, amount);
|
||||
},
|
||||
feed(nutrition, saturation_modifier) {
|
||||
if (![nutrition, saturation_modifier].every((n) => typeof n === "number" && Number.isFinite(n) && n >= 0)) {
|
||||
throw new Error("feed takes two numbers of 0 or more");
|
||||
}
|
||||
player.vitals.eat(nutrition, saturation_modifier);
|
||||
},
|
||||
add_exhaustion(amount) {
|
||||
if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0) {
|
||||
throw new Error("exhaustion must be a number of 0 or more");
|
||||
}
|
||||
player.vitals.add_exhaustion(amount);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Container, Cursor, ItemData, ItemStack } from "$/common/inventory.ts";
|
||||
import { PlayerInfo, ScreenLayout } from "$/common/protocol.ts";
|
||||
import { type SavedVitals, Vitals } from "./vitals.ts";
|
||||
|
||||
export const INVENTORY_SIZE = 9 * 4;
|
||||
export const CRAFTING_SIZE = 10;
|
||||
@@ -26,6 +27,8 @@ export interface SavedPlayer {
|
||||
pitch: number;
|
||||
selected_slot: number;
|
||||
inventory: (ItemData | null)[];
|
||||
// players saved before health and hunger start full
|
||||
vitals?: SavedVitals;
|
||||
}
|
||||
|
||||
export class ServerPlayer {
|
||||
@@ -40,6 +43,11 @@ export class ServerPlayer {
|
||||
pitch = 0;
|
||||
|
||||
inventory = new Container(INVENTORY_SIZE);
|
||||
vitals = new Vitals();
|
||||
// blocks fallen since last standing on something, for fall damage
|
||||
fall_distance = 0;
|
||||
// when the last move came, to tell walking from sprinting
|
||||
last_move_tick = 0;
|
||||
crafting = new Container(CRAFTING_SIZE);
|
||||
cursor: Cursor = { item: undefined };
|
||||
selected_slot = 0;
|
||||
@@ -70,6 +78,7 @@ export class ServerPlayer {
|
||||
pitch: this.pitch,
|
||||
selected_slot: this.selected_slot,
|
||||
inventory: this.inventory.to_data(),
|
||||
vitals: this.vitals.save(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -81,5 +90,6 @@ export class ServerPlayer {
|
||||
this.pitch = saved.pitch;
|
||||
this.selected_slot = saved.selected_slot;
|
||||
this.inventory.load(saved.inventory);
|
||||
this.vitals.load(saved.vitals);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
// a player's health, hunger and saturation, with minecraft's rules (its FoodData). the server owns them, clients only
|
||||
// draw them
|
||||
import { TICKS_PER_SECOND } from "$/common/constants.ts";
|
||||
|
||||
export const MAX_HEALTH = 20;
|
||||
export const MAX_FOOD = 20;
|
||||
// what a new or respawned player starts with, like minecraft
|
||||
export const START_SATURATION = 5;
|
||||
// every this much exhaustion costs a point of saturation, or of hunger once saturation is gone
|
||||
const EXHAUSTION_PER_POINT = 4;
|
||||
const MAX_EXHAUSTION = 40;
|
||||
// healing from a full stomach: fast while there's saturation, slow while hunger is at least SLOW_REGEN_FOOD
|
||||
const FAST_REGEN_TICKS = 10;
|
||||
const SLOW_REGEN_TICKS = 4 * TICKS_PER_SECOND;
|
||||
const SLOW_REGEN_FOOD = 18;
|
||||
const STARVE_TICKS = 4 * TICKS_PER_SECOND;
|
||||
// starving stops here, like minecraft on normal difficulty
|
||||
const STARVE_MIN_HEALTH = 1;
|
||||
|
||||
// how tiring things are, from minecraft
|
||||
export const EXHAUSTION = {
|
||||
sprint_per_block: 0.1,
|
||||
swim_per_block: 0.01,
|
||||
jump: 0.05,
|
||||
sprint_jump: 0.2,
|
||||
break_block: 0.005,
|
||||
damage: 0.1,
|
||||
heal_per_health: 6,
|
||||
};
|
||||
|
||||
export interface SavedVitals {
|
||||
health: number;
|
||||
food: number;
|
||||
saturation: number;
|
||||
exhaustion: number;
|
||||
}
|
||||
|
||||
export class Vitals {
|
||||
health = MAX_HEALTH;
|
||||
food = MAX_FOOD;
|
||||
saturation = START_SATURATION;
|
||||
exhaustion = 0;
|
||||
#timer = 0;
|
||||
|
||||
add_exhaustion(amount: number) {
|
||||
this.exhaustion = Math.min(this.exhaustion + amount, MAX_EXHAUSTION);
|
||||
}
|
||||
|
||||
// eating: saturation_modifier works like minecraft's, bread's is 0.6. saturation never goes above hunger
|
||||
eat(nutrition: number, saturation_modifier: number) {
|
||||
this.food = Math.min(this.food + nutrition, MAX_FOOD);
|
||||
this.saturation = Math.min(this.saturation + nutrition * saturation_modifier * 2, this.food);
|
||||
}
|
||||
|
||||
can_eat() {
|
||||
return this.food < MAX_FOOD;
|
||||
}
|
||||
|
||||
// one tick. heal and hurt go through the game server, which fires events and handles dying
|
||||
tick(heal: (amount: number) => void, hurt: (amount: number) => void) {
|
||||
if (this.exhaustion > EXHAUSTION_PER_POINT) {
|
||||
this.exhaustion -= EXHAUSTION_PER_POINT;
|
||||
if (this.saturation > 0) {
|
||||
this.saturation = Math.max(this.saturation - 1, 0);
|
||||
} else {
|
||||
this.food = Math.max(this.food - 1, 0);
|
||||
}
|
||||
}
|
||||
|
||||
const hurt_some = this.health < MAX_HEALTH;
|
||||
if (this.saturation > 0 && hurt_some && this.food >= MAX_FOOD) {
|
||||
if (++this.#timer >= FAST_REGEN_TICKS) {
|
||||
const amount = Math.min(this.saturation, 6);
|
||||
heal(amount / 6);
|
||||
this.add_exhaustion(amount);
|
||||
this.#timer = 0;
|
||||
}
|
||||
} else if (this.food >= SLOW_REGEN_FOOD && hurt_some) {
|
||||
if (++this.#timer >= SLOW_REGEN_TICKS) {
|
||||
heal(1);
|
||||
this.add_exhaustion(EXHAUSTION.heal_per_health);
|
||||
this.#timer = 0;
|
||||
}
|
||||
} else if (this.food <= 0) {
|
||||
if (++this.#timer >= STARVE_TICKS) {
|
||||
if (this.health > STARVE_MIN_HEALTH) hurt(1);
|
||||
this.#timer = 0;
|
||||
}
|
||||
} else {
|
||||
this.#timer = 0;
|
||||
}
|
||||
}
|
||||
|
||||
reset() {
|
||||
this.health = MAX_HEALTH;
|
||||
this.food = MAX_FOOD;
|
||||
this.saturation = START_SATURATION;
|
||||
this.exhaustion = 0;
|
||||
this.#timer = 0;
|
||||
}
|
||||
|
||||
save(): SavedVitals {
|
||||
return { health: this.health, food: this.food, saturation: this.saturation, exhaustion: this.exhaustion };
|
||||
}
|
||||
|
||||
load(saved: SavedVitals | undefined) {
|
||||
if (!saved) return;
|
||||
this.health = saved.health;
|
||||
this.food = saved.food;
|
||||
this.saturation = saved.saturation;
|
||||
this.exhaustion = saved.exhaustion;
|
||||
}
|
||||
}
|
||||
@@ -24,8 +24,8 @@ const inventory_of = (messages: Msg[]) =>
|
||||
Deno.test("the base game loads from mods/bworld", async () => {
|
||||
const { game } = await test_game("mods");
|
||||
assertEquals(EverythingRegistry.entries("blocks").length, 21);
|
||||
// 15 items plus the item forms of the 18 blocks that have one
|
||||
assertEquals(EverythingRegistry.entries("items").length, 33);
|
||||
// 17 items plus the item forms of the 18 blocks that have one
|
||||
assertEquals(EverythingRegistry.entries("items").length, 35);
|
||||
assertEquals(game.recipes.shaped.length, 5);
|
||||
assertEquals(game.recipes.furnace.size, 6);
|
||||
assertEquals(game.recipes.fuel.size, 2);
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
// health, hunger and saturation, with minecraft's rules
|
||||
import { assert, assertAlmostEquals, assertEquals } from "@std/assert";
|
||||
import { MAX_HEALTH, Vitals } from "$/server/game/vitals.ts";
|
||||
import { test_game } from "./helpers.ts";
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
type Msg = any;
|
||||
|
||||
Deno.test("exhaustion eats saturation first, then hunger", () => {
|
||||
const vitals = new Vitals();
|
||||
const noop = () => {};
|
||||
vitals.add_exhaustion(4.1);
|
||||
vitals.tick(noop, noop);
|
||||
assertEquals([vitals.food, vitals.saturation], [20, 4]);
|
||||
|
||||
vitals.saturation = 0;
|
||||
vitals.add_exhaustion(4);
|
||||
vitals.tick(noop, noop);
|
||||
assertEquals([vitals.food, vitals.saturation], [19, 0]);
|
||||
});
|
||||
|
||||
Deno.test("a full stomach heals, fast with saturation and slowly without, and starving stops at half a heart", () => {
|
||||
let healed = 0;
|
||||
let hurt = 0;
|
||||
const heal = (amount: number) => healed += amount;
|
||||
const damage = (amount: number) => hurt += amount;
|
||||
|
||||
// full hunger and saturation: every 10 ticks, up to a whole heart, paid for with exhaustion
|
||||
const fast = new Vitals();
|
||||
fast.health = 10;
|
||||
for (let i = 0; i < 10; i++) fast.tick(heal, damage);
|
||||
assertAlmostEquals(healed, 5 / 6);
|
||||
assertEquals(fast.exhaustion, 5);
|
||||
|
||||
// 18 hunger and no saturation: 1 every 4 seconds
|
||||
healed = 0;
|
||||
const slow = new Vitals();
|
||||
slow.health = 10;
|
||||
slow.food = 18;
|
||||
slow.saturation = 0;
|
||||
for (let i = 0; i < 80; i++) slow.tick(heal, damage);
|
||||
assertEquals(healed, 1);
|
||||
|
||||
// starving: 1 every 4 seconds, never below 1 health
|
||||
const starving = new Vitals();
|
||||
starving.food = 0;
|
||||
starving.saturation = 0;
|
||||
starving.health = 2;
|
||||
for (let i = 0; i < 80; i++) starving.tick(heal, (amount) => starving.health -= amount);
|
||||
assertEquals(starving.health, 1);
|
||||
for (let i = 0; i < 400; i++) starving.tick(heal, (amount) => starving.health -= amount);
|
||||
assertEquals(starving.health, 1);
|
||||
assertEquals(hurt, 0);
|
||||
});
|
||||
|
||||
Deno.test("eating fills hunger, and saturation never goes above it", () => {
|
||||
const vitals = new Vitals();
|
||||
vitals.food = 10;
|
||||
vitals.saturation = 0;
|
||||
vitals.eat(3, 0.6);
|
||||
assertEquals(vitals.food, 13);
|
||||
assertAlmostEquals(vitals.saturation, 3.6);
|
||||
vitals.eat(20, 1.2);
|
||||
assertEquals([vitals.food, vitals.saturation], [20, 20]);
|
||||
});
|
||||
|
||||
// a player standing on a stone floor at y 99
|
||||
async function setup() {
|
||||
const t = await test_game("mods");
|
||||
t.join(1, "alice");
|
||||
for (let x = -3; x <= 3; x++) {
|
||||
for (let z = -3; z <= 3; z++) t.game.set_block(x, 99, z, "bworld:stone");
|
||||
}
|
||||
const move = (y: number) => t.send(1, { type: "move", x: 0.5, y, z: 0.5, yaw: 0, pitch: 0 });
|
||||
move(100);
|
||||
const player = t.game.players()[0];
|
||||
return { ...t, move, player };
|
||||
}
|
||||
|
||||
Deno.test("falling more than 3 blocks hurts, 1 per block after that, and water breaks the fall", async () => {
|
||||
const t = await setup();
|
||||
// up 10 blocks, then down in steps like a fall
|
||||
t.move(110);
|
||||
for (let y = 109; y >= 100; y--) t.move(y);
|
||||
assertEquals(t.player.vitals.health, MAX_HEALTH - 7);
|
||||
|
||||
// the same fall into water
|
||||
t.player.vitals.health = MAX_HEALTH;
|
||||
t.game.set_block(0, 100, 0, "bworld:water");
|
||||
t.move(110);
|
||||
for (let y = 109; y >= 100; y--) t.move(y);
|
||||
assertEquals(t.player.vitals.health, MAX_HEALTH);
|
||||
});
|
||||
|
||||
Deno.test("health and hunger are sent to the player when they change, and saved", async () => {
|
||||
const t = await setup();
|
||||
t.take(1);
|
||||
t.player.vitals.health = 15;
|
||||
t.player.vitals.food = 12;
|
||||
t.game.tick();
|
||||
const vitals = t.take(1).filter((m) => m.type === "vitals").at(-1);
|
||||
assertEquals([vitals.health, vitals.food], [15, 12]);
|
||||
t.game.tick();
|
||||
assert(!t.take(1).some((m) => m.type === "vitals"), "only when they change");
|
||||
|
||||
t.game.on_disconnect(1);
|
||||
const loaded = await test_game("mods", t.game.save());
|
||||
loaded.join(1, "alice");
|
||||
assertEquals(loaded.game.players()[0].vitals.health, 15);
|
||||
assertEquals(loaded.game.players()[0].vitals.food, 12);
|
||||
});
|
||||
|
||||
Deno.test("right clicking food eats it when hungry, and not when full", async () => {
|
||||
const t = await setup();
|
||||
t.send(1, { type: "chat", text: "/give carrot 2" });
|
||||
const slot = t.player.inventory.to_data().findIndex((i) => i?.id === "bworld:carrot");
|
||||
t.send(1, { type: "select_slot", slot });
|
||||
|
||||
t.send(1, { type: "use_item" });
|
||||
assertEquals(t.player.inventory.get_item(slot)?.amount, 2, "full, so it isn't eaten");
|
||||
|
||||
t.player.vitals.food = 10;
|
||||
t.player.vitals.saturation = 0;
|
||||
t.send(1, { type: "use_item" });
|
||||
assertEquals(t.player.vitals.food, 13);
|
||||
assertAlmostEquals(t.player.vitals.saturation, 3.6);
|
||||
assertEquals(t.player.inventory.get_item(slot)?.amount, 1);
|
||||
});
|
||||
|
||||
Deno.test("dying drops everything, tells everyone, and respawns with full health and hunger", async () => {
|
||||
const t = await setup();
|
||||
const deaths: string[] = [];
|
||||
t.game.mods.after.player_death.for_mod("test").subscribe(({ player, cause }) =>
|
||||
deaths.push(`${player.name} ${cause}`)
|
||||
);
|
||||
t.send(1, { type: "chat", text: "/give coal 5" });
|
||||
t.player.vitals.food = 3;
|
||||
t.take(1);
|
||||
|
||||
t.game.damage_player(t.player, 25, "fall");
|
||||
const messages = t.take(1);
|
||||
assertEquals(deaths, ["alice fall"]);
|
||||
assert(messages.some((m: Msg) => m.type === "chat" && m.text === "alice hit the ground too hard"));
|
||||
assert(messages.some((m: Msg) => m.type === "teleport"));
|
||||
assertEquals([t.player.vitals.health, t.player.vitals.food], [MAX_HEALTH, 20]);
|
||||
assert(t.player.inventory.to_data().every((i) => i === null));
|
||||
assertEquals(t.game.item_entities().map((e) => e.item.to_data()), [{ id: "bworld:coal", count: 5 }]);
|
||||
});
|
||||
|
||||
Deno.test("mods can stop or change damage, and hurt, heal and feed players", async () => {
|
||||
const t = await setup();
|
||||
t.game.mods.before.player_damage.for_mod("test").subscribe((event) => {
|
||||
if (event.cause === "fall") event.cancel = true;
|
||||
if (event.cause === "poison") event.amount = 1;
|
||||
});
|
||||
const api = t.game.mods.player(t.player);
|
||||
t.game.damage_player(t.player, 10, "fall");
|
||||
assertEquals(api.health, MAX_HEALTH);
|
||||
api.damage(10, "poison");
|
||||
assertEquals(api.health, MAX_HEALTH - 1);
|
||||
api.heal(5);
|
||||
assertEquals(api.health, MAX_HEALTH);
|
||||
t.player.vitals.food = 2;
|
||||
api.feed(4, 0.5);
|
||||
assertEquals(api.food, 6);
|
||||
});
|
||||
Reference in New Issue
Block a user