Make players mobs too !

This commit is contained in:
2026-09-30 10:42:52 -03:00
parent 65f27d6099
commit 4fbcca6851
23 changed files with 314 additions and 132 deletions
+7 -4
View File
@@ -4,6 +4,7 @@ import { LocalPlayer } from "./entity/local_player.ts";
import { RemotePlayer } from "./entity/remote_player.ts"; import { RemotePlayer } from "./entity/remote_player.ts";
import { ItemEntity } from "./entity/item_entity.ts"; import { ItemEntity } from "./entity/item_entity.ts";
import { RemoteEntity } from "./entity/remote_entity.ts"; import { RemoteEntity } from "./entity/remote_entity.ts";
import type { Entity } from "./entity/entity.ts";
import { Camera } from "./camera.ts"; import { Camera } from "./camera.ts";
import { Options } from "./options.ts"; import { Options } from "./options.ts";
import { MultiPlayerGameMode } from "./game_mode.ts"; import { MultiPlayerGameMode } from "./game_mode.ts";
@@ -46,8 +47,8 @@ export class Client {
screens: GuiScreen[] = []; screens: GuiScreen[] = [];
// what the player is looking at, updated every frame // what the player is looking at, updated every frame
hit_result: BlockHitResult | undefined; hit_result: BlockHitResult | undefined;
// the entity being looked at, closer than any block. hit_result is undefined then // the entity or other player being looked at, closer than any block. hit_result is undefined then
entity_hit: RemoteEntity | undefined; entity_hit: Entity | undefined;
debugging = false; debugging = false;
// seconds of game time not ticked yet // seconds of game time not ticked yet
@@ -255,7 +256,9 @@ export class Client {
player.yaw, player.yaw,
player.pitch, player.pitch,
ENTITY_REACH, ENTITY_REACH,
(entity) => entity instanceof RemoteEntity && !entity.dead && is_hittable(entity), (entity) =>
entity instanceof RemotePlayer ||
(entity instanceof RemoteEntity && !entity.dead && is_hittable(entity)),
); );
// a block in front of the entity hides it // a block in front of the entity hides it
this.hit_result = this.level.pick( this.hit_result = this.level.pick(
@@ -266,7 +269,7 @@ export class Client {
player.pitch, player.pitch,
picked?.distance ?? BLOCK_REACH, picked?.distance ?? BLOCK_REACH,
); );
this.entity_hit = picked && !this.hit_result ? picked.entity as RemoteEntity : undefined; this.entity_hit = picked && !this.hit_result ? picked.entity : undefined;
} }
// clicks happen right away, holding to break advances in tick() // clicks happen right away, holding to break advances in tick()
+12
View File
@@ -4,6 +4,8 @@ import type { ClientLevel } from "../level/client_level.ts";
import { Player } from "./player.ts"; import { Player } from "./player.ts";
const SMOOTHING = 12; const SMOOTHING = 12;
// how long they flash red after being hurt, like minecraft
const HURT_TICKS = 10;
// another player on the server, it moves where the server says instead of simulating anything // another player on the server, it moves where the server says instead of simulating anything
export class RemotePlayer extends Player { export class RemotePlayer extends Player {
@@ -11,6 +13,8 @@ export class RemotePlayer extends Player {
target_x: number; target_x: number;
target_y: number; target_y: number;
target_z: number; target_z: number;
// counting down after a hurt event
hurt_time = 0;
constructor(level: ClientLevel, info: PlayerInfo) { constructor(level: ClientLevel, info: PlayerInfo) {
super(level, info.id, info.name); super(level, info.id, info.name);
@@ -33,7 +37,15 @@ export class RemotePlayer extends Player {
this.pitch = pitch; this.pitch = pitch;
} }
// players respawn straight away, so dying doesn't show
on_event(event: "hurt" | "death") {
if (event === "hurt") {
this.hurt_time = HURT_TICKS;
}
}
tick() { tick() {
if (this.hurt_time > 0) this.hurt_time -= 1;
const t = Math.min(1, TICK_DELTA * SMOOTHING); const t = Math.min(1, TICK_DELTA * SMOOTHING);
this.x += (this.target_x - this.x) * t; this.x += (this.target_x - this.x) * t;
this.y += (this.target_y - this.y) * t; this.y += (this.target_y - this.y) * t;
+3 -2
View File
@@ -8,6 +8,7 @@ import { box_overlaps_block, can_place, placement_target } from "$/common/utils.
import type { EntityJson } from "$/common/mod_data.ts"; import type { EntityJson } from "$/common/mod_data.ts";
import { RemoteEntity } from "./entity/remote_entity.ts"; import { RemoteEntity } from "./entity/remote_entity.ts";
import { Player } from "./entity/player.ts"; import { Player } from "./entity/player.ts";
import type { Entity } from "./entity/entity.ts";
// breaking and using blocks against a server, like minecraft's MultiPlayerGameMode. the client times breaking // breaking and using blocks against a server, like minecraft's MultiPlayerGameMode. the client times breaking
// and guesses the results so they feel instant, the server decides what really happens // and guesses the results so they feel instant, the server decides what really happens
@@ -95,8 +96,8 @@ export class MultiPlayerGameMode {
container.set_item(index, item.amount > 0 ? item : undefined); container.set_item(index, item.amount > 0 ? item : undefined);
} }
// left click on an entity, the server decides whether it's hurt // left click on an entity or another player, the server decides whether it's hurt
attack(entity: RemoteEntity) { attack(entity: Entity) {
this.client.player.send_position_now(); this.client.player.send_position_now();
this.client.connection.send({ type: "attack_entity", id: entity.id }); this.client.connection.send({ type: "attack_entity", id: entity.id });
} }
+6 -1
View File
@@ -119,7 +119,7 @@ export class ClientPacketListener {
} }
case "entity_event": { case "entity_event": {
const entity = level.entities.get(message.id); const entity = level.entities.get(message.id);
if (entity instanceof RemoteEntity) { if (entity instanceof RemoteEntity || entity instanceof RemotePlayer) {
entity.on_event(message.event); entity.on_event(message.event);
} }
break; break;
@@ -224,6 +224,11 @@ export class ClientPacketListener {
case "teleport": case "teleport":
client.player.set_position(message.x, message.y, message.z); client.player.set_position(message.x, message.y, message.z);
break; break;
case "set_motion":
client.player.vx = message.vx;
client.player.vy = message.vy;
client.player.vz = message.vz;
break;
case "close_screen": case "close_screen":
// closed by the server (the block broke), it already put everything back // closed by the server (the block broke), it already put everything back
client.screens = client.screens.filter((s) => !(s instanceof GuiContainer)); client.screens = client.screens.filter((s) => !(s instanceof GuiContainer));
+1 -3
View File
@@ -9,12 +9,10 @@ import { get_sprite_region } from "$/client/sprites.ts";
import type { SpriteRegion } from "$/common/constants.ts"; import type { SpriteRegion } from "$/common/constants.ts";
import { EverythingRegistry } from "$/common/everything_registry.ts"; import { EverythingRegistry } from "$/common/everything_registry.ts";
import type { EntityBoneJson, EntityJson, EntityModelJson } from "$/common/mod_data.ts"; import type { EntityBoneJson, EntityJson, EntityModelJson } from "$/common/mod_data.ts";
import { push_box, type Vec3 } from "./player_renderer.ts"; import { HURT_TINT, push_box, type Vec3 } from "./player_renderer.ts";
// models are in texture pixels, 16 to a block // models are in texture pixels, 16 to a block
const PIXEL = 1 / 16; const PIXEL = 1 / 16;
// how much of each color is left while it flashes red after being hurt, like minecraft's
const HURT_TINT: Vec3 = [1, 0.6, 0.6];
// the atlas has to be the current texture // the atlas has to be the current texture
export function render_mod_entity(entity: RemoteEntity, camera: Camera, partial_tick: number) { export function render_mod_entity(entity: RemoteEntity, camera: Camera, partial_tick: number) {
+2 -2
View File
@@ -7,7 +7,7 @@ import type { Entity } from "$/client/entity/entity.ts";
import { RemotePlayer } from "$/client/entity/remote_player.ts"; import { RemotePlayer } from "$/client/entity/remote_player.ts";
import { ItemEntity } from "$/client/entity/item_entity.ts"; import { ItemEntity } from "$/client/entity/item_entity.ts";
import { render_block_items, render_item_entity } from "./item_renderer.ts"; import { render_block_items, render_item_entity } from "./item_renderer.ts";
import { render_player } from "./player_renderer.ts"; import { HURT_TINT, render_player } from "./player_renderer.ts";
import { render_mod_entity } from "./entity_renderer.ts"; import { render_mod_entity } from "./entity_renderer.ts";
import { RemoteEntity } from "$/client/entity/remote_entity.ts"; import { RemoteEntity } from "$/client/entity/remote_entity.ts";
import { import {
@@ -104,7 +104,7 @@ export class LevelRenderer {
flush_batch(); flush_batch();
set_current_texture(skin.tex); set_current_texture(skin.tex);
} }
render_player(entity, skin, partial_tick); render_player(entity, skin, partial_tick, entity.hurt_time > 0 ? HURT_TINT : undefined);
} }
} }
flush_batch(); flush_batch();
+10 -5
View File
@@ -4,6 +4,9 @@ import { push_vertex, type Texture } from "$/client/renderer/mod.ts";
export type Vec3 = [number, number, number]; export type Vec3 = [number, number, number];
// how much of each color is left while something flashes red after being hurt, like minecraft's
export const HURT_TINT: Vec3 = [1, 0.6, 0.6];
// minecraft's player model is 32 skin pixels tall, it's scaled to the player's height // minecraft's player model is 32 skin pixels tall, it's scaled to the player's height
const PIXEL = PLAYER_HEIGHT / 32; const PIXEL = PLAYER_HEIGHT / 32;
// keeps nearest sampling from picking the texel next to a face's edge // keeps nearest sampling from picking the texel next to a face's edge
@@ -144,8 +147,9 @@ const FACES: { rect: (w: number, h: number, d: number) => number[]; corners: num
}, },
]; ];
// a player with a minecraft skin, like minecraft's PlayerRenderer. the skin has to be the current texture // a player with a minecraft skin, like minecraft's PlayerRenderer. the skin has to be the current texture. tint
export function render_player(player: Player, skin: Texture, partial_tick: number) { // multiplies its colors, for flashing red when hurt
export function render_player(player: Player, skin: Texture, partial_tick: number, tint?: Vec3) {
const { x, y, z } = player.render_position(partial_tick); const { x, y, z } = player.render_position(partial_tick);
const yaw_sin = Math.sin(player.yaw); const yaw_sin = Math.sin(player.yaw);
const yaw_cos = Math.cos(player.yaw); const yaw_cos = Math.cos(player.yaw);
@@ -173,8 +177,8 @@ export function render_player(player: Player, skin: Texture, partial_tick: numbe
const mz = (py * sin + pz * cos + pivot_z) * PIXEL; const mz = (py * sin + pz * cos + pivot_z) * PIXEL;
return [x + mx * yaw_cos + mz * yaw_sin, y + my, z - mx * yaw_sin + mz * yaw_cos]; return [x + mx * yaw_cos + mz * yaw_sin, y + my, z - mx * yaw_sin + mz * yaw_cos];
}; };
push_cube(skin, part, part.texture, 0, transform); push_cube(skin, part, part.texture, 0, transform, tint);
push_cube(skin, part, part.overlay, part.inflate, transform); push_cube(skin, part, part.overlay, part.inflate, transform, tint);
} }
} }
@@ -184,10 +188,11 @@ function push_cube(
uv: [number, number], uv: [number, number],
inflate: number, inflate: number,
transform: (x: number, y: number, z: number) => Vec3, transform: (x: number, y: number, z: number) => Vec3,
tint?: Vec3,
) { ) {
const low = part.from.map((n) => n - inflate) as Vec3; const low = part.from.map((n) => n - inflate) as Vec3;
const high = part.from.map((n, i) => n + part.size[i] + inflate) as Vec3; const high = part.from.map((n, i) => n + part.size[i] + inflate) as Vec3;
push_box(part.size, low, high, uv, (u, v) => [u / skin.width, v / skin.height], transform); push_box(part.size, low, high, uv, (u, v) => [u / skin.width, v / skin.height], transform, tint);
} }
// a box of a model, from low to high, textured like minecraft's box uv from [u, v] for a box of size (in texture // a box of a model, from low to high, textured like minecraft's box uv from [u, v] for a box of size (in texture
+2
View File
@@ -174,6 +174,8 @@ export type ServerMessage =
| { type: "set_block_item"; x: number; y: number; z: number; item: ItemData | null } | { type: "set_block_item"; x: number; y: number; z: number; item: ItemData | null }
| { type: "chat"; from?: string; text: string } | { type: "chat"; from?: string; text: string }
| { type: "teleport"; x: number; y: number; z: number } | { type: "teleport"; x: number; y: number; z: number }
// the player was knocked back: their speed is this now, in blocks per second
| { type: "set_motion"; vx: number; vy: number; vz: number }
| { type: "container"; container: ContainerKey; items: (ItemData | null)[] } | { type: "container"; container: ContainerKey; items: (ItemData | null)[] }
| { type: "cursor"; item: ItemData | null } | { type: "cursor"; item: ItemData | null }
| { type: "open_screen"; layout: ScreenLayout; properties: Record<string, number> } | { type: "open_screen"; layout: ScreenLayout; properties: Record<string, number> }
+3 -2
View File
@@ -41,8 +41,9 @@ and players. Mods define new kinds in their `entities/` folder, and draw them wi
**Animals** (the default) are mobs: they wander around, panic when hurt, look at players now and then, swim up in water, **Animals** (the default) are mobs: they wander around, panic when hurt, look at players now and then, swim up in water,
and never despawn. They're saved with the world, and players can't place solid blocks where one is standing. and never despawn. They're saved with the world, and players can't place solid blocks where one is standing.
Players hit animals by left clicking them from up to 3 blocks away, for 1 physical damage (half a heart) whatever they Players hit animals, and each other, by left clicking them from up to 3 blocks away, for 1 physical damage (half a
hold. The hit pushes them away, and like any damage it can't hurt them again for half a second unless it's harder. heart) whatever they hold. The hit pushes them away, and like any damage it can't hurt them again for half a second
unless it's harder. See [Players](players.md#health-and-hunger).
**Scripted** entities stay exactly where a script puts them. They don't fall, think or get hurt, and aren't saved with **Scripted** entities stay exactly where a script puts them. They don't fall, think or get hurt, and aren't saved with
the world, so a script never finds one it doesn't know about after a restart. The fishing hook is one: the world, so a script never finds one it doesn't know about after a restart. The fishing hook is one:
+4
View File
@@ -53,6 +53,10 @@ Players follow Minecraft's rules, with 20 health (10 hearts) and 20 hunger:
- **Starving**: at 0 hunger they lose health every 4 seconds, down to half a heart. - **Starving**: at 0 hunger they lose health every 4 seconds, down to half a heart.
- **Falling** hurts 1 per block after the first 3, unless they land in water. - **Falling** hurts 1 per block after the first 3, unless they land in water.
- **The void**: below the world, they keep taking damage until they die. - **The void**: below the world, they keep taking damage until they die.
- **Fighting**: other players and mobs can hit them, which also pushes them away.
Players are living entities, like mobs, so damage works the same for both. After being hurt they can't be hurt again for
half a second, unless the new hit is harder, and then only by the difference.
`damage(amount, cause)` hurts them like anything else would. `cause` shows in the `player_damage` and `player_death` `damage(amount, cause)` hurts them like anything else would. `cause` shows in the `player_damage` and `player_death`
[events](../concepts/events.md) and in the death message. Before events can change the amount or cancel it. [events](../concepts/events.md) and in the death message. Before events can change the amount or cancel it.
+4 -7
View File
@@ -9,6 +9,7 @@ import type { BlockRegistry } from "$/common/everything_registry.ts";
import type { ItemStack } from "$/common/inventory.ts"; import type { ItemStack } from "$/common/inventory.ts";
import { type Collisions, move_body } from "$/common/physics.ts"; import { type Collisions, move_body } from "$/common/physics.ts";
import type { EntityData, EntityInfo } from "$/common/protocol.ts"; import type { EntityData, EntityInfo } from "$/common/protocol.ts";
import type { ServerPlayer } from "../player.ts";
// below this, entities have fallen out of the world // below this, entities have fallen out of the world
export const VOID_Y = -64; export const VOID_Y = -64;
@@ -27,11 +28,6 @@ export interface Attacker {
readonly z: number; readonly z: number;
} }
// a player as entities see them, ServerPlayer is one
export interface PlayerTarget extends Attacker {
readonly name: string;
}
export type DamageType = "physical" | "arcane" | "absolute"; export type DamageType = "physical" | "arcane" | "absolute";
// what hurt something. cause is for mods and death messages, like "fall", "drown" or "mob_attack" // what hurt something. cause is for mods and death messages, like "fall", "drown" or "mob_attack"
@@ -68,8 +64,9 @@ export interface EntityLevel {
get_entity(id: string): Entity | undefined; get_entity(id: string): Entity | undefined;
// entities whose feet are within the box around x, y, z // entities whose feet are within the box around x, y, z
entities_near(x: number, y: number, z: number, radius: number): Entity[]; entities_near(x: number, y: number, z: number, radius: number): Entity[];
nearest_player(x: number, y: number, z: number, max_distance: number): PlayerTarget | undefined; nearest_player(x: number, y: number, z: number, max_distance: number): ServerPlayer | undefined;
damage_player(id: string, amount: number, source: DamageSource): void; // what ServerPlayer.hurt does: mods get a say, then they're hurt. returns whether they were
hurt_player(player: ServerPlayer, amount: number, source: DamageSource): boolean;
spawn_item(x: number, y: number, z: number, stack: ItemStack, pickup_delay?: number): Entity; spawn_item(x: number, y: number, z: number, stack: ItemStack, pickup_delay?: number): Entity;
// an item on the ground was picked up whole by who, clients see it fly to them. it's gone after // an item on the ground was picked up whole by who, clients see it fly to them. it's gone after
take_item(item: Entity, by: string): void; take_item(item: Entity, by: string): void;
+8 -5
View File
@@ -17,7 +17,7 @@ export interface EntityHost {
readonly current_tick: number; readonly current_tick: number;
players(): ServerPlayer[]; players(): ServerPlayer[];
send(player: ServerPlayer, message: ServerMessage): void; send(player: ServerPlayer, message: ServerMessage): void;
damage_player(player: ServerPlayer, amount: number, cause: string): void; hurt_player(player: ServerPlayer, amount: number, source: DamageSource): boolean;
on_entity_death?(entity: Entity, source: DamageSource): void; on_entity_death?(entity: Entity, source: DamageSource): void;
} }
@@ -110,9 +110,8 @@ export class EntityManager implements EntityLevel {
return nearest; return nearest;
} }
damage_player(id: string, amount: number, source: DamageSource) { hurt_player(player: ServerPlayer, amount: number, source: DamageSource) {
const player = this.#host.players().find((player) => player.id === id); return this.#host.hurt_player(player, amount, source);
if (player) this.#host.damage_player(player, amount, source.cause);
} }
spawn_item(x: number, y: number, z: number, stack: ItemStack, pickup_delay = 0): ItemEntity { spawn_item(x: number, y: number, z: number, stack: ItemStack, pickup_delay = 0): ItemEntity {
@@ -131,9 +130,13 @@ export class EntityManager implements EntityLevel {
this.#entities.delete(item.id); this.#entities.delete(item.id);
} }
// players aren't tracked like entities, everyone else knows about them
entity_event(entity: Entity, event: "hurt" | "death") { entity_event(entity: Entity, event: "hurt" | "death") {
const is_player = this.#host.players().includes(entity as ServerPlayer);
for (const [player, tracked] of this.#tracked) { for (const [player, tracked] of this.#tracked) {
if (tracked.has(entity.id)) this.#host.send(player, { type: "entity_event", id: entity.id, event }); if (is_player ? player !== entity : tracked.has(entity.id)) {
this.#host.send(player, { type: "entity_event", id: entity.id, event });
}
} }
} }
+5 -8
View File
@@ -1,10 +1,8 @@
// what mobs decide to do, like minecraft's Goal and GoalSelector. each goal says when it wants to run and which // what mobs decide to do, like minecraft's Goal and GoalSelector. each goal says when it wants to run and which
// controls it needs (its flags), and the most important goals that can run get them. a lower priority number is // controls it needs (its flags), and the most important goals that can run get them. a lower priority number is
// more important, and can take a flag from a less important goal that's running // more important, and can take a flag from a less important goal that's running
import { PLAYER_WIDTH } from "$/common/constants.ts";
import { ATTRIBUTES } from "./attributes.ts"; import { ATTRIBUTES } from "./attributes.ts";
import { Entity, type PlayerTarget } from "./entity.ts"; import type { LivingEntity } from "./living_entity.ts";
import { LivingEntity } from "./living_entity.ts";
import type { Mob } from "./mob.ts"; import type { Mob } from "./mob.ts";
export type GoalFlag = "move" | "look" | "jump" | "target"; export type GoalFlag = "move" | "look" | "jump" | "target";
@@ -196,7 +194,7 @@ export class PanicGoal extends Goal {
// looks at a nearby player for a couple of seconds, now and then // looks at a nearby player for a couple of seconds, now and then
export class LookAtPlayerGoal extends Goal { export class LookAtPlayerGoal extends Goal {
override flags: GoalFlag[] = ["look"]; override flags: GoalFlag[] = ["look"];
#player: PlayerTarget | undefined; #player: LivingEntity | undefined;
#ticks = 0; #ticks = 0;
constructor(readonly mob: Mob, readonly range = 8, readonly probability = 0.02) { constructor(readonly mob: Mob, readonly range = 8, readonly probability = 0.02) {
@@ -291,7 +289,7 @@ export class MeleeAttackGoal extends Goal {
mob.move_control.move_to(target.x, target.y, target.z, this.speed_modifier); mob.move_control.move_to(target.x, target.y, target.z, this.speed_modifier);
this.#cooldown = Math.max(0, this.#cooldown - 1); this.#cooldown = Math.max(0, this.#cooldown - 1);
// minecraft's reach: its width doubled, squared, plus the target's width // minecraft's reach: its width doubled, squared, plus the target's width
const reach = (mob.width * 2) ** 2 + (target instanceof Entity ? target.width : PLAYER_WIDTH); const reach = (mob.width * 2) ** 2 + target.width;
const distance = (target.x - mob.x) ** 2 + (target.y - mob.y) ** 2 + (target.z - mob.z) ** 2; const distance = (target.x - mob.x) ** 2 + (target.y - mob.y) ** 2 + (target.z - mob.z) ** 2;
if (distance <= reach && this.#cooldown === 0) { if (distance <= reach && this.#cooldown === 0) {
this.#cooldown = this.attack_interval; this.#cooldown = this.attack_interval;
@@ -333,9 +331,8 @@ export class NearestAttackablePlayerGoal extends Goal {
} }
} }
// players are always alive to mobs, they respawn straight away function is_alive(target: LivingEntity) {
function is_alive(target: LivingEntity | PlayerTarget) { return target.alive;
return !(target instanceof LivingEntity) || target.alive;
} }
// somewhere random within range it could stand: solid ground under it, room for its box, and inside its home. // somewhere random within range it could stand: solid ground under it, room for its box, and inside its home.
+16
View File
@@ -331,6 +331,22 @@ export abstract class LivingEntity extends Entity {
this.health -= post_mitigation; this.health -= post_mitigation;
} }
// back to full health with nothing left over from before: no effects, fire, hurt cooldown or who hurt it. for
// players respawning, minecraft makes them a new entity instead
revive() {
this.clear_effects();
this.health = this.max_health;
this.fire = 0;
this.air = this.max_air;
this.fall_distance = 0;
this.vx = this.vy = this.vz = 0;
this.hurt_time = this.death_time = 0;
this.#hurt_cooldown = 0;
this.#last_hurt_amount = 0;
this.last_hurt_by_mob = this.last_hurt_by_player = undefined;
this.ticks_since_last_hurt_by_mob = this.last_hurt_by_player_memory_time = 0;
}
// it was just hurt, for kinds that react // it was just hurt, for kinds that react
on_hurt(_source: DamageSource) {} on_hurt(_source: DamageSource) {}
+3 -7
View File
@@ -1,7 +1,7 @@
// living entities with a mind of their own, like minecraft's Mob: goals decide what to do (see goals.ts) and // living entities with a mind of their own, like minecraft's Mob: goals decide what to do (see goals.ts) and
// controls turn that into walking, looking and jumping. they can despawn, pick up items and be kept near a home // controls turn that into walking, looking and jumping. they can despawn, pick up items and be kept near a home
import { ATTRIBUTES, type AttributeType } from "./attributes.ts"; import { ATTRIBUTES, type AttributeType } from "./attributes.ts";
import { type DamageSource, Entity, finite, type PlayerTarget } from "./entity.ts"; import { type DamageSource, Entity, finite } from "./entity.ts";
import { GoalSelector } from "./goals.ts"; import { GoalSelector } from "./goals.ts";
import { ItemEntity } from "./item_entity.ts"; import { ItemEntity } from "./item_entity.ts";
import { EQUIPMENT_SLOTS, type EquipmentSlot, LivingEntity, type SavedLivingEntity } from "./living_entity.ts"; import { EQUIPMENT_SLOTS, type EquipmentSlot, LivingEntity, type SavedLivingEntity } from "./living_entity.ts";
@@ -56,7 +56,7 @@ export abstract class Mob extends LivingEntity {
goals = new GoalSelector(); goals = new GoalSelector();
target_goals = new GoalSelector(); target_goals = new GoalSelector();
// who it's after, set by target goals // who it's after, set by target goals
target: LivingEntity | PlayerTarget | undefined; target: LivingEntity | undefined;
move_control = new MoveControl(this); move_control = new MoveControl(this);
look_control = new LookControl(this); look_control = new LookControl(this);
@@ -165,13 +165,9 @@ export abstract class Mob extends LivingEntity {
// fighting // fighting
// hits whoever it's attacking with its attack damage, like minecraft's doHurtTarget. returns whether it hurt them // hits whoever it's attacking with its attack damage, like minecraft's doHurtTarget. returns whether it hurt them
do_hurt_target(target: Entity | PlayerTarget): boolean { do_hurt_target(target: Entity): boolean {
const damage = this.attribute(ATTRIBUTES.attack_damage); const damage = this.attribute(ATTRIBUTES.attack_damage);
const source = { cause: "mob_attack", attacker: this, type: "physical" } as const; const source = { cause: "mob_attack", attacker: this, type: "physical" } as const;
if (!(target instanceof Entity)) {
this.level.damage_player(target.id, damage, source);
return true;
}
if (!(target instanceof LivingEntity)) return false; if (!(target instanceof LivingEntity)) return false;
if (!target.hurt(damage, source)) return false; if (!target.hurt(damage, source)) return false;
const knockback = this.attribute(ATTRIBUTES.attack_knockback); const knockback = this.attribute(ATTRIBUTES.attack_knockback);
+60 -41
View File
@@ -44,7 +44,7 @@ import {
placement_target, placement_target,
set_state_value, set_state_value,
} from "$/common/utils.ts"; } from "$/common/utils.ts";
import { EXHAUSTION, MAX_HEALTH } from "./vitals.ts"; import { EXHAUSTION } from "./vitals.ts";
import { ModRuntime, run_guarded, type ServerCommandSource } from "./mod_runtime.ts"; import { ModRuntime, run_guarded, type ServerCommandSource } from "./mod_runtime.ts";
import { import {
argument, argument,
@@ -75,12 +75,11 @@ import { Mob } from "./entity/mob.ts";
import { LivingEntity } from "./entity/living_entity.ts"; import { LivingEntity } from "./entity/living_entity.ts";
import { EntityManager } from "./entity/entity_manager.ts"; import { EntityManager } from "./entity/entity_manager.ts";
import { create_entity, entity_type_ids } from "./entity/entity_types.ts"; import { create_entity, entity_type_ids } from "./entity/entity_types.ts";
import type { SavedEntity } from "./entity/entity.ts"; import { DAMAGE, type DamageSource, type SavedEntity } from "./entity/entity.ts";
import { ATTRIBUTES } from "./entity/attributes.ts";
// how far from a player's eyes a block can be changed, a bit more than the client's reach // how far from a player's eyes a block can be changed, a bit more than the client's reach
const MAX_REACH = 8; const MAX_REACH = 8;
// how hard a player hits with their fist, whatever they're holding. half a heart, like minecraft
const PLAYER_ATTACK_DAMAGE = 1;
// how far past a player's box items get picked up from, sideways and up or down, like minecraft // how far past a player's box items get picked up from, sideways and up or down, like minecraft
const PICKUP_REACH_XZ = 1; const PICKUP_REACH_XZ = 1;
const PICKUP_REACH_Y = 0.5; const PICKUP_REACH_Y = 0.5;
@@ -97,10 +96,6 @@ const SPRINT_SPEED = 5;
const TELEPORT_DISTANCE = 20; const TELEPORT_DISTANCE = 20;
// how close feet have to be to a block's top to stand on it // how close feet have to be to a block's top to stand on it
const GROUND_EPSILON = 0.02; 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 // the most mornings run at once after time jumps forward, the rest are skipped
const MAX_CATCH_UP_DAYS = 64; const MAX_CATCH_UP_DAYS = 64;
// how long a client gets between welcome and ready to download and load everything // how long a client gets between welcome and ready to download and load everything
@@ -206,7 +201,10 @@ export class GameServer {
}, },
players: () => this.players(), players: () => this.players(),
send: (player, message) => this.#send(player, message), send: (player, message) => this.#send(player, message),
damage_player: (player, amount, cause) => this.damage_player(player, amount, cause), hurt_player: (player, amount, source) => this.hurt_player(player, amount, source),
on_entity_death: (entity, source) => {
if (entity instanceof ServerPlayer) this.#kill(entity, source);
},
}); });
this.mods.storage = saved?.mod_storage ?? {}; this.mods.storage = saved?.mod_storage ?? {};
if (saved) { if (saved) {
@@ -271,9 +269,11 @@ export class GameServer {
return; return;
} }
this.#close_screen(player); this.#close_screen(player);
this.#saved_players[player.name] = player.save(); this.#saved_players[player.name] = player.save_player();
this.world.dirty = true; this.world.dirty = true;
this.#players.delete(conn); this.#players.delete(conn);
// mobs after them give up
player.remove();
this.entities.stop_tracking(player); this.entities.stop_tracking(player);
this.mods.after.player_leave.emit({ player: this.mods.player(player) }); this.mods.after.player_leave.emit({ player: this.mods.player(player) });
this.#broadcast({ type: "player_leave", id: player.id }); this.#broadcast({ type: "player_leave", id: player.id });
@@ -358,7 +358,7 @@ export class GameServer {
// level.json and the chunks changed since the last save // level.json and the chunks changed since the last save
save(): Required<WorldSave> { save(): Required<WorldSave> {
for (const player of this.#players.values()) { for (const player of this.#players.values()) {
this.#saved_players[player.name] = player.save(); this.#saved_players[player.name] = player.save_player();
} }
const level: SavedLevel = { const level: SavedLevel = {
version: 5, version: 5,
@@ -672,10 +672,10 @@ export class GameServer {
} }
#join(conn: number, raw_name: unknown, view_distance: number) { #join(conn: number, raw_name: unknown, view_distance: number) {
const player = new ServerPlayer(conn, this.#unique_name(raw_name), view_distance); const player = new ServerPlayer(this.entities, conn, this.#unique_name(raw_name), view_distance);
const saved = this.#saved_players[player.name]; const saved = this.#saved_players[player.name];
if (saved) { if (saved) {
player.load(saved); player.load_player(saved);
} else { } else {
Object.assign(player, this.world.spawn_point()); Object.assign(player, this.world.spawn_point());
} }
@@ -684,7 +684,7 @@ export class GameServer {
type: "join", type: "join",
id: player.id, id: player.id,
name: player.name, name: player.name,
players: [...this.#players.values()].map((p) => p.info()), players: [...this.#players.values()].map((p) => p.player_info()),
entities: this.entities.start_tracking(player), entities: this.entities.start_tracking(player),
blocks: this.world.block_table(), blocks: this.world.block_table(),
spawn: { x: player.x, y: player.y, z: player.z, yaw: player.yaw, pitch: player.pitch }, spawn: { x: player.x, y: player.y, z: player.z, yaw: player.yaw, pitch: player.pitch },
@@ -696,7 +696,7 @@ export class GameServer {
this.#update_view(player); this.#update_view(player);
this.#sync(player); this.#sync(player);
this.#broadcast({ type: "player_join", player: player.info() }, player); this.#broadcast({ type: "player_join", player: player.player_info() }, player);
this.#broadcast({ type: "chat", text: `${player.name} joined` }); this.#broadcast({ type: "chat", text: `${player.name} joined` });
this.mods.after.player_join.emit({ player: this.mods.player(player) }); this.mods.after.player_join.emit({ player: this.mods.player(player) });
console.log(`${player.name} joined (${this.#players.size} online)`); console.log(`${player.name} joined (${this.#players.size} online)`);
@@ -813,14 +813,18 @@ export class GameServer {
} }
} }
// left click on an entity: hurts it and pushes it away. it can't be hurt again for a moment, see LivingEntity.hurt // left click on an entity or another player: hurts them with the player's attack_damage and pushes them away.
// they can't be hurt again for a moment, see LivingEntity.hurt
#attack_entity(player: ServerPlayer, id: string) { #attack_entity(player: ServerPlayer, id: string) {
const entity = this.entities.get_entity(id); const entity = this.entities.get_entity(id) ?? this.players().find((other) => other.id === id);
if (!(entity instanceof LivingEntity) || !entity.alive || !this.#entity_in_reach(player, entity)) { if (
!(entity instanceof LivingEntity) || entity === player || !entity.alive || !player.alive ||
!this.#entity_in_reach(player, entity)
) {
return; return;
} }
const source = { type: "physical", cause: "player_attack", attacker: player, by_player: true } as const; const source = { type: "physical", cause: "player_attack", attacker: player, by_player: true } as const;
if (entity.hurt(PLAYER_ATTACK_DAMAGE, source)) { if (entity.hurt(player.attribute(ATTRIBUTES.attack_damage), source)) {
player.vitals.add_exhaustion(EXHAUSTION.attack); player.vitals.add_exhaustion(EXHAUSTION.attack);
} }
} }
@@ -1330,31 +1334,32 @@ export class GameServer {
// hurts a player, killing them at 0. cause is for mods and the death message, like "fall" // 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) { damage_player(player: ServerPlayer, amount: number, cause: string) {
if (amount <= 0 || player.vitals.health <= 0) { const known: Record<string, DamageSource> = DAMAGE;
return; player.hurt(amount, known[cause] ?? { cause, type: "physical" });
}
// everything that hurts a player ends up here, see ServerPlayer.hurt. mods can change or cancel it first
hurt_player(player: ServerPlayer, amount: number, source: DamageSource): boolean {
if (player.is_invulnerable_to(source) || !player.alive || !(amount > 0)) {
return false;
} }
const before = { player: this.mods.player(player), amount, cause, cancel: false }; const before = { player: this.mods.player(player), amount, cause: source.cause, cancel: false };
this.mods.before.player_damage.emit(before); this.mods.before.player_damage.emit(before);
const final = Number(before.amount); const final = Number(before.amount);
if (before.cancel || !(final > 0)) { if (before.cancel || !(final > 0)) {
return; return false;
}
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);
} }
return player.apply_hurt(final, source);
} }
heal_player(player: ServerPlayer, amount: number) { heal_player(player: ServerPlayer, amount: number) {
if (amount > 0 && player.vitals.health > 0) { player.heal(amount);
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. tools lose 1 // like minecraft: everything they carried falls out where they died, and they start over at spawn. tools lose 1
// durability first, and ones that run out break instead of dropping // durability first, and ones that run out break instead of dropping
#kill(player: ServerPlayer, cause: string) { #kill(player: ServerPlayer, source: DamageSource) {
const cause = source.cause;
const { x, y, z } = player; const { x, y, z } = player;
this.close_screen(player); this.close_screen(player);
for (let i = 0; i < player.inventory.size; i++) { for (let i = 0; i < player.inventory.size; i++) {
@@ -1366,8 +1371,9 @@ export class GameServer {
} }
} }
this.mods.after.player_death.emit({ player: this.mods.player(player), cause }); this.mods.after.player_death.emit({ player: this.mods.player(player), cause });
this.#broadcast({ type: "chat", text: death_message(player.name, cause) }); this.#broadcast({ type: "chat", text: death_message(player.name, source) });
player.vitals.reset(); player.vitals.reset();
player.revive();
const spawn = this.world.spawn_point(); const spawn = this.world.spawn_point();
this.teleport(player, spawn.x, spawn.y, spawn.z); this.teleport(player, spawn.x, spawn.y, spawn.z);
this.world.dirty = true; this.world.dirty = true;
@@ -1375,14 +1381,13 @@ export class GameServer {
#tick_vitals() { #tick_vitals() {
for (const player of this.#players.values()) { for (const player of this.#players.values()) {
// burning, effects, and falling out of the world
player.tick();
player.vitals.tick( player.vitals.tick(
player.health,
(amount) => this.heal_player(player, amount), (amount) => this.heal_player(player, amount),
(amount) => this.damage_player(player, amount, "starve"), (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");
}
} }
} }
@@ -1416,7 +1421,9 @@ export class GameServer {
if (dy < 0 && !in_liquid) { if (dy < 0 && !in_liquid) {
player.fall_distance -= dy; player.fall_distance -= dy;
} }
if (this.#on_ground(x, y, z)) { // knockback only lifts them off the ground
player.on_ground = this.#on_ground(x, y, z);
if (player.on_ground) {
const damage = Math.ceil(player.fall_distance - SAFE_FALL); const damage = Math.ceil(player.fall_distance - SAFE_FALL);
player.fall_distance = 0; player.fall_distance = 0;
if (damage > 0) { if (damage > 0) {
@@ -1523,6 +1530,13 @@ export class GameServer {
} }
}; };
// knockback, their client moves them
const motion = player.take_motion();
if (motion) {
const [vx, vy, vz] = motion;
this.#send(player, { type: "set_motion", vx, vy, vz });
}
// with lore, so it's resent when only the lore changed // with lore, so it's resent when only the lore changed
const inventory = player.inventory.to_synced_data(); const inventory = player.inventory.to_synced_data();
sync("inventory", inventory, () => ({ type: "container", container: "inventory", items: inventory })); sync("inventory", inventory, () => ({ type: "container", container: "inventory", items: inventory }));
@@ -1531,7 +1545,8 @@ export class GameServer {
const cursor = player.cursor.item?.to_synced_data() ?? null; const cursor = player.cursor.item?.to_synced_data() ?? null;
sync("cursor", cursor, () => ({ type: "cursor", item: cursor })); sync("cursor", cursor, () => ({ type: "cursor", item: cursor }));
const { health, food, saturation } = player.vitals; const { food, saturation } = player.vitals;
const health = player.health;
sync("vitals", [health, food, saturation], () => ({ type: "vitals", health, food, saturation })); sync("vitals", [health, food, saturation], () => ({ type: "vitals", health, food, saturation }));
if (player.screen) { if (player.screen) {
@@ -1708,8 +1723,12 @@ function upgrade_v4_entities(entities: SavedLevelV4["entities"]): SavedEntity[]
} }
// what everyone's told when someone dies // what everyone's told when someone dies
function death_message(name: string, cause: string) { function death_message(name: string, source: DamageSource) {
switch (cause) { switch (source.cause) {
case "player_attack":
return source.attacker instanceof ServerPlayer
? `${name} was slain by ${source.attacker.name}`
: `${name} died`;
case "fall": case "fall":
return `${name} hit the ground too hard`; return `${name} hit the ground too hard`;
case "void": case "void":
+1 -1
View File
@@ -782,7 +782,7 @@ function player_api(game: GameServer, player: ServerPlayer): Player {
game.teleport(player, x, y, z); game.teleport(player, x, y, z);
}, },
get health() { get health() {
return player.vitals.health; return player.health;
}, },
max_health: MAX_HEALTH, max_health: MAX_HEALTH,
get food() { get food() {
+77 -15
View File
@@ -1,7 +1,11 @@
import { PLAYER_EYE_HEIGHT, PLAYER_HEIGHT, PLAYER_WIDTH } from "$/common/constants.ts";
import { Container, Cursor, ItemData, ItemStack } from "$/common/inventory.ts"; import { Container, Cursor, ItemData, ItemStack } from "$/common/inventory.ts";
import { PlayerInfo, ScreenLayout } from "$/common/protocol.ts"; import { PlayerInfo, ScreenLayout } from "$/common/protocol.ts";
import { type SavedVitals, Vitals } from "./vitals.ts"; import { EXHAUSTION, type SavedVitals, Vitals } from "./vitals.ts";
import { PlayerChunks } from "./player_chunks.ts"; import { PlayerChunks } from "./player_chunks.ts";
import { ATTRIBUTES, type AttributeType } from "./entity/attributes.ts";
import type { DamageSource, EntityLevel } from "./entity/entity.ts";
import { LivingEntity } from "./entity/living_entity.ts";
export const INVENTORY_SIZE = 9 * 4; export const INVENTORY_SIZE = 9 * 4;
export const CRAFTING_SIZE = 10; export const CRAFTING_SIZE = 10;
@@ -35,21 +39,22 @@ export interface SavedPlayer {
slim?: boolean; slim?: boolean;
} }
export class ServerPlayer { // a player is a living entity, like minecraft's Player: they have health, can be hurt and pushed around by mobs and
// other players, and have effects. their client moves them though, so they don't walk, fall or think here. they're
// kept apart from the entity manager's entities, clients hear about players through their own messages
export class ServerPlayer extends LivingEntity {
readonly type = "bworld:player";
readonly conn: number; readonly conn: number;
readonly id = crypto.randomUUID();
readonly name: string; readonly name: string;
x = 0; override y = 100;
y = 100; override width = PLAYER_WIDTH;
z = 0; override height = PLAYER_HEIGHT;
yaw = 0; override eye_height = PLAYER_EYE_HEIGHT;
pitch = 0;
inventory = new Container(INVENTORY_SIZE); inventory = new Container(INVENTORY_SIZE);
// hunger and saturation, health is the entity's
vitals = new Vitals(); 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 // when the last move came, to tell walking from sprinting
last_move_tick = 0; last_move_tick = 0;
crafting = new Container(CRAFTING_SIZE); crafting = new Container(CRAFTING_SIZE);
@@ -68,17 +73,73 @@ export class ServerPlayer {
// the chunks their client has and still needs // the chunks their client has and still needs
chunks: PlayerChunks; chunks: PlayerChunks;
constructor(conn: number, name: string, view_distance: number) { constructor(level: EntityLevel, conn: number, name: string, view_distance: number) {
super(level);
this.conn = conn; this.conn = conn;
this.name = name; this.name = name;
this.chunks = new PlayerChunks(view_distance); this.chunks = new PlayerChunks(view_distance);
} }
override default_attributes(): [AttributeType, number?][] {
return [
...super.default_attributes(),
// a fist does half a heart, like minecraft
[ATTRIBUTES.attack_damage, 1],
[ATTRIBUTES.physical_shielding],
[ATTRIBUTES.arcane_shielding],
];
}
// they're saved by name with the players, not with the world's entities
override get persistent() {
return false;
}
// there's no air bar to show yet, so players don't drown
override get can_breathe_underwater() {
return true;
}
// their client moves them, this only burns, falls out of the world and counts effects and hurt time down
override tick() {
this.base_tick();
if (!this.dead) {
this.tick_effects();
}
}
// everything that hurts a player goes through the game server first, which lets mods change or cancel it
override hurt(amount: number, source: DamageSource): boolean {
return this.level.hurt_player(this, amount, source);
}
// hurts them for real, once mods have had their say
apply_hurt(amount: number, source: DamageSource): boolean {
return super.hurt(amount, source);
}
override on_hurt(_source: DamageSource) {
this.vitals.add_exhaustion(EXHAUSTION.damage);
}
// they don't drop loot or fall over, the game server drops what they carry and respawns them
override die(source: DamageSource) {
this.level.on_death(this, source);
}
// knockback is how fast their client should move them, sent with the next sync and cleared
take_motion(): [number, number, number] | undefined {
if (!this.vx && !this.vy && !this.vz) return undefined;
const motion: [number, number, number] = [this.vx, this.vy, this.vz];
this.vx = this.vy = this.vz = 0;
return motion;
}
get held_item(): ItemStack | undefined { get held_item(): ItemStack | undefined {
return this.inventory.get_item(this.selected_slot); return this.inventory.get_item(this.selected_slot);
} }
info(): PlayerInfo { player_info(): PlayerInfo {
return { return {
id: this.id, id: this.id,
name: this.name, name: this.name,
@@ -92,7 +153,7 @@ export class ServerPlayer {
}; };
} }
save(): SavedPlayer { save_player(): SavedPlayer {
return { return {
x: this.x, x: this.x,
y: this.y, y: this.y,
@@ -101,13 +162,13 @@ export class ServerPlayer {
pitch: this.pitch, pitch: this.pitch,
selected_slot: this.selected_slot, selected_slot: this.selected_slot,
inventory: this.inventory.to_data(), inventory: this.inventory.to_data(),
vitals: this.vitals.save(), vitals: { health: this.health, ...this.vitals.save() },
skin: this.skin, skin: this.skin,
slim: this.slim || undefined, slim: this.slim || undefined,
}; };
} }
load(saved: SavedPlayer) { load_player(saved: SavedPlayer) {
this.x = saved.x; this.x = saved.x;
this.y = saved.y; this.y = saved.y;
this.z = saved.z; this.z = saved.z;
@@ -116,6 +177,7 @@ export class ServerPlayer {
this.selected_slot = saved.selected_slot; this.selected_slot = saved.selected_slot;
this.inventory.load(saved.inventory); this.inventory.load(saved.inventory);
this.vitals.load(saved.vitals); this.vitals.load(saved.vitals);
this.health = saved.vitals?.health ?? this.max_health;
this.skin = saved.skin; this.skin = saved.skin;
this.slim = saved.slim ?? false; this.slim = saved.slim ?? false;
} }
+10 -11
View File
@@ -1,5 +1,5 @@
// a player's health, hunger and saturation, with minecraft's rules (its FoodData). the server owns them, clients only // a player's hunger and saturation, with minecraft's rules (its FoodData), and what they do to health. the server
// draw them // owns them, clients only draw them
import { TICKS_PER_SECOND } from "$/common/constants.ts"; import { TICKS_PER_SECOND } from "$/common/constants.ts";
export const MAX_HEALTH = 20; export const MAX_HEALTH = 20;
@@ -37,7 +37,6 @@ export interface SavedVitals {
} }
export class Vitals { export class Vitals {
health = MAX_HEALTH;
food = MAX_FOOD; food = MAX_FOOD;
saturation = START_SATURATION; saturation = START_SATURATION;
exhaustion = 0; exhaustion = 0;
@@ -57,8 +56,9 @@ export class Vitals {
return this.food < MAX_FOOD; return this.food < MAX_FOOD;
} }
// one tick. heal and hurt go through the game server, which fires events and handles dying // one tick, for someone with that much health. heal and hurt go through the game server, which fires events and
tick(heal: (amount: number) => void, hurt: (amount: number) => void) { // handles dying
tick(health: number, heal: (amount: number) => void, hurt: (amount: number) => void) {
if (this.exhaustion > EXHAUSTION_PER_POINT) { if (this.exhaustion > EXHAUSTION_PER_POINT) {
this.exhaustion -= EXHAUSTION_PER_POINT; this.exhaustion -= EXHAUSTION_PER_POINT;
if (this.saturation > 0) { if (this.saturation > 0) {
@@ -68,7 +68,7 @@ export class Vitals {
} }
} }
const hurt_some = this.health < MAX_HEALTH; const hurt_some = health < MAX_HEALTH;
if (this.saturation > 0 && hurt_some && this.food >= MAX_FOOD) { if (this.saturation > 0 && hurt_some && this.food >= MAX_FOOD) {
if (++this.#timer >= FAST_REGEN_TICKS) { if (++this.#timer >= FAST_REGEN_TICKS) {
const amount = Math.min(this.saturation, 6); const amount = Math.min(this.saturation, 6);
@@ -84,7 +84,7 @@ export class Vitals {
} }
} else if (this.food <= 0) { } else if (this.food <= 0) {
if (++this.#timer >= STARVE_TICKS) { if (++this.#timer >= STARVE_TICKS) {
if (this.health > STARVE_MIN_HEALTH) hurt(1); if (health > STARVE_MIN_HEALTH) hurt(1);
this.#timer = 0; this.#timer = 0;
} }
} else { } else {
@@ -93,20 +93,19 @@ export class Vitals {
} }
reset() { reset() {
this.health = MAX_HEALTH;
this.food = MAX_FOOD; this.food = MAX_FOOD;
this.saturation = START_SATURATION; this.saturation = START_SATURATION;
this.exhaustion = 0; this.exhaustion = 0;
this.#timer = 0; this.#timer = 0;
} }
save(): SavedVitals { // health is the player's, they add it
return { health: this.health, food: this.food, saturation: this.saturation, exhaustion: this.exhaustion }; save(): Omit<SavedVitals, "health"> {
return { food: this.food, saturation: this.saturation, exhaustion: this.exhaustion };
} }
load(saved: SavedVitals | undefined) { load(saved: SavedVitals | undefined) {
if (!saved) return; if (!saved) return;
this.health = saved.health;
this.food = saved.food; this.food = saved.food;
this.saturation = saved.saturation; this.saturation = saved.saturation;
this.exhaustion = saved.exhaustion; this.exhaustion = saved.exhaustion;
+17
View File
@@ -0,0 +1,17 @@
import { test_game } from "../helpers.ts";
Deno.test("kb", async () => {
const t = await test_game("mods");
t.join(1, "alice");
t.join(2, "bob");
for (let x = -8; x <= 8; x++) for (let z = -8; z <= 8; z++) t.game.set_block(x, 99, z, "bworld:stone");
t.send(1, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0 });
t.send(2, { type: "move", x: 0.5, y: 100, z: 2.5, yaw: 0, pitch: 0 });
t.game.tick();
t.take(2);
const bob = t.game.players()[1];
console.log("on_ground", bob.on_ground);
t.send(1, { type: "attack_entity", id: bob.id });
console.log("v after hurt", bob.vx, bob.vy, bob.vz, "health", bob.health);
t.game.tick();
console.log(t.take(2).filter((m) => m.type === "set_motion"));
});
+1 -1
View File
@@ -172,7 +172,7 @@ Deno.test("a stove is placed lit and heats the pot, coal relights it, and standi
// standing on it: 1 every 10 ticks // standing on it: 1 every 10 ticks
t.game.destroy_block(...POT); t.game.destroy_block(...POT);
t.send(1, { type: "move", x: 0.5, y: 101, z: 0.5, yaw: 0, pitch: 0 }); t.send(1, { type: "move", x: 0.5, y: 101, z: 0.5, yaw: 0, pitch: 0 });
const health = () => t.game.players()[0].vitals.health; const health = () => t.game.players()[0].health;
// (full hunger heals some of it back meanwhile, like minecraft) // (full hunger heals some of it back meanwhile, like minecraft)
const before = health(); const before = health();
t.ticks(40); t.ticks(40);
+47
View File
@@ -161,6 +161,53 @@ Deno.test("players hit entities they can reach, pushing them away", async () =>
send(1, { type: "attack_entity", id: "nothing" }); send(1, { type: "attack_entity", id: "nothing" });
}); });
Deno.test("players hit each other, knocking them back and flashing red for everyone else", async () => {
const { game, ticks, send, join, take } = await floor_game();
join(2, "bob");
send(2, { type: "move", x: 0.5, y: 100, z: 2.5, yaw: 0, pitch: 0 });
const [alice, bob] = game.players();
ticks(1);
take(1);
take(2);
send(1, { type: "attack_entity", id: bob.id });
assertEquals(bob.health, 19);
ticks(1);
const motion = take(2).find((m) => m.type === "set_motion");
assert(motion && motion.vz > 0, "bob's client is told he's knocked back, away from alice");
assert(take(1).some((m) => m.type === "entity_event" && m.id === bob.id && m.event === "hurt"));
send(1, { type: "attack_entity", id: alice.id });
assertEquals(alice.health, 20, "not yourself");
// past the hurt cooldown, and whatever full hunger healed back
ticks(20);
bob.health = 1;
send(1, { type: "attack_entity", id: bob.id });
assert(take(1).some((m) => m.type === "chat" && m.text === "bob was slain by alice"));
assertEquals(bob.health, 20, "respawned");
send(1, { type: "attack_entity", id: bob.id });
assertEquals(bob.health, 20, "too far away now, back at spawn");
});
Deno.test("mobs hurt players like anything else, and mods still get a say", async () => {
const { game, spawn, ticks } = await floor_game();
const alice = game.players()[0];
const causes: string[] = [];
game.mods.before.player_damage.for_mod("test").subscribe((event) => causes.push(event.cause));
const mob = spawn(0.5, 100, 1.5);
ticks(1);
assert(mob.do_hurt_target(alice));
assertEquals(alice.health, 18);
assertEquals(causes, ["mob_attack"]);
assertEquals(alice.last_hurt_by_mob, mob.id);
assertEquals(mob.do_hurt_target(alice), false, "not again straight away");
game.on_disconnect(1);
assertEquals(alice.alive, false, "gone, so mobs after her give up");
});
Deno.test("dying: it drops what it had, falls over for a second and is gone", async () => { Deno.test("dying: it drops what it had, falls over for a second and is gone", async () => {
const { game, spawn, take, ticks } = await floor_game(); const { game, spawn, take, ticks } = await floor_game();
const mob = spawn(0.5, 100, 2.5); const mob = spawn(0.5, 100, 2.5);
+15 -17
View File
@@ -12,12 +12,12 @@ Deno.test("exhaustion eats saturation first, then hunger", () => {
const vitals = new Vitals(); const vitals = new Vitals();
const noop = () => {}; const noop = () => {};
vitals.add_exhaustion(4.1); vitals.add_exhaustion(4.1);
vitals.tick(noop, noop); vitals.tick(20, noop, noop);
assertEquals([vitals.food, vitals.saturation], [20, 4]); assertEquals([vitals.food, vitals.saturation], [20, 4]);
vitals.saturation = 0; vitals.saturation = 0;
vitals.add_exhaustion(4); vitals.add_exhaustion(4);
vitals.tick(noop, noop); vitals.tick(20, noop, noop);
assertEquals([vitals.food, vitals.saturation], [19, 0]); assertEquals([vitals.food, vitals.saturation], [19, 0]);
}); });
@@ -29,29 +29,27 @@ Deno.test("a full stomach heals, fast with saturation and slowly without, and st
// full hunger and saturation: every 10 ticks, up to a whole heart, paid for with exhaustion // full hunger and saturation: every 10 ticks, up to a whole heart, paid for with exhaustion
const fast = new Vitals(); const fast = new Vitals();
fast.health = 10; for (let i = 0; i < 10; i++) fast.tick(10, heal, damage);
for (let i = 0; i < 10; i++) fast.tick(heal, damage);
assertAlmostEquals(healed, 5 / 6); assertAlmostEquals(healed, 5 / 6);
assertEquals(fast.exhaustion, 5); assertEquals(fast.exhaustion, 5);
// 18 hunger and no saturation: 1 every 4 seconds // 18 hunger and no saturation: 1 every 4 seconds
healed = 0; healed = 0;
const slow = new Vitals(); const slow = new Vitals();
slow.health = 10;
slow.food = 18; slow.food = 18;
slow.saturation = 0; slow.saturation = 0;
for (let i = 0; i < 80; i++) slow.tick(heal, damage); for (let i = 0; i < 80; i++) slow.tick(10, heal, damage);
assertEquals(healed, 1); assertEquals(healed, 1);
// starving: 1 every 4 seconds, never below 1 health // starving: 1 every 4 seconds, never below 1 health
const starving = new Vitals(); const starving = new Vitals();
starving.food = 0; starving.food = 0;
starving.saturation = 0; starving.saturation = 0;
starving.health = 2; let health = 2;
for (let i = 0; i < 80; i++) starving.tick(heal, (amount) => starving.health -= amount); for (let i = 0; i < 80; i++) starving.tick(health, heal, (amount) => health -= amount);
assertEquals(starving.health, 1); assertEquals(health, 1);
for (let i = 0; i < 400; i++) starving.tick(heal, (amount) => starving.health -= amount); for (let i = 0; i < 400; i++) starving.tick(health, heal, (amount) => health -= amount);
assertEquals(starving.health, 1); assertEquals(health, 1);
assertEquals(hurt, 0); assertEquals(hurt, 0);
}); });
@@ -84,20 +82,20 @@ Deno.test("falling more than 3 blocks hurts, 1 per block after that, and water b
// up 10 blocks, then down in steps like a fall // up 10 blocks, then down in steps like a fall
t.move(110); t.move(110);
for (let y = 109; y >= 100; y--) t.move(y); for (let y = 109; y >= 100; y--) t.move(y);
assertEquals(t.player.vitals.health, MAX_HEALTH - 7); assertEquals(t.player.health, MAX_HEALTH - 7);
// the same fall into water // the same fall into water
t.player.vitals.health = MAX_HEALTH; t.player.health = MAX_HEALTH;
t.game.set_block(0, 100, 0, "bworld:water"); t.game.set_block(0, 100, 0, "bworld:water");
t.move(110); t.move(110);
for (let y = 109; y >= 100; y--) t.move(y); for (let y = 109; y >= 100; y--) t.move(y);
assertEquals(t.player.vitals.health, MAX_HEALTH); assertEquals(t.player.health, MAX_HEALTH);
}); });
Deno.test("health and hunger are sent to the player when they change, and saved", async () => { Deno.test("health and hunger are sent to the player when they change, and saved", async () => {
const t = await setup(); const t = await setup();
t.take(1); t.take(1);
t.player.vitals.health = 15; t.player.health = 15;
t.player.vitals.food = 12; t.player.vitals.food = 12;
t.game.tick(); t.game.tick();
const vitals = t.take(1).filter((m) => m.type === "vitals").at(-1); const vitals = t.take(1).filter((m) => m.type === "vitals").at(-1);
@@ -108,7 +106,7 @@ Deno.test("health and hunger are sent to the player when they change, and saved"
t.game.on_disconnect(1); t.game.on_disconnect(1);
const loaded = await test_game("mods", t.game.save()); const loaded = await test_game("mods", t.game.save());
loaded.join(1, "alice"); loaded.join(1, "alice");
assertEquals(loaded.game.players()[0].vitals.health, 15); assertEquals(loaded.game.players()[0].health, 15);
assertEquals(loaded.game.players()[0].vitals.food, 12); assertEquals(loaded.game.players()[0].vitals.food, 12);
}); });
@@ -144,7 +142,7 @@ Deno.test("dying drops everything, tells everyone, and respawns with full health
assertEquals(deaths, ["alice fall"]); 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 === "chat" && m.text === "alice hit the ground too hard"));
assert(messages.some((m: Msg) => m.type === "teleport")); assert(messages.some((m: Msg) => m.type === "teleport"));
assertEquals([t.player.vitals.health, t.player.vitals.food], [MAX_HEALTH, 20]); assertEquals([t.player.health, t.player.vitals.food], [MAX_HEALTH, 20]);
assert(t.player.inventory.to_data().every((i) => i === null)); 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 }]); assertEquals(t.game.item_entities().map((e) => e.item.to_data()), [{ id: "bworld:coal", count: 5 }]);
}); });