BlueGit

timfa questward

Files

questward / client / src / play / crafting.js

crafting.js

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