BlueGit

timfa questward

Files

questward / client / src / play / crafting.js

crafting.js

crafting.js 8.4 KiB Download Raw
1import {
2 itemDefinition,
3 itemDisplayName,
4 itemAssetPathForStack,
5 formatQuantity
6} from "/shared/definitions/items.js";
7import { craftingStationDefinition } from "/shared/definitions/craftingStations.js";
8import {
9 CRAFT_DURATION_MS,
10 canStartCraft,
11 countItemInSlots,
12 hasRecipeInputs,
13 recipesForStation
14} from "/shared/crafting/recipes.js";
15import { applyItemIcon } from "../render/potionIcon.js";
16
17export function initCrafting ({
18 socket,
19 MessageType,
20 getInventorySlots,
21 getSkillLevel
22})
23{
24 const backdrop = document.getElementById("craft-backdrop");
25 const panel = document.getElementById("craft-panel");
26 const stationName = document.getElementById("craft-station-name");
27 const recipeGrid = document.getElementById("craft-recipe-grid");
28 const detailEmpty = document.getElementById("craft-detail-empty");
29 const detailBody = document.getElementById("craft-detail-body");
30 const outputImg = document.getElementById("craft-output-img");
31 const outputName = document.getElementById("craft-output-name");
32 const inputsList = document.getElementById("craft-inputs");
33 const statusEl = document.getElementById("craft-status");
34 const progressWrap = document.getElementById("craft-progress");
35 const progressFill = document.getElementById("craft-progress-fill");
36 const craftButton = document.getElementById("craft-button");
37
38 let open = false;
39 let stationId = null;
40 let recipes = [];
41 let selectedRecipeId = null;
42 let crafting = false;
43 let craftTimer = null;
44 let craftAnimFrame = null;
45 let craftStartedAt = 0;
46
47 document.getElementById("craft-close").addEventListener("click", () => close());
48 backdrop.addEventListener("click", () => close());
49 craftButton.addEventListener("click", () => startCraft());
50
51 function selectedRecipe ()
52 {
53 return recipes.find((recipe) => recipe.recipeId === selectedRecipeId) ?? null;
54 }
55
56 function stationSkillLevel ()
57 {
58 const def = craftingStationDefinition(stationId);
59 return getSkillLevel?.(def?.skillId) ?? 1;
60 }
61
62 function refresh ()
63 {
64 if (!open)
65 { return; }
66 renderRecipeGrid();
67 renderDetail();
68 }
69
70 function renderRecipeGrid ()
71 {
72 recipeGrid.replaceChildren();
73 for (const recipe of recipes)
74 {
75 recipeGrid.append(renderRecipeCell(recipe));
76 }
77 }
78
79 function renderRecipeCell (recipe)
80 {
81 const def = itemDefinition(recipe.output.itemId);
82 const stack = { itemId: recipe.output.itemId, quantity: recipe.output.quantity | 0 || 1 };
83 const cell = document.createElement("button");
84 cell.type = "button";
85 cell.className = "craft-recipe-cell";
86 if (recipe.recipeId === selectedRecipeId)
87 { cell.classList.add("selected"); }
88
89 const img = document.createElement("img");
90 img.alt = def?.displayName ?? "Item";
91 applyItemIcon(img, stack, itemAssetPathForStack(stack));
92
93 const label = document.createElement("span");
94 label.className = "craft-recipe-name";
95 label.textContent = def?.displayName ?? "Item";
96
97 cell.append(img, label);
98 cell.addEventListener("click", () =>
99 {
100 if (crafting)
101 { return; }
102 selectedRecipeId = recipe.recipeId;
103 renderRecipeGrid();
104 renderDetail();
105 });
106 return cell;
107 }
108
109 function renderDetail ()
110 {
111 const recipe = selectedRecipe();
112 if (!recipe)
113 {
114 detailEmpty.hidden = false;
115 detailBody.hidden = true;
116 return;
117 }
118 detailEmpty.hidden = true;
119 detailBody.hidden = false;
120
121 const outputStack = {
122 itemId: recipe.output.itemId,
123 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
124 };
125 applyItemIcon(outputImg, outputStack, itemAssetPathForStack(outputStack));
126 outputImg.alt = itemDisplayName(outputStack);
127 const qtySuffix = outputStack.quantity > 1 ? ` ×${formatQuantity(outputStack.quantity)}` : "";
128 outputName.textContent = `${itemDisplayName(outputStack)}${qtySuffix}`;
129
130 inputsList.replaceChildren();
131 const slots = getInventorySlots?.() ?? [];
132 for (const input of recipe.inputs ?? [])
133 {
134 inputsList.append(renderInputRow(input, slots));
135 }
136
137 updateCraftState(slots, recipe);
138 }
139
140 function renderInputRow (input, slots)
141 {
142 const need = input.quantity | 0;
143 const have = countItemInSlots(slots, input.itemId);
144 const stack = { itemId: input.itemId, quantity: need };
145 const row = document.createElement("li");
146 row.className = "craft-input-row";
147 if (have < need)
148 { row.classList.add("short"); }
149
150 const img = document.createElement("img");
151 img.alt = itemDisplayName(stack);
152 applyItemIcon(img, stack, itemAssetPathForStack(stack));
153
154 const text = document.createElement("span");
155 text.textContent = `${itemDisplayName(stack)} — ${formatQuantity(have)} / ${formatQuantity(need)}`;
156 row.append(img, text);
157 return row;
158 }
159
160 function updateCraftState (slots, recipe)
161 {
162 if (crafting)
163 {
164 craftButton.disabled = true;
165 return;
166 }
167 const skill = stationSkillLevel();
168 const minLevel = recipe.minSkillLevel | 0 || 1;
169 if (skill < minLevel)
170 {
171 statusEl.textContent = `Requires skill level ${minLevel} (you have ${skill}).`;
172 craftButton.disabled = true;
173 return;
174 }
175 const slotsSnapshot = slots ?? getInventorySlots?.() ?? [];
176 if (canStartCraft(slotsSnapshot, recipe, skill))
177 {
178 statusEl.textContent = `Crafting takes ${CRAFT_DURATION_MS / 1000} seconds.`;
179 craftButton.disabled = false;
180 return;
181 }
182 if (!hasRecipeInputs(slotsSnapshot, recipe))
183 {
184 statusEl.textContent = "Missing materials.";
185 }
186 else
187 {
188 statusEl.textContent = "Not enough bag space for the result.";
189 }
190 craftButton.disabled = true;
191 }
192
193 function startCraft ()
194 {
195 const recipe = selectedRecipe();
196 if (!recipe || crafting)
197 { return; }
198 const slots = getInventorySlots?.() ?? [];
199 if (!canStartCraft(slots, recipe, stationSkillLevel()))
200 {
201 renderDetail();
202 return;
203 }
204 crafting = true;
205 craftButton.disabled = true;
206 progressWrap.hidden = false;
207 progressFill.style.width = "0%";
208 statusEl.textContent = "Crafting…";
209 craftStartedAt = performance.now();
210 socket.send({
211 type: MessageType.startCraft,
212 stationId,
213 recipeId: recipe.recipeId
214 });
215 animateProgress();
216 craftTimer = window.setTimeout(() => finishCraft(true), CRAFT_DURATION_MS);
217 }
218
219 function animateProgress ()
220 {
221 const tick = (now) =>
222 {
223 if (!crafting)
224 { return; }
225 const elapsed = now - craftStartedAt;
226 const pct = Math.min(100, (elapsed / CRAFT_DURATION_MS) * 100);
227 progressFill.style.width = `${pct}%`;
228 if (pct < 100)
229 { craftAnimFrame = requestAnimationFrame(tick); }
230 };
231 craftAnimFrame = requestAnimationFrame(tick);
232 }
233
234 function stopCraftAnimation ()
235 {
236 if (craftTimer != null)
237 {
238 clearTimeout(craftTimer);
239 craftTimer = null;
240 }
241 if (craftAnimFrame != null)
242 {
243 cancelAnimationFrame(craftAnimFrame);
244 craftAnimFrame = null;
245 }
246 crafting = false;
247 progressWrap.hidden = true;
248 progressFill.style.width = "0%";
249 }
250
251 function finishCraft (timedOut)
252 {
253 stopCraftAnimation();
254 if (timedOut)
255 {
256 statusEl.textContent = "Waiting for server…";
257 }
258 renderDetail();
259 }
260
261 function openStation (nextStationId)
262 {
263 const def = craftingStationDefinition(nextStationId);
264 if (!def)
265 { return; }
266 stationId = nextStationId;
267 recipes = recipesForStation(nextStationId);
268 selectedRecipeId = recipes[0]?.recipeId ?? null;
269 stationName.textContent = def.displayName;
270 open = true;
271 panel.hidden = false;
272 backdrop.hidden = false;
273 statusEl.textContent = recipes.length
274 ? "Select a recipe."
275 : "No recipes defined for this station yet.";
276 renderRecipeGrid();
277 renderDetail();
278 }
279
280 function close ()
281 {
282 if (crafting)
283 {
284 socket.send({ type: MessageType.cancelCraft });
285 stopCraftAnimation();
286 }
287 open = false;
288 stationId = null;
289 recipes = [];
290 selectedRecipeId = null;
291 panel.hidden = true;
292 backdrop.hidden = true;
293 detailEmpty.hidden = false;
294 detailBody.hidden = true;
295 statusEl.textContent = "";
296 }
297
298 function handleCraftResult (message)
299 {
300 if (!open || message.recipeId !== selectedRecipeId)
301 { return; }
302 stopCraftAnimation();
303 if (message.ok)
304 {
305 statusEl.textContent = message.burned
306 ? "The food burned."
307 : "Craft complete.";
308 }
309 else
310 {
311 statusEl.textContent = message.error ?? "Could not craft.";
312 }
313 renderDetail();
314 }
315
316 return {
317 openStation,
318 close,
319 refresh,
320 handleCraftResult,
321 isOpen ()
322 {
323 return open;
324 },
325 isBlocking ()
326 {
327 if (!open)
328 { return false; }
329 if (backdrop && !backdrop.hidden)
330 { return true; }
331 const x = GameInput.mousePosition.x;
332 const y = GameInput.mousePosition.y;
333 const box = panel.getBoundingClientRect();
334 return x >= box.left && x < box.right && y >= box.top && y < box.bottom;
335 },
336 reset ()
337 {
338 close();
339 }
340 };
341}