BlueGit

timfa questward

Files

questward / shared / definitions / mobs.js

mobs.js

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