BlueGit

timfa questward

Files

questward / client / src / play / crafting.js

crafting.js

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