Health and hunger system

This commit is contained in:
2026-09-26 21:07:36 -03:00
parent 0fa6ec4ed3
commit 8d9c85d379
18 changed files with 662 additions and 8 deletions
+176
View File
@@ -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`;
}
}
+33
View File
@@ -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);
},
};
}
+10
View File
@@ -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);
}
}
+113
View File
@@ -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;
}
}