BlueGit

timfa questward

Files

questward / shared / alchemy / recipes.js

recipes.js

recipes.js 9.7 KiB Download Raw
1import { AlchemyStepKind, ALCHEMY_POTION_DEFINITIONS, UNSTABLE_POTION_EFFECTS, CAULDRON_FLAVOR_LINES, CAULDRON_EMPTY_FLAVOR, alchemyPotionDefinition } from "../definitions/alchemy.js";
2import { ITEM_DEFINITIONS, ItemId, itemDefinition } from "../definitions/items.js";
3import { skillLevel, SkillId } from "../definitions/skills.js";
4
5/** Resolve an alchemy ingredient/step item key or id to a player-facing name. */
6export function alchemyItemLabel ({ itemId = null, itemKey = null, key = null } = {})
7{
8 if (itemId != null)
9 {
10 const def = itemDefinition(itemId);
11 if (def?.displayName)
12 { return def.displayName; }
13 }
14 const lookupKey = itemKey ?? key;
15 if (lookupKey)
16 {
17 const resolvedId = itemIdByKeyMap().get(lookupKey);
18 const def = resolvedId != null ? itemDefinition(resolvedId) : null;
19 if (def?.displayName)
20 { return def.displayName; }
21 return String(lookupKey);
22 }
23 return itemId != null ? String(itemId) : "?";
24}
25
26/** Serialize a step for hashing / recipe papers. */
27export function formatAlchemyStep (step)
28{
29 if (step.kind === AlchemyStepKind.insert)
30 {
31 if (step.potionKey)
32 {
33 const potion = alchemyPotionDefinition(step.potionKey);
34 return `insert ${potion?.displayName ?? step.potionKey}`;
35 }
36 return `insert ${alchemyItemLabel({
37 itemId: step.itemId,
38 itemKey: step.itemKey
39 })}`;
40 }
41 return step.kind;
42}
43
44export function hashAlchemySteps (steps)
45{
46 const text = (steps ?? []).map((step) =>
47 {
48 if (step.kind === AlchemyStepKind.insert)
49 {
50 if (step.potionKey)
51 { return `insert:potion:${step.potionKey}`; }
52 return `insert:${step.itemId ?? step.itemKey}`;
53 }
54 return step.kind;
55 }).join("|");
56 let hash = 2166136261;
57 for (let i = 0; i < text.length; i++)
58 {
59 hash ^= text.charCodeAt(i);
60 hash = Math.imul(hash, 16777619);
61 }
62 return hash >>> 0;
63}
64
65/** Latest cauldron look line from the step hash (or empty copy). */
66export function cauldronFlavorText (steps)
67{
68 if (!(steps?.length > 0))
69 { return CAULDRON_EMPTY_FLAVOR; }
70 const hash = hashAlchemySteps(steps);
71 return CAULDRON_FLAVOR_LINES[hash % CAULDRON_FLAVOR_LINES.length];
72}
73
74export function unstablePotionFromSteps (steps)
75{
76 const hash = hashAlchemySteps(steps);
77 const index = hash % UNSTABLE_POTION_EFFECTS.length;
78 const effect = UNSTABLE_POTION_EFFECTS[index];
79 return {
80 potionKey: `unstable:${effect.effectKey}`,
81 unstable: true,
82 stepsHash: hash,
83 displayName: effect.displayName,
84 color: effect.color,
85 fillLevel: effect.fillLevel,
86 effect: effect.effect,
87 effectKey: effect.effectKey
88 };
89}
90
91export function itemIdByKeyMap ()
92{
93 const map = new Map();
94 for (const def of Object.values(ITEM_DEFINITIONS))
95 {
96 if (def?.key != null)
97 { map.set(def.key, def.itemId); }
98 }
99 return map;
100}
101
102/**
103 * Resolve ingredient itemIds on potion defs that use item keys (after items are loaded).
104 */
105export function resolvePotionIngredientIds (potion, byKey = itemIdByKeyMap())
106{
107 const ingredients = (potion.ingredients ?? []).map((row) =>
108 {
109 if (row.potionKey)
110 {
111 return {
112 itemId: ItemId.potion,
113 potionKey: row.potionKey,
114 key: row.key ?? row.potionKey,
115 quantity: row.quantity
116 };
117 }
118 const itemId = row.itemId ?? byKey.get(row.key) ?? null;
119 return { itemId, key: row.key, quantity: row.quantity };
120 });
121 const steps = (potion.steps ?? []).map((step) =>
122 {
123 if (step.kind !== AlchemyStepKind.insert)
124 { return { ...step }; }
125 if (step.potionKey)
126 {
127 return {
128 kind: AlchemyStepKind.insert,
129 itemId: ItemId.potion,
130 potionKey: step.potionKey,
131 itemKey: step.itemKey ?? "potion"
132 };
133 }
134 const itemId = step.itemId ?? byKey.get(step.itemKey) ?? null;
135 return { kind: AlchemyStepKind.insert, itemId, itemKey: step.itemKey };
136 });
137 return { ...potion, ingredients, steps };
138}
139
140let cachedResolvedPotions = null;
141
142export function resolvedAlchemyPotions ()
143{
144 if (!cachedResolvedPotions)
145 {
146 const byKey = itemIdByKeyMap();
147 cachedResolvedPotions = Object.values(ALCHEMY_POTION_DEFINITIONS)
148 .map((potion) => resolvePotionIngredientIds(potion, byKey));
149 }
150 return cachedResolvedPotions;
151}
152
153/** Test helper when potion defs are patched mid-suite. */
154export function clearResolvedAlchemyPotionsCache ()
155{
156 cachedResolvedPotions = null;
157}
158
159export function alchemyIngredientNeedKey (row)
160{
161 if (row?.potionKey)
162 { return `potion:${row.potionKey}`; }
163 return `item:${row?.itemId | 0}`;
164}
165
166export function alchemyStackHaveKey (stack)
167{
168 if ((stack?.itemId | 0) === ItemId.potion && stack.instance?.potionKey)
169 { return `potion:${stack.instance.potionKey}`; }
170 return `item:${stack?.itemId | 0}`;
171}
172
173/**
174 * Greatest integer batch size for reserved slot quantities vs recipe ingredient ratios.
175 * Returns 0 if ratios do not match (wrong items or non-integer multiple).
176 * Potion ingredients match by potionKey (full bottles still counted as quantity).
177 */
178export function alchemyBatchCount (recipeIngredients, reservedStacks)
179{
180 const need = new Map();
181 for (const row of recipeIngredients ?? [])
182 {
183 if (row.potionKey)
184 {
185 if (!(row.quantity > 0))
186 { return 0; }
187 const key = alchemyIngredientNeedKey(row);
188 need.set(key, (need.get(key) ?? 0) + row.quantity);
189 continue;
190 }
191 if (row.itemId == null || row.quantity <= 0)
192 { return 0; }
193 const key = alchemyIngredientNeedKey(row);
194 need.set(key, (need.get(key) ?? 0) + row.quantity);
195 }
196 if (need.size === 0 || need.size > 4)
197 { return 0; }
198
199 const have = new Map();
200 for (const stack of reservedStacks ?? [])
201 {
202 if (!stack?.itemId || !(stack.quantity > 0))
203 { continue; }
204 const key = alchemyStackHaveKey(stack);
205 have.set(key, (have.get(key) ?? 0) + (stack.quantity | 0));
206 }
207 if (have.size !== need.size)
208 { return 0; }
209
210 let batch = Infinity;
211 for (const [key, qty] of need)
212 {
213 const got = have.get(key);
214 if (got == null || got % qty !== 0)
215 { return 0; }
216 batch = Math.min(batch, got / qty);
217 }
218 for (const key of have.keys())
219 {
220 if (!need.has(key))
221 { return 0; }
222 }
223 return Number.isFinite(batch) && batch > 0 ? batch | 0 : 0;
224}
225
226export function stepsMatchRecipe (takenSteps, recipeSteps)
227{
228 if (!Array.isArray(takenSteps) || !Array.isArray(recipeSteps))
229 { return false; }
230 if (takenSteps.length !== recipeSteps.length)
231 { return false; }
232 for (let i = 0; i < recipeSteps.length; i++)
233 {
234 const want = recipeSteps[i];
235 const got = takenSteps[i];
236 if (want.kind !== got.kind)
237 { return false; }
238 if (want.kind === AlchemyStepKind.insert)
239 {
240 if ((want.itemId | 0) !== (got.itemId | 0))
241 { return false; }
242 const wantPotion = want.potionKey ?? null;
243 const gotPotion = got.potionKey ?? null;
244 if (wantPotion || gotPotion)
245 {
246 if (wantPotion !== gotPotion)
247 { return false; }
248 }
249 }
250 }
251 return true;
252}
253
254/**
255 * Evaluate bottling: success potion + batch, or unstable failure.
256 * Underleveled Alchemy on a correct recipe also yields unstable.
257 */
258export function evaluateAlchemyBottle ({
259 skills,
260 brewStacks,
261 takenSteps,
262 potions = resolvedAlchemyPotions()
263})
264{
265 const level = skillLevel(skills, SkillId.alchemy);
266 for (const potion of potions)
267 {
268 const batch = alchemyBatchCount(potion.ingredients, brewStacks);
269 if (batch <= 0)
270 { continue; }
271 if (!stepsMatchRecipe(takenSteps, potion.steps))
272 { continue; }
273 if (level < (potion.minAlchemyLevel ?? 1))
274 {
275 return {
276 ok: true,
277 success: false,
278 batch: 1,
279 result: unstablePotionFromSteps(takenSteps),
280 reason: "alchemy-level",
281 recipe: potion
282 };
283 }
284 return {
285 ok: true,
286 success: true,
287 batch,
288 result: {
289 potionKey: potion.potionKey,
290 unstable: false,
291 displayName: potion.displayName,
292 color: potion.color,
293 fillLevel: potion.fillLevel ?? 4,
294 effect: potion.effect,
295 effectKey: potion.effect?.type ?? potion.potionKey,
296 minAlchemyLevel: potion.minAlchemyLevel ?? 1,
297 outputItemId: potion.outputItemId ?? null,
298 outputQuantity: potion.outputQuantity ?? 1,
299 requiresEmptyBottles: potion.requiresEmptyBottles !== false
300 },
301 recipe: potion
302 };
303 }
304 return {
305 ok: true,
306 success: false,
307 batch: 1,
308 result: unstablePotionFromSteps(takenSteps),
309 reason: "no-match"
310 };
311}
312
313export function recipePaperBody (potion)
314{
315 const lines = [
316 `${potion.displayName}`,
317 `Alchemy level required: ${potion.minAlchemyLevel ?? 1}`,
318 "",
319 "Ingredients (ratios):"
320 ];
321 for (const row of potion.ingredients ?? [])
322 {
323 if (row.potionKey)
324 {
325 const brew = alchemyPotionDefinition(row.potionKey);
326 lines.push(`- ${row.quantity}× ${brew?.displayName ?? row.potionKey} (full bottle)`);
327 continue;
328 }
329 lines.push(`- ${row.quantity}× ${alchemyItemLabel({
330 itemId: row.itemId,
331 key: row.key
332 })}`);
333 }
334 lines.push("", "Steps:");
335 for (const step of potion.steps ?? [])
336 { lines.push(`- ${formatAlchemyStep(step)}`); }
337 lines.push("", "Finish by bottling at the cauldron.");
338 return lines.join("\n");
339}
340
341export function potionItemInstance (result)
342{
343 return {
344 kind: "potion",
345 potionKey: result.potionKey,
346 unstable: !!result.unstable,
347 displayName: result.displayName,
348 color: result.color,
349 fillLevel: Math.max(1, Math.min(5, result.fillLevel | 0 || 4)),
350 effect: result.effect ?? null,
351 effectKey: result.effectKey ?? result.effect?.type ?? result.potionKey,
352 stepsHash: result.stepsHash ?? null,
353 minAlchemyLevel: result.minAlchemyLevel ?? null
354 };
355}
356
357/** Resolve a potion instance's gameplay effect (legacy rows may omit `effect`). */
358export function resolvePotionEffect (instance)
359{
360 if (!instance || instance.kind !== "potion")
361 { return null; }
362 if (instance.effect && typeof instance.effect === "object")
363 { return instance.effect; }
364 const potionKey = instance.potionKey;
365 if (!potionKey)
366 { return null; }
367 if (potionKey.startsWith("unstable:"))
368 {
369 const effectKey = potionKey.slice("unstable:".length) || instance.effectKey;
370 const entry = UNSTABLE_POTION_EFFECTS.find((row) => row.effectKey === effectKey);
371 return entry?.effect ?? null;
372 }
373 return alchemyPotionDefinition(potionKey)?.effect ?? null;
374}