BlueGit

timfa questward

Files

questward / shared / alchemy / recipes.js

recipes.js

recipes.js 6.2 KiB Download Raw
1import { AlchemyStepKind, ALCHEMY_POTION_DEFINITIONS, UNSTABLE_POTION_EFFECTS } from "../definitions/alchemy.js";
2import { ITEM_DEFINITIONS, 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 const def = itemDefinition(step.itemId);
11 return `insert ${def?.displayName ?? step.itemKey ?? step.itemId}`;
12 }
13 return step.kind;
14}
15
16export function hashAlchemySteps (steps)
17{
18 const text = (steps ?? []).map((step) =>
19 {
20 if (step.kind === AlchemyStepKind.insert)
21 { return `insert:${step.itemId ?? step.itemKey}`; }
22 return step.kind;
23 }).join("|");
24 let hash = 2166136261;
25 for (let i = 0; i < text.length; i++)
26 {
27 hash ^= text.charCodeAt(i);
28 hash = Math.imul(hash, 16777619);
29 }
30 return hash >>> 0;
31}
32
33export function unstablePotionFromSteps (steps)
34{
35 const hash = hashAlchemySteps(steps);
36 const index = hash % UNSTABLE_POTION_EFFECTS.length;
37 const effect = UNSTABLE_POTION_EFFECTS[index];
38 return {
39 potionKey: `unstable:${effect.effectKey}`,
40 unstable: true,
41 stepsHash: hash,
42 displayName: effect.displayName,
43 color: effect.color,
44 fillLevel: effect.fillLevel,
45 effect: effect.effect,
46 effectKey: effect.effectKey
47 };
48}
49
50export function itemIdByKeyMap ()
51{
52 const map = new Map();
53 for (const def of Object.values(ITEM_DEFINITIONS))
54 {
55 if (def?.key != null)
56 { map.set(def.key, def.itemId); }
57 }
58 return map;
59}
60
61/**
62 * Resolve ingredient itemIds on potion defs that use item keys (after items are loaded).
63 */
64export function resolvePotionIngredientIds (potion, byKey = itemIdByKeyMap())
65{
66 const ingredients = (potion.ingredients ?? []).map((row) =>
67 {
68 const itemId = row.itemId ?? byKey.get(row.key) ?? null;
69 return { itemId, key: row.key, quantity: row.quantity };
70 });
71 const steps = (potion.steps ?? []).map((step) =>
72 {
73 if (step.kind !== AlchemyStepKind.insert)
74 { return { ...step }; }
75 const itemId = step.itemId ?? byKey.get(step.itemKey) ?? null;
76 return { kind: AlchemyStepKind.insert, itemId, itemKey: step.itemKey };
77 });
78 return { ...potion, ingredients, steps };
79}
80
81let cachedResolvedPotions = null;
82
83export function resolvedAlchemyPotions ()
84{
85 if (!cachedResolvedPotions)
86 {
87 const byKey = itemIdByKeyMap();
88 cachedResolvedPotions = Object.values(ALCHEMY_POTION_DEFINITIONS)
89 .map((potion) => resolvePotionIngredientIds(potion, byKey));
90 }
91 return cachedResolvedPotions;
92}
93
94/**
95 * Greatest integer batch size for reserved slot quantities vs recipe ingredient ratios.
96 * Returns 0 if ratios do not match (wrong items or non-integer multiple).
97 */
98export function alchemyBatchCount (recipeIngredients, reservedStacks)
99{
100 const need = new Map();
101 for (const row of recipeIngredients ?? [])
102 {
103 if (row.itemId == null || row.quantity <= 0)
104 { return 0; }
105 need.set(row.itemId, (need.get(row.itemId) ?? 0) + row.quantity);
106 }
107 if (need.size === 0 || need.size > 4)
108 { return 0; }
109
110 const have = new Map();
111 for (const stack of reservedStacks ?? [])
112 {
113 if (!stack?.itemId || !(stack.quantity > 0))
114 { continue; }
115 have.set(stack.itemId, (have.get(stack.itemId) ?? 0) + stack.quantity);
116 }
117 if (have.size !== need.size)
118 { return 0; }
119
120 let batch = Infinity;
121 for (const [itemId, qty] of need)
122 {
123 const got = have.get(itemId);
124 if (got == null || got % qty !== 0)
125 { return 0; }
126 batch = Math.min(batch, got / qty);
127 }
128 for (const itemId of have.keys())
129 {
130 if (!need.has(itemId))
131 { return 0; }
132 }
133 return Number.isFinite(batch) && batch > 0 ? batch | 0 : 0;
134}
135
136export function stepsMatchRecipe (takenSteps, recipeSteps)
137{
138 if (!Array.isArray(takenSteps) || !Array.isArray(recipeSteps))
139 { return false; }
140 if (takenSteps.length !== recipeSteps.length)
141 { return false; }
142 for (let i = 0; i < recipeSteps.length; i++)
143 {
144 const want = recipeSteps[i];
145 const got = takenSteps[i];
146 if (want.kind !== got.kind)
147 { return false; }
148 if (want.kind === AlchemyStepKind.insert && want.itemId !== got.itemId)
149 { return false; }
150 }
151 return true;
152}
153
154/**
155 * Evaluate bottling: success potion + batch, or unstable failure.
156 * Underleveled Alchemy on a correct recipe also yields unstable.
157 */
158export function evaluateAlchemyBottle ({
159 skills,
160 brewStacks,
161 takenSteps,
162 potions = resolvedAlchemyPotions()
163})
164{
165 const level = skillLevel(skills, SkillId.alchemy);
166 for (const potion of potions)
167 {
168 const batch = alchemyBatchCount(potion.ingredients, brewStacks);
169 if (batch <= 0)
170 { continue; }
171 if (!stepsMatchRecipe(takenSteps, potion.steps))
172 { continue; }
173 if (level < (potion.minAlchemyLevel ?? 1))
174 {
175 return {
176 ok: true,
177 success: false,
178 batch: 1,
179 result: unstablePotionFromSteps(takenSteps),
180 reason: "alchemy-level"
181 };
182 }
183 return {
184 ok: true,
185 success: true,
186 batch,
187 result: {
188 potionKey: potion.potionKey,
189 unstable: false,
190 displayName: potion.displayName,
191 color: potion.color,
192 fillLevel: potion.fillLevel ?? 4,
193 effect: potion.effect,
194 effectKey: potion.effect?.type ?? potion.potionKey,
195 minAlchemyLevel: potion.minAlchemyLevel ?? 1
196 },
197 recipe: potion
198 };
199 }
200 return {
201 ok: true,
202 success: false,
203 batch: 1,
204 result: unstablePotionFromSteps(takenSteps),
205 reason: "no-match"
206 };
207}
208
209export function recipePaperBody (potion)
210{
211 const lines = [
212 `${potion.displayName}`,
213 `Alchemy level required: ${potion.minAlchemyLevel ?? 1}`,
214 "",
215 "Ingredients (ratios):"
216 ];
217 for (const row of potion.ingredients ?? [])
218 {
219 const def = itemDefinition(row.itemId);
220 lines.push(`- ${row.quantity}× ${def?.displayName ?? row.key ?? row.itemId}`);
221 }
222 lines.push("", "Steps:");
223 for (const step of potion.steps ?? [])
224 { lines.push(`- ${formatAlchemyStep(step)}`); }
225 lines.push("", "Finish by bottling at the cauldron.");
226 return lines.join("\n");
227}
228
229export function potionItemInstance (result)
230{
231 return {
232 kind: "potion",
233 potionKey: result.potionKey,
234 unstable: !!result.unstable,
235 displayName: result.displayName,
236 color: result.color,
237 fillLevel: Math.max(1, Math.min(5, result.fillLevel | 0 || 4)),
238 effect: result.effect ?? null,
239 effectKey: result.effectKey ?? result.effect?.type ?? result.potionKey,
240 stepsHash: result.stepsHash ?? null,
241 minAlchemyLevel: result.minAlchemyLevel ?? null
242 };
243}