BlueGit

timfa questward

Files

questward / shared / definitions / mobs.js

mobs.js

mobs.js 13.3 KiB Download Raw
1import { spriteImageName } from "./tileSprites.js";
2import { centralExchangeStaffCount } from "../market/exchange.js";
3import { LeatherItemId } from "./leatherItems.js";
4import { RangedItemId } from "./rangedItems.js";
5import { ItemId } from "./items.js";
6
7export const MobId = Object.freeze({
8 deer: "deer",
9 pigeon: "pigeon",
10 rat: "rat",
11 chicken: "chicken",
12 humanoid: "humanoid",
13 /** Humanoid guards that respond to bounty kills within wander range. */
14 townGuard: "town-guard",
15 /** Editor/spawner identity for Central Exchange staff (always humanoid bodies). */
16 centralExchange: "central-exchange"
17});
18
19/** @typedef {{ itemId: number, chance: number, quantity?: number, quantityMin?: number, quantityMax?: number }} MobDrop */
20/** @typedef {{ isPlayer: boolean, text: string }} DialogueLine */
21/** @typedef {{ trigger: string, text: string, available?: (ctx: object) => boolean }} DialogueResponse */
22
23/**
24 * Target mob content schema (rendering fields stay alongside gameplay fields for now).
25 * - displayName: shown name
26 * - health / maxHealth: hit points
27 * - attackSkill: one skill level for hit chance and damage
28 * - drops: { itemId, chance } roll on death
29 * - sells: default item IDs for shop stock (overridable per spawner)
30 * - dialogue: branching trees with triggers, lines, responses, and action hooks (later)
31 * - usePlayerBody: draw male/female character body instead of a mob sprite
32 */
33export const MOB_DEFINITIONS = Object.freeze({
34 [MobId.deer]: Object.freeze({
35 mobTypeId: MobId.deer,
36 key: "deer",
37 assetFolder: "mobs",
38 displayName: "Deer",
39 health: 8,
40 maxHealth: 8,
41 attackSkill: 2,
42 attackCooldownMs: 1000,
43 drops: Object.freeze([
44 { itemId: LeatherItemId.softLeather, chance: 1 }
45 ]),
46 sells: Object.freeze([]),
47 dialogue: Object.freeze([]),
48 persistent: false,
49 flying: false,
50 freeFlight: false,
51 ambient: false,
52 talkable: false,
53 untargetable: false,
54 aggressive: false,
55 gait: "walk",
56 sex: "male",
57 frames: 1,
58 framesPerRow: 1,
59 animationSpeed: 0
60 }),
61 [MobId.pigeon]: Object.freeze({
62 mobTypeId: MobId.pigeon,
63 key: "pigeon",
64 assetFolder: "pigeons",
65 displayName: "Pigeon",
66 health: 1,
67 maxHealth: 1,
68 canFight: false,
69 drops: Object.freeze([]),
70 sells: Object.freeze([]),
71 dialogue: Object.freeze([]),
72 persistent: false,
73 flying: true,
74 freeFlight: true,
75 ambient: false,
76 talkable: false,
77 untargetable: true,
78 aggressive: false,
79 gait: "walk",
80 sex: "male",
81 frames: 2,
82 framesPerRow: 2,
83 animationSpeed: 0.18,
84 defaultState: "pigeon-flying",
85 flightSpeedTilesPerSec: 2.5
86 }),
87 [MobId.rat]: Object.freeze({
88 mobTypeId: MobId.rat,
89 key: "rat",
90 assetFolder: "mobs",
91 displayName: "Rat",
92 health: 12,
93 maxHealth: 12,
94 attackSkill: 3,
95 attackCooldownMs: 900,
96 drops: Object.freeze([]),
97 sells: Object.freeze([]),
98 dialogue: Object.freeze([]),
99 persistent: false,
100 flying: false,
101 freeFlight: false,
102 ambient: false,
103 talkable: false,
104 untargetable: false,
105 /** Auto-engage nearby players when in range with line of sight. */
106 aggressive: true,
107 aggroRangeTiles: 5,
108 elementAffinities: Object.freeze({ fire: "weak" }),
109 gait: "walk",
110 sex: "male",
111 frames: 1,
112 framesPerRow: 1,
113 animationSpeed: 0
114 }),
115 [MobId.chicken]: Object.freeze({
116 mobTypeId: MobId.chicken,
117 key: "chicken",
118 assetFolder: "mobs",
119 displayName: "Chicken",
120 health: 5,
121 maxHealth: 5,
122 attackSkill: 1,
123 attackCooldownMs: 1200,
124 drops: Object.freeze([
125 { itemId: RangedItemId.feather, chance: 1, quantityMin: 1, quantityMax: 3 },
126 { itemId: ItemId.egg, chance: 0.2 }
127 ]),
128 sells: Object.freeze([]),
129 dialogue: Object.freeze([]),
130 persistent: false,
131 flying: false,
132 freeFlight: false,
133 ambient: false,
134 talkable: false,
135 untargetable: false,
136 aggressive: false,
137 gait: "walk",
138 sex: "female",
139 frames: 1,
140 framesPerRow: 1,
141 animationSpeed: 0
142 }),
143 [MobId.humanoid]: Object.freeze({
144 mobTypeId: MobId.humanoid,
145 key: "humanoid",
146 assetFolder: "characters",
147 displayName: "Humanoid",
148 health: 10,
149 maxHealth: 10,
150 /** HP = spawner level + 10 (same floor as a starting player's Health). */
151 maxHealthFromLevel: "levelPlus10",
152 drops: Object.freeze([]),
153 sells: Object.freeze([]),
154 dialogue: Object.freeze([]),
155 persistent: false,
156 flying: false,
157 freeFlight: false,
158 ambient: false,
159 talkable: true,
160 untargetable: false,
161 aggressive: false,
162 usePlayerBody: true,
163 gait: "walk",
164 sex: "male",
165 frames: 1,
166 framesPerRow: 1,
167 animationSpeed: 0
168 }),
169 [MobId.townGuard]: Object.freeze({
170 mobTypeId: MobId.townGuard,
171 key: "town-guard",
172 assetFolder: "characters",
173 displayName: "Town Guard",
174 health: 10,
175 maxHealth: 10,
176 maxHealthFromLevel: "levelPlus10",
177 drops: Object.freeze([]),
178 sells: Object.freeze([]),
179 dialogue: Object.freeze([]),
180 persistent: false,
181 flying: false,
182 freeFlight: false,
183 ambient: false,
184 talkable: false,
185 untargetable: false,
186 aggressive: false,
187 usePlayerBody: true,
188 townGuard: true,
189 gait: "walk",
190 sex: "male",
191 frames: 1,
192 framesPerRow: 1,
193 animationSpeed: 0
194 }),
195 [MobId.centralExchange]: Object.freeze({
196 mobTypeId: MobId.centralExchange,
197 key: "central-exchange",
198 assetFolder: "characters",
199 displayName: "Central Exchange staff",
200 health: 10,
201 maxHealth: 10,
202 maxHealthFromLevel: "levelPlus10",
203 drops: Object.freeze([]),
204 sells: Object.freeze([]),
205 dialogue: Object.freeze([]),
206 persistent: false,
207 flying: false,
208 freeFlight: false,
209 ambient: false,
210 talkable: false,
211 untargetable: false,
212 aggressive: false,
213 usePlayerBody: true,
214 centralExchange: true,
215 gait: "walk",
216 sex: "male",
217 frames: 1,
218 framesPerRow: 1,
219 animationSpeed: 0
220 })
221});
222
223export function mobDefinition (mobTypeId)
224{
225 return MOB_DEFINITIONS[mobTypeId] ?? null;
226}
227
228export function mobSpriteName (mobTypeId)
229{
230 const def = mobDefinition(mobTypeId);
231 const key = def?.key ?? def?.mobTypeId ?? "deer";
232 if (def?.usePlayerBody)
233 {
234 // Editor palette preview; live entities use appearance.sex → bodySprite().
235 return spriteImageName("character", "player-body-male", "player-body-male");
236 }
237 if (def?.sprite)
238 { return def.sprite; }
239 const state = def?.defaultState ?? key;
240 return spriteImageName("mob", key, state);
241}
242
243export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
244{
245 const humanoid = isHumanoidMob(mobTypeId) || mobTypeId === MobId.humanoid;
246 const townGuard = mobTypeId === MobId.townGuard;
247 const centralExchange = mobTypeId === MobId.centralExchange;
248 const bodyNpc = humanoid || townGuard || centralExchange;
249 return {
250 spawnerId,
251 mobTypeId,
252 maxAlive: centralExchange
253 ? centralExchangeStaffCount()
254 : (bodyNpc ? 1 : 3),
255 spawnRangeTiles: bodyNpc ? 1 : 4,
256 maxWanderRangeTiles: bodyNpc ? 1 : 8,
257 level: 1,
258 bounty: 0,
259 /** Humanoid spawners only: auto-engage players in aggro range. Forces bounty 0. */
260 aggressive: false,
261 sex: "male",
262 displayName: townGuard ? "Town Guard" : (humanoid ? "Shopkeeper" : ""),
263 equipment: emptySpawnerEquipment(),
264 sells: [],
265 spells: [],
266 buysItems: false,
267 hiddenDiscount: 0.9,
268 centralExchange,
269 townGuard,
270 dialogueId: null
271 };
272}
273
274function emptySpawnerEquipment ()
275{
276 return {
277 head: null,
278 chest: null,
279 legs: null,
280 boots: null,
281 weapon: null,
282 offhand: null
283 };
284}
285
286/**
287 * Spawner equipment entry: legacy itemId number, or `{ itemId, dyeColor? }` for dyed clothing.
288 * Normalized form keeps a plain number when undyed (world-save compatible).
289 */
290function normalizeEquipmentEntry (value)
291{
292 if (value == null || value === "" || value === "0")
293 { return null; }
294 let itemId = 0;
295 let dyeColor = null;
296 if (typeof value === "object")
297 {
298 itemId = Number(value.itemId) | 0;
299 dyeColor = normalizeDyeColor(value.dyeColor);
300 }
301 else
302 { itemId = Number(value) | 0; }
303 if (!Number.isFinite(itemId) || itemId <= 0)
304 { return null; }
305 if (!dyeColor)
306 { return itemId; }
307 return Object.freeze({ itemId, dyeColor });
308}
309
310function normalizeDyeColor (raw)
311{
312 if (!raw || typeof raw !== "object")
313 { return null; }
314 const r = Number(raw.r);
315 const g = Number(raw.g);
316 const b = Number(raw.b);
317 if (![r, g, b].every(Number.isFinite))
318 { return null; }
319 const asByte = r > 1 || g > 1 || b > 1;
320 return Object.freeze({
321 r: Math.min(1, Math.max(0, asByte ? r / 255 : r)),
322 g: Math.min(1, Math.max(0, asByte ? g / 255 : g)),
323 b: Math.min(1, Math.max(0, asByte ? b / 255 : b))
324 });
325}
326
327function normalizeEquipment (raw)
328{
329 const next = emptySpawnerEquipment();
330 if (!raw || typeof raw !== "object")
331 { return next; }
332 for (const slot of Object.keys(next))
333 { next[slot] = normalizeEquipmentEntry(raw[slot]); }
334 return next;
335}
336
337/** Resolve authored spawner equipment into itemId (+ optional dye). */
338export function spawnerEquipmentSlot (entry)
339{
340 if (entry == null)
341 { return { itemId: 0, dyeColor: null }; }
342 if (typeof entry === "object")
343 {
344 return {
345 itemId: Number(entry.itemId) | 0,
346 dyeColor: entry.dyeColor ?? null
347 };
348 }
349 return { itemId: Number(entry) | 0, dyeColor: null };
350}
351
352function normalizeSells (raw)
353{
354 if (!Array.isArray(raw))
355 { return []; }
356 const lines = [];
357 const seen = new Set();
358 for (const entry of raw)
359 {
360 let itemId;
361 let quantity = 0;
362 if (entry && typeof entry === "object")
363 {
364 itemId = Number(entry.itemId);
365 quantity = Math.max(0, Number(entry.quantity) || 0) | 0;
366 }
367 else
368 { itemId = Number(entry); }
369 if (!Number.isFinite(itemId) || itemId <= 0 || seen.has(itemId | 0))
370 { continue; }
371 seen.add(itemId | 0);
372 lines.push({ itemId: itemId | 0, quantity });
373 }
374 return lines;
375}
376
377function normalizeSpells (raw)
378{
379 if (!Array.isArray(raw))
380 { return []; }
381 const lines = [];
382 const seen = new Set();
383 for (const entry of raw)
384 {
385 if (!entry || typeof entry !== "object")
386 { continue; }
387 const spellId = String(entry.spellId ?? "").trim();
388 if (!spellId || seen.has(spellId))
389 { continue; }
390 seen.add(spellId);
391 // Cast chance is derived from mob level at spawn time — not stored.
392 lines.push({ spellId });
393 }
394 return lines;
395}
396
397/** Clamp wander ≥ spawn; coerce numeric fields; keep humanoid shop/appearance options. */
398export function normalizeSpawnerConfig (config, spawnerId = "spawner")
399{
400 const mobTypeId = config?.mobTypeId ?? MobId.deer;
401 const centralExchange = mobTypeId === MobId.centralExchange || !!config?.centralExchange;
402 const townGuard = !centralExchange && (mobTypeId === MobId.townGuard || !!config?.townGuard);
403 const effectiveMob = centralExchange
404 ? MobId.centralExchange
405 : (townGuard ? MobId.townGuard : mobTypeId);
406 const base = defaultSpawnerConfig(spawnerId, effectiveMob);
407 const merged = { ...base, ...(config ?? {}), spawnerId: config?.spawnerId || spawnerId, mobTypeId: effectiveMob };
408 const spawnRangeTiles = Math.max(1, Math.min(32, Number(merged.spawnRangeTiles) || base.spawnRangeTiles));
409 const maxWanderRangeTiles = Math.max(
410 spawnRangeTiles,
411 Math.min(64, Number(merged.maxWanderRangeTiles) || spawnRangeTiles)
412 );
413 const sex = merged.sex === "female" ? "female" : "male";
414 const hiddenDiscount = Math.min(1, Math.max(0.01, Number(merged.hiddenDiscount) || base.hiddenDiscount));
415 const displayName = String(merged.displayName ?? "").trim().slice(0, 48);
416 const staffCap = centralExchangeStaffCount();
417 const level = Math.max(1, Math.min(99, Number(merged.level) || base.level || 1)) | 0;
418 const bodyNpc = isHumanoidMob(effectiveMob) || centralExchange || townGuard;
419 const aggressive = bodyNpc ? !!merged.aggressive : false;
420 const bounty = aggressive ? 0 : (Math.max(0, Number(merged.bounty) || 0) | 0);
421 return {
422 spawnerId: String(merged.spawnerId),
423 mobTypeId: effectiveMob,
424 maxAlive: centralExchange
425 ? staffCap
426 : Math.max(1, Math.min(20, Number(merged.maxAlive) || base.maxAlive)),
427 spawnRangeTiles,
428 maxWanderRangeTiles,
429 level,
430 bounty,
431 aggressive,
432 sex,
433 displayName,
434 equipment: normalizeEquipment(merged.equipment),
435 sells: centralExchange ? [] : normalizeSells(merged.sells),
436 spells: normalizeSpells(merged.spells),
437 buysItems: centralExchange ? false : !!merged.buysItems,
438 hiddenDiscount,
439 centralExchange,
440 townGuard,
441 dialogueId: bodyNpc
442 ? (String(merged.dialogueId ?? "").trim().slice(0, 64) || null)
443 : null
444 };
445}
446
447export function listAmbientMobTypes ()
448{
449 return Object.values(MOB_DEFINITIONS).filter((def) => def.ambient);
450}
451
452/** Every mob type that can be authored as a world-editor spawner. */
453export function listSpawnableMobTypes ()
454{
455 return Object.values(MOB_DEFINITIONS);
456}
457
458export function isHumanoidMob (mobTypeId)
459{
460 return mobDefinition(mobTypeId)?.usePlayerBody === true;
461}
462
463export function isTownGuardMob (mobTypeId)
464{
465 return mobTypeId === MobId.townGuard || !!mobDefinition(mobTypeId)?.townGuard;
466}
467
468export function isCentralExchangeSpawner (configOrMobTypeId)
469{
470 if (configOrMobTypeId && typeof configOrMobTypeId === "object")
471 { return !!configOrMobTypeId.centralExchange || configOrMobTypeId.mobTypeId === MobId.centralExchange; }
472 return configOrMobTypeId === MobId.centralExchange;
473}
474
475/** Max HP for a mob at the given spawner level. */
476export function mobMaxHealthForLevel (def, level)
477{
478 const lv = Math.max(1, Math.floor(Number(level) || 1));
479 const formula = def?.maxHealthFromLevel;
480 if (formula === "levelPlus10" || (!formula && def?.usePlayerBody))
481 { return lv + 10; }
482 const base = Math.max(1, Number(def?.health ?? def?.maxHealth ?? 8) || 8);
483 return Math.max(1, base + (lv - 1));
484}
485
486/** Display label for hover / UI: `Lv.5 Deer`. */
487export function mobLevelDisplayName (level, displayName)
488{
489 const lv = Math.max(1, Math.floor(Number(level) || 1));
490 const name = String(displayName ?? "").trim() || "Creature";
491 return `Lv.${lv} ${name}`;
492}