BlueGit

timfa questward

Files

questward / shared / definitions / mobs.js

mobs.js

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