Something went wrong. Try again.
A Social Deduction / Deception Game
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464// ---------------------------------------------------------------------------// Decorative NPCs — set dressing (PLAN §9), built on the entity layer. They do// NOT block movement and are never on the wire; each client animates its own.// An NPC is defined by a bag of *weights* + an actor spritesheet (as clips), and// flips between three behaviours on PRN-driven timers://// • idle — stand, facing a direction// • spin — turn in place, cycling facing (no translation)// • wander — walk to a random point inside its leashed area//// The state-transition choice is a parameterized function (`NpcPolicy`); the// default {@link weightedPolicy} just samples the def's weights, and a game can// pass its own. Randomness comes from an injectable `rng` (pass a seeded// {@link mulberry32} for reproducibility) — "PRN driven".//// Yielding: an NPC near a player drifts directly away ("gets out of the way").// This is cosmetic and one-directional — NPCs avoid players, players never route// around NPCs — so it stays off the authoritative engine (PLAN §9).// ---------------------------------------------------------------------------
import { Text, type Container } from 'pixi.js'import { findFreeSpot } from './collision'import type { Rect } from './contract'import type { Clip, Entity, EntityLayer, Facing } from './entity'
// directions tried, in radians offset from "straight away", when dodging a// player: straight back first, then fanning sideways, then toward the player as// a last resort (so a cornered NPC still slides out).const DRIFT_FAN = [0, 0.5, -0.5, 1.0, -1.0, 1.6, -1.6, Math.PI]
// Emote bubble (the NPC's `emoji` popping above its head): cosmetic, like the// rest of the NPC. Lives in a world-space overlay (NOT a child of the sprite, so// it isn't scaled down with a small critter), drawn above everything.const EMOTE_INTERVAL: [number, number] = [3500, 9000] // ms between emotesconst EMOTE_DURATION = 1500 // ms a bubble stays upconst EMOTE_RISE = 16 // px it floats upward over its lifeconst EMOTE_GAP = 6 // px between the head and the bubble's baseconst EMOTE_Z = 1e7 // sort above all entities/objects/markersconst EMOTE_STYLE = { fontFamily: 'sans-serif', fontSize: 26, fill: 0xffffff } as const
export type NpcStateKind = 'idle' | 'spin' | 'wander'
/** Relative likelihood of each behaviour at a decision point (any non-negative * scale; they need not sum to 1). */export interface NpcWeights { idle: number spin: number wander: number}
export interface NpcDef { /** directional clips, e.g. from {@link import('./entity').walkSheetClips}. */ clips: Record<string, Clip> /** behaviour weights sampled by the policy. */ weights: NpcWeights /** the region the NPC is leashed to and wanders within (cell px). */ area: Rect /** wander walk speed (px/sec). Default 45. */ speed?: number /** sprite scale. Default 1. */ scale?: number /** idle duration range (ms). Default [800, 2600]. */ idleMs?: [number, number] /** spin duration range (ms). Default [700, 1800]. */ spinMs?: [number, number] /** how often facing changes while spinning (ms). Default 160. */ spinStepMs?: number /** start drifting away when a player is within this many px. 0 disables. * Default 56. */ yieldRadius?: number /** drift speed while yielding (px/sec). Default 90. */ yieldSpeed?: number /** personal-space radius for NPC↔NPC separation (px): two NPCs closer than * this push apart so they never stand on top of each other. 0 disables. * Default 26 (≈ a body width). Pair with a group / `neighbors` (see * {@link NpcController.update}); a lone NPC has nothing to separate from. */ radius?: number /** an emoji this NPC occasionally emotes above its head (a little floating * bubble). Needs a `SpawnNpcOptions.overlay` to draw into; absent = no emote. */ emoji?: string}
/** Picks the next behaviour given the rng, the def, and the previous state. */export type NpcPolicy = (rng: () => number, def: NpcDef, prev: NpcStateKind) => NpcStateKind
/** Per-frame surroundings an NPC reacts to. */export interface NpcWorld { /** world points to yield (drift away) from — the viewer's known players. */ players?: readonly Point[] /** OTHER NPCs' positions for separation (exclude self). A {@link NpcGroup} * supplies these automatically; pass them yourself for a hand-rolled set. */ neighbors?: readonly Point[]}
export interface NpcController { readonly entity: Entity /** the active behaviour, or `'yield'` while dodging a player. */ readonly state: NpcStateKind | 'yield' /** advance behaviour by `dtMs`, reacting to `world` (players to dodge, * neighbours to keep apart from). Both optional. */ update(dtMs: number, world?: NpcWorld): void destroy(): void}
interface Point { x: number y: number}
export interface SpawnNpcOptions { def: NpcDef /** initial position; defaults to the area centre. */ x?: number y?: number /** randomness source in [0,1). Default `Math.random`; pass a seeded * {@link mulberry32} for reproducible motion. */ rng?: () => number /** override the transition policy (default {@link weightedPolicy}). */ policy?: NpcPolicy /** keeps wander/yield from entering walls; e.g. a scene-collider test. A * blocked candidate step is simply skipped. */ blocked?: (x: number, y: number) => boolean /** world-space container to draw emote bubbles into (usually the same sortable * `world` the entity layer renders in). Required for `def.emoji` to show. */ overlay?: Container}
const DIRS: Facing[] = ['south', 'west', 'north', 'east']
/** Spawn a decorative NPC into an entity layer. */export function spawnNpc(layer: EntityLayer, opts: SpawnNpcOptions): NpcController { const { def } = opts const rng = opts.rng ?? Math.random const policy = opts.policy ?? weightedPolicy const blocked = opts.blocked const area = def.area const speed = def.speed ?? 45 const yieldRadius = def.yieldRadius ?? 56 const yieldSpeed = def.yieldSpeed ?? 90 const radius = def.radius ?? 26 const idleMs = def.idleMs ?? [800, 2600] const spinMs = def.spinMs ?? [700, 1800] const spinStepMs = def.spinStepMs ?? 160
const startX = opts.x ?? area.x + area.w / 2 const startY = opts.y ?? area.y + area.h / 2
let facing: Facing = DIRS[Math.floor(rng() * DIRS.length)]! const entity = layer.spawn({ clips: def.clips, clip: `idle-${facing}`, x: startX, y: startY, scale: def.scale ?? 1, })
let state: NpcStateKind = 'idle' let yielding = false let timer = 0 // ms remaining in the current state let spinClock = 0 // ms until the next facing change while spinning let target: { x: number; y: number } | null = null // wander destination
// emote bubble state: null when none is up. `emoteIn` counts down to the next // pop (Infinity disables — no emoji or no overlay to draw into). const overlay = opts.overlay const emoji = def.emoji let emote: { text: Text; age: number } | null = null let emoteIn = emoji && overlay ? randRange(rng, EMOTE_INTERVAL) : Infinity
const clearEmote = () => { if (!emote) return overlay?.removeChild(emote.text) emote.text.destroy() emote = null }
// Advance the emote: count down to a pop, then float a fading bubble up over // the head. Positioned in world space each frame so it tracks the NPC and // never inherits the sprite's scale (a tiny chick still gets a full-size emoji). const stepEmote = (dtMs: number) => { if (!emoji || !overlay) return const headTop = entity.y - entity.sprite.height - EMOTE_GAP if (emote) { emote.age += dtMs const t = emote.age / EMOTE_DURATION if (t >= 1) return clearEmote() // ease in over the first fifth, hold, fade out over the last third emote.text.alpha = clamp(t < 0.2 ? t / 0.2 : t > 0.7 ? (1 - t) / 0.3 : 1, 0, 1) emote.text.position.set(entity.x, headTop - EMOTE_RISE * t) } else if ((emoteIn -= dtMs) <= 0) { emoteIn = randRange(rng, EMOTE_INTERVAL) const text = new Text({ text: emoji, style: EMOTE_STYLE }) text.anchor.set(0.5, 1) text.zIndex = EMOTE_Z text.alpha = 0 text.position.set(entity.x, headTop) overlay.addChild(text) emote = { text, age: 0 } } }
const setFacing = (f: Facing, moving: boolean) => { facing = f entity.play(`${moving ? 'walk' : 'idle'}-${f}`) }
const enter = (next: NpcStateKind) => { state = next if (next === 'idle') { timer = randRange(rng, idleMs) setFacing(facing, false) } else if (next === 'spin') { timer = randRange(rng, spinMs) spinClock = spinStepMs setFacing(facing, false) } else { // wander: aim at a random point in the area (skip unreachable picks) target = pickTarget() const f = target ? facingToward(startXY().x, startXY().y, target.x, target.y) : facing setFacing(f, target !== null) } }
const startXY = () => ({ x: entity.x, y: entity.y })
const pickTarget = (): { x: number; y: number } | null => { for (let tries = 0; tries < 6; tries++) { const x = area.x + rng() * area.w const y = area.y + rng() * area.h if (!blocked || !blocked(x, y)) return { x, y } } return null }
// move toward (tx,ty) by up to `dist` px, honouring `blocked` + area leash. // returns true if a step was taken. const stepToward = (tx: number, ty: number, dist: number): boolean => { const dx = tx - entity.x const dy = ty - entity.y const d = Math.hypot(dx, dy) if (d < 0.5) return false return tryStep(dx / d, dy / d, Math.min(dist, d)) }
// step a unit direction by `dist`, honouring `blocked` + area leash. const tryStep = (ux: number, uy: number, dist: number): boolean => { const nx = clamp(entity.x + ux * dist, area.x, area.x + area.w) const ny = clamp(entity.y + uy * dist, area.y, area.y + area.h) if (Math.abs(nx - entity.x) < 0.01 && Math.abs(ny - entity.y) < 0.01) return false if (blocked && blocked(nx, ny)) return false entity.setPosition(nx, ny) return true }
// drift away along the first free direction in a fan around (ux,uy), so a // cornered NPC slides around obstacles instead of pinning against one. const driftAway = (ux: number, uy: number, dist: number): void => { const base = Math.atan2(uy, ux) for (const off of DRIFT_FAN) { const a = base + off const dirX = Math.cos(a) const dirY = Math.sin(a) if (tryStep(dirX, dirY, dist)) { setFacing(facingToward(0, 0, dirX, dirY), true) return } } }
// push out of any neighbour we're overlapping, so two NPCs never stand on top // of each other. Resolves HALF of each penetration (the neighbour resolves the // other half symmetrically), capped per frame to avoid jitter, and honours the // leash + `blocked`. Runs every frame regardless of behaviour state. const separate = (neighbors: readonly Point[] | undefined): void => { if (radius <= 0 || !neighbors || neighbors.length === 0) return let mx = 0 let my = 0 for (const o of neighbors) { let dx = entity.x - o.x let dy = entity.y - o.y let d = Math.hypot(dx, dy) if (d >= radius) continue if (d < 0.01) { // exactly coincident — pick a stable arbitrary axis to break the tie dx = 1 dy = 0 d = 1 } const push = (radius - d) * 0.5 // half the penetration mx += (dx / d) * push my += (dy / d) * push } const len = Math.hypot(mx, my) if (len < 0.01) return const capped = Math.min(len, radius) // never teleport more than one radius tryStep(mx / len, my / len, capped) }
// don't start life standing in a wall: nudge to the nearest free spot. if (blocked && blocked(startX, startY)) { const free = findFreeSpot(startX, startY, blocked, { step: 16, rings: 24 }) if (free) entity.setPosition(clamp(free.x, area.x, area.x + area.w), clamp(free.y, area.y, area.y + area.h)) }
enter(pickInitial(rng, def, policy))
return { entity, get state() { return yielding ? 'yield' : state }, update(dtMs, world) { // 1) yield to a close player, else run the current behaviour const near = nearestWithin(world?.players, entity.x, entity.y, yieldRadius) if (near) { yielding = true const ax = entity.x - near.x const ay = entity.y - near.y const len = Math.hypot(ax, ay) || 1 driftAway(ax / len, ay / len, (yieldSpeed * dtMs) / 1000) } else if (yielding) { // just cleared the player — settle back into a fresh idle yielding = false enter('idle') } else { timer -= dtMs if (state === 'wander') { if (!target || !stepToward(target.x, target.y, (speed * dtMs) / 1000)) { enter(policy(rng, def, state)) // arrived / stuck → re-decide } } else if (state === 'spin') { spinClock -= dtMs if (spinClock <= 0) { spinClock = spinStepMs setFacing(DIRS[(DIRS.indexOf(facing) + 1) % DIRS.length]!, false) } if (timer <= 0) enter(policy(rng, def, state)) } else { if (timer <= 0) enter(policy(rng, def, state)) } }
// 2) keep clear of other NPCs (always — even while idle/spinning/yielding) separate(world?.neighbors)
// 3) advance the emote bubble (cosmetic; no-op without an emoji/overlay) stepEmote(dtMs) }, destroy() { clearEmote() entity.destroy() }, }}
/** A managed set of NPCs that feeds each member the others' positions every * frame, so they keep apart (NPC↔NPC separation) without the caller wiring * neighbours by hand. This is the normal way to run a crowd; {@link spawnNpc} * alone is for a lone NPC or a hand-rolled neighbour set. */export interface NpcGroup { /** spawn a member into the group (and its entity layer). */ spawn(opts: SpawnNpcOptions): NpcController readonly members: readonly NpcController[] /** advance every member; `players` are dodged by all of them, and each member * is kept apart from the others. */ update(dtMs: number, players?: readonly Point[]): void destroy(): void}
/** Create an NPC group over an entity layer. `overlay` (a world-space container) * receives every member's emote bubbles; omit it to disable emoting group-wide. */export function createNpcGroup(layer: EntityLayer, overlay?: Container): NpcGroup { const members: NpcController[] = [] return { spawn(opts) { const c = spawnNpc(layer, overlay ? { overlay, ...opts } : opts) members.push(c) return c }, get members() { return members }, update(dtMs, players) { // snapshot positions once so every member separates against the same // start-of-frame layout (order-independent, symmetric). const pts = members.map((m) => ({ x: m.entity.x, y: m.entity.y })) members.forEach((m, i) => { const neighbors: Point[] = [] for (let j = 0; j < pts.length; j++) if (j !== i) neighbors.push(pts[j]!) m.update(dtMs, { players, neighbors }) }) }, destroy() { for (const m of [...members]) m.destroy() members.length = 0 }, }}
/** Default policy: sample a behaviour by its weight. */export function weightedPolicy(rng: () => number, def: NpcDef, _prev: NpcStateKind): NpcStateKind { const w = def.weights const total = Math.max(0, w.idle) + Math.max(0, w.spin) + Math.max(0, w.wander) if (total <= 0) return 'idle' let r = rng() * total if ((r -= Math.max(0, w.idle)) < 0) return 'idle' if ((r -= Math.max(0, w.spin)) < 0) return 'spin' return 'wander'}
/** A small, fast seeded PRNG (mulberry32). Seed an NPC with it for reproducible, * per-NPC motion: `rng: mulberry32(baseSeed + index)`. */export function mulberry32(seed: number): () => number { let a = seed >>> 0 return () => { a |= 0 a = (a + 0x6d2b79f5) | 0 let t = Math.imul(a ^ (a >>> 15), 1 | a) t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t return ((t ^ (t >>> 14)) >>> 0) / 4294967296 }}
// --- helpers ---------------------------------------------------------------
function pickInitial(rng: () => number, def: NpcDef, policy: NpcPolicy): NpcStateKind { return policy(rng, def, 'idle')}
function randRange(rng: () => number, [a, b]: [number, number]): number { return a + rng() * (b - a)}
function clamp(v: number, lo: number, hi: number): number { return Math.max(lo, Math.min(hi, v))}
function facingToward(fromX: number, fromY: number, toX: number, toY: number): Facing { const dx = toX - fromX const dy = toY - fromY if (Math.abs(dx) > Math.abs(dy)) return dx < 0 ? 'west' : 'east' return dy < 0 ? 'north' : 'south'}
/** Nearest of `points` within `radius` of (x,y), or null. */function nearestWithin( points: readonly { x: number; y: number }[] | undefined, x: number, y: number, radius: number,): { x: number; y: number } | null { if (!points || radius <= 0) return null let best: { x: number; y: number } | null = null let bestD = radius for (const p of points) { const d = Math.hypot(p.x - x, p.y - y) if (d <= bestD) { bestD = d best = p } } return best}