BlueGit

timfa questward

Files

questward / shared / definitions / mobs.js

mobs.js

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