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