BlueGit

timfa questward

Files

questward / shared / alchemy / recipes.js

recipes.js

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