BlueGit

timfa questward

Files

questward / shared / definitions / mobs.js

mobs.js

mobs.js 13.6 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 bodyNpc = humanoid || townGuard || centralExchange;
251 return {
252 spawnerId,
253 mobTypeId,
254 maxAlive: centralExchange
255 ? centralExchangeStaffCount()
256 : (bodyNpc ? 1 : 3),
257 spawnRangeTiles: bodyNpc ? 1 : 4,
258 maxWanderRangeTiles: bodyNpc ? 1 : 8,
259 level: townGuard ? 30 : 1,
260 bounty: townGuard ? 500 : 0,
261 /** Humanoid spawners only: auto-engage players in aggro range. Forces bounty 0. */
262 aggressive: false,
263 sex: "male",
264 displayName: townGuard ? "Town Guard" : (humanoid ? "Shopkeeper" : ""),
265 equipment: townGuard
266 ? {
267 head: ArmourItemId.ironHelmet,
268 chest: ArmourItemId.ironChestplate,
269 legs: ArmourItemId.bronzeGreaves,
270 boots: ArmourItemId.ironBoots,
271 weapon: WoodItemId.oakQuarterstaff,
272 offhand: null
273 }
274 : emptySpawnerEquipment(),
275 sells: [],
276 spells: [],
277 buysItems: false,
278 hiddenDiscount: 0.9,
279 centralExchange,
280 townGuard,
281 dialogueId: null
282 };
283}
284
285function emptySpawnerEquipment ()
286{
287 return {
288 head: null,
289 chest: null,
290 legs: null,
291 boots: null,
292 weapon: null,
293 offhand: null
294 };
295}
296
297/**
298 * Spawner equipment entry: legacy itemId number, or `{ itemId, dyeColor? }` for dyed clothing.
299 * Normalized form keeps a plain number when undyed (world-save compatible).
300 */
301function normalizeEquipmentEntry (value)
302{
303 if (value == null || value === "" || value === "0")
304 { return null; }
305 let itemId = 0;
306 let dyeColor = null;
307 if (typeof value === "object")
308 {
309 itemId = Number(value.itemId) | 0;
310 dyeColor = normalizeDyeColor(value.dyeColor);
311 }
312 else
313 { itemId = Number(value) | 0; }
314 if (!Number.isFinite(itemId) || itemId <= 0)
315 { return null; }
316 if (!dyeColor)
317 { return itemId; }
318 return Object.freeze({ itemId, dyeColor });
319}
320
321function normalizeDyeColor (raw)
322{
323 if (!raw || typeof raw !== "object")
324 { return null; }
325 const r = Number(raw.r);
326 const g = Number(raw.g);
327 const b = Number(raw.b);
328 if (![r, g, b].every(Number.isFinite))
329 { return null; }
330 const asByte = r > 1 || g > 1 || b > 1;
331 return Object.freeze({
332 r: Math.min(1, Math.max(0, asByte ? r / 255 : r)),
333 g: Math.min(1, Math.max(0, asByte ? g / 255 : g)),
334 b: Math.min(1, Math.max(0, asByte ? b / 255 : b))
335 });
336}
337
338function normalizeEquipment (raw)
339{
340 const next = emptySpawnerEquipment();
341 if (!raw || typeof raw !== "object")
342 { return next; }
343 for (const slot of Object.keys(next))
344 { next[slot] = normalizeEquipmentEntry(raw[slot]); }
345 return next;
346}
347
348/** Resolve authored spawner equipment into itemId (+ optional dye). */
349export function spawnerEquipmentSlot (entry)
350{
351 if (entry == null)
352 { return { itemId: 0, dyeColor: null }; }
353 if (typeof entry === "object")
354 {
355 return {
356 itemId: Number(entry.itemId) | 0,
357 dyeColor: entry.dyeColor ?? null
358 };
359 }
360 return { itemId: Number(entry) | 0, dyeColor: null };
361}
362
363function normalizeSells (raw)
364{
365 if (!Array.isArray(raw))
366 { return []; }
367 const lines = [];
368 const seen = new Set();
369 for (const entry of raw)
370 {
371 let itemId;
372 let quantity = 0;
373 if (entry && typeof entry === "object")
374 {
375 itemId = Number(entry.itemId);
376 quantity = Math.max(0, Number(entry.quantity) || 0) | 0;
377 }
378 else
379 { itemId = Number(entry); }
380 if (!Number.isFinite(itemId) || itemId <= 0 || seen.has(itemId | 0))
381 { continue; }
382 seen.add(itemId | 0);
383 lines.push({ itemId: itemId | 0, quantity });
384 }
385 return lines;
386}
387
388function normalizeSpells (raw)
389{
390 if (!Array.isArray(raw))
391 { return []; }
392 const lines = [];
393 const seen = new Set();
394 for (const entry of raw)
395 {
396 if (!entry || typeof entry !== "object")
397 { continue; }
398 const spellId = String(entry.spellId ?? "").trim();
399 if (!spellId || seen.has(spellId))
400 { continue; }
401 seen.add(spellId);
402 // Cast chance is derived from mob level at spawn time — not stored.
403 lines.push({ spellId });
404 }
405 return lines;
406}
407
408/** Clamp wander ≥ spawn; coerce numeric fields; keep humanoid shop/appearance options. */
409export function normalizeSpawnerConfig (config, spawnerId = "spawner")
410{
411 const mobTypeId = config?.mobTypeId ?? MobId.deer;
412 const centralExchange = mobTypeId === MobId.centralExchange || !!config?.centralExchange;
413 const townGuard = !centralExchange && (mobTypeId === MobId.townGuard || !!config?.townGuard);
414 const effectiveMob = centralExchange
415 ? MobId.centralExchange
416 : (townGuard ? MobId.townGuard : mobTypeId);
417 const base = defaultSpawnerConfig(spawnerId, effectiveMob);
418 const merged = { ...base, ...(config ?? {}), spawnerId: config?.spawnerId || spawnerId, mobTypeId: effectiveMob };
419 const spawnRangeTiles = Math.max(1, Math.min(32, Number(merged.spawnRangeTiles) || base.spawnRangeTiles));
420 const maxWanderRangeTiles = Math.max(
421 spawnRangeTiles,
422 Math.min(64, Number(merged.maxWanderRangeTiles) || spawnRangeTiles)
423 );
424 const sex = merged.sex === "female" ? "female" : "male";
425 const hiddenDiscount = Math.min(1, Math.max(0.01, Number(merged.hiddenDiscount) || base.hiddenDiscount));
426 const displayName = String(merged.displayName ?? "").trim().slice(0, 48);
427 const staffCap = centralExchangeStaffCount();
428 const level = Math.max(1, Math.min(99, Number(merged.level) || base.level || 1)) | 0;
429 const bodyNpc = isHumanoidMob(effectiveMob) || centralExchange || townGuard;
430 const aggressive = bodyNpc ? !!merged.aggressive : false;
431 const bounty = aggressive ? 0 : (Math.max(0, Number(merged.bounty) || 0) | 0);
432 return {
433 spawnerId: String(merged.spawnerId),
434 mobTypeId: effectiveMob,
435 maxAlive: centralExchange
436 ? staffCap
437 : Math.max(1, Math.min(20, Number(merged.maxAlive) || base.maxAlive)),
438 spawnRangeTiles,
439 maxWanderRangeTiles,
440 level,
441 bounty,
442 aggressive,
443 sex,
444 displayName,
445 equipment: normalizeEquipment(merged.equipment),
446 sells: centralExchange ? [] : normalizeSells(merged.sells),
447 spells: normalizeSpells(merged.spells),
448 buysItems: centralExchange ? false : !!merged.buysItems,
449 hiddenDiscount,
450 centralExchange,
451 townGuard,
452 dialogueId: bodyNpc
453 ? (String(merged.dialogueId ?? "").trim().slice(0, 64) || null)
454 : null
455 };
456}
457
458export function listAmbientMobTypes ()
459{
460 return Object.values(MOB_DEFINITIONS).filter((def) => def.ambient);
461}
462
463/** Every mob type that can be authored as a world-editor spawner. */
464export function listSpawnableMobTypes ()
465{
466 return Object.values(MOB_DEFINITIONS);
467}
468
469export function isHumanoidMob (mobTypeId)
470{
471 return mobDefinition(mobTypeId)?.usePlayerBody === true;
472}
473
474export function isTownGuardMob (mobTypeId)
475{
476 return mobTypeId === MobId.townGuard || !!mobDefinition(mobTypeId)?.townGuard;
477}
478
479export function isCentralExchangeSpawner (configOrMobTypeId)
480{
481 if (configOrMobTypeId && typeof configOrMobTypeId === "object")
482 { return !!configOrMobTypeId.centralExchange || configOrMobTypeId.mobTypeId === MobId.centralExchange; }
483 return configOrMobTypeId === MobId.centralExchange;
484}
485
486/** Max HP for a mob at the given spawner level. */
487export function mobMaxHealthForLevel (def, level)
488{
489 const lv = Math.max(1, Math.floor(Number(level) || 1));
490 const formula = def?.maxHealthFromLevel;
491 if (formula === "levelPlus10" || (!formula && def?.usePlayerBody))
492 { return lv + 10; }
493 const base = Math.max(1, Number(def?.health ?? def?.maxHealth ?? 8) || 8);
494 return Math.max(1, base + (lv - 1));
495}
496
497/** Display label for hover / UI: `Lv.5 Deer`. */
498export function mobLevelDisplayName (level, displayName)
499{
500 const lv = Math.max(1, Math.floor(Number(level) || 1));
501 const name = String(displayName ?? "").trim() || "Creature";
502 return `Lv.${lv} ${name}`;
503}