<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,…
- User
<style> #mine { border: 2px solid black; background-color: #4d999f; border-radius: 10px; font-family: "Gill Sans", "Gill Sans MT", Calibri, "Trebuchet MS", sans-serif; font-size: x-large; } #craft { background-color: #4d999f; width: 500px; height: 360px; border: 2px solid black; position: relative; left: 515.4px; bottom: 530px; font-family: "Gill Sans", "Gill Sans MT", Calibri, "Trebuchet MS", sans-serif; font-size: large; text-align: center; } #inputContainer { gap: 5px; } #textBox { font-size: 15px; border: 1px solid black; padding: 5px; height: 30px; font-family: "Gill Sans", "Gill Sans MT", Calibri, "Trebuchet MS", sans-serif; } #craftButton { border: 1px solid black; background-color: white; border-radius: 3px; height: 33px; font-family: "Gill Sans", "Gill Sans MT", Calibri, "Trebuchet MS", sans-serif; } #inventory { width: 1000px; height: 300px; overflow-y: scroll; border: 1px solid black; justify-content: center; align-items: center; position: relative; left: 515px; bottom: 542px; } #inventory ul { display: grid; grid-template-columns: repeat(9, 1fr); grid-auto-rows: 1fr; gap: 4px; width: 100%; height: 100%; list-style: none; padding: 0; margin: 0; } #inventory ul li { border: 1px solid black; padding: 10px; font-size: 15px; text-align: center; justify-content: center; align-items: center; background-color: #4d999f; font-family: "Gill Sans", "Gill Sans MT", Calibri, "Trebuchet MS", sans-serif; } body { overflow-y: hidden; background: rgb(149, 104, 239); } #progressContainer { width: 500px; /* ширина такая же, как у кнопки */ border: 2px solid black; /* рамка для контейнера */ border-radius: 5px; margin-top: 10px; background-color: #4d999f; } #progressBar { width: 0; height: 30px; background-color: white; transition: width 0.04s linear; border-radius: 5px; } #craftNeed { list-style: none; padding: 0; margin: 0; max-height: 150px; overflow-y: auto; text-align: center; } #craftNeed li { display: block; margin: 5px 0; } #craftDoButton { border: 1px solid black; background-color: white; border-radius: 3px; height: 33px; font-family: "Gill Sans", "Gill Sans MT", Calibri, "Trebuchet MS", sans-serif; visibility: hidden; } </style><button id="mine" style="height: 500px; width: 500px;" onclick="mine()">Mine</button> <div id="progressContainer"> <div id="progressBar"></div> </div> <div id="inventory"> <ul id="list"></ul> </div> <div id="craft"> <h3>Craft</h3> <div id="inputContainer"> <input type="text" id="textBox" placeholder="Craft ID"> <button id="craftButton" onclick="findCraftID()">Find Craft</button> <ul id="craftNeed"></ul> <button id="craftDoButton" onclick="craft()">Craft</button> </div> </div> <script> // main variables let isMining = false; //for mine function let inventory = []; //main inventory let itemsID = ["Stick", "Flint", "Small Stone", "Oak Log"] //ids of items let allItemsID = ["Oak Planks"] let craftID = { 1: {need: ["Oak Log", 4, "Stick", 2], output: ["Oak Planks", 1, "Stuff", 2]} } let amountToGive = 122; //mine function to give let miningTime = 1000; window.onload = function() { inventorySetup(); addInvenetoryUI(); }; function getItemSearch() { let item = itemsID[Math.floor(Math.random() * itemsID.length)]; return item; } function mine() { if (isMining) return; isMining = true; startBar(miningTime); setTimeout(() => { isMining = false; let newItem = getItemSearch(); let remaining = Math.floor(Math.random() * 2) + amountToGive; // Проходим по инвентарю, чтобы распределить предметы for (let i = 0; i < inventory.length; i++) { if (inventory[i].name === newItem && inventory[i].amount < 64) { let spaceLeft = 64 - inventory[i].amount; let toAdd = Math.min(spaceLeft, remaining); inventory[i].amount += toAdd; remaining -= toAdd; // Обновляем UI document.getElementById(i).innerHTML = inventory[i].name + " " + inventory[i].amount + "x"; if (remaining === 0) break; } } // Если остались предметы, заполняем пустые слоты for (let i = 0; i < inventory.length && remaining > 0; i++) { if (inventory[i] === "Empty") { let toAdd = Math.min(64, remaining); inventory[i] = { name: newItem, amount: toAdd }; remaining -= toAdd; // Обновляем UI document.getElementById(i).innerHTML = inventory[i].name + " " + inventory[i].amount + "x"; } } }, miningTime); } function addInvenetoryUI(){ for (i = 0; i < 36; i++) { const inventoryHTML = document.getElementById("list"); const li = document.createElement("li"); li.setAttribute("id", i); li.innerHTML = inventory[i]; inventoryHTML.appendChild(li); } } function inventorySetup() { for (i = 0; i < 36; i++) { inventory.push("Empty") } } function startBar(time) { const progressBar = document.getElementById("progressBar") progressBar.style.width = '0%'; // Ресетим бар let startTime = null; function animateProgress(timestamp) { if (!startTime) startTime = timestamp; // ищем время после запуска const elapsed = timestamp - startTime; const width = Math.min((elapsed / time) * 100, 100); // ширина progressBar.style.width = width + '%'; if (elapsed < time) { requestAnimationFrame(animateProgress); // анимация } else { progressBar.style.width = '0%'; // ресет } } requestAnimationFrame(animateProgress); // старт анимации } function findCraftID() { const inputValue = document.getElementById("textBox").value; const craftHTML = document.getElementById("craftNeed"); craftHTML.innerHTML = ""; // Clear previous ingredients document.getElementById("craftDoButton").style.visibility = "hidden" if (craftID[inputValue]) { const ingredients = craftID[inputValue]["need"]; const output = craftID[inputValue]["output"]; document.getElementById("craftDoButton").style.visibility = "visible" // Display ingredients for (let i = 0; i < ingredients.length; i += 2) { const li = document.createElement("li"); li.innerHTML = `${ingredients[i]} x${ingredients[i + 1]}`; craftHTML.appendChild(li); } // Display output for (let i = 0; i < output.length; i += 2) { const outputLi = document.createElement("li"); outputLi.style.fontWeight = "bold"; outputLi.innerHTML = `Output: ${output[i]} x${output[i + 1]}`; craftHTML.appendChild(outputLi); } } else { const li = document.createElement("li"); li.innerHTML = "Invalid Craft ID"; craftHTML.appendChild(li); } } function craft() { const inputValue = document.getElementById("textBox").value; // Получаем ID крафта const craftRecipe = craftID[inputValue]; // Берем рецепт по ID if (!craftRecipe) { alert("Invalid Craft ID"); // Если ID неправильный return; } const requiredItems = craftRecipe.need; // Требуемые ресурсы const outputItems = craftRecipe.output; // Выходные ресурсы // Проверяем наличие всех ингредиентов let hasAllIngredients = true; const slotsToUse = []; // Запоминаем слоты, которые будем использовать for (let i = 0; i < requiredItems.length; i += 2) { const itemName = requiredItems[i]; const requiredAmount = requiredItems[i + 1]; let amountFound = 0; for (let j = 0; j < inventory.length; j++) { if (inventory[j].name === itemName) { amountFound += inventory[j].amount; slotsToUse.push(j); // Запоминаем слоты if (amountFound >= requiredAmount) break; } } if (amountFound < requiredAmount) { hasAllIngredients = false; break; } } if (!hasAllIngredients) { alert("Not enough ingredients"); return; } // Проверяем, есть ли место для выходных предметов let hasSpace = true; const freeSlots = []; for (let i = 0; i < inventory.length; i++) { if (inventory[i] === "Empty") { freeSlots.push(i); // Находим свободные слоты hasSpace = true; } else { hasSpace = false; } } if (!hasSpace) { alert("Not enough Space in Inventory"); return; } // Удаляем использованные ресурсы if (hasSpace = true) { for (let i = 0; i < requiredItems.length; i += 2) { const itemName = requiredItems[i]; let requiredAmount = requiredItems[i + 1]; for (let j = 0; j < slotsToUse.length; j++) { const slot = slotsToUse[j]; if (inventory[slot].name === itemName) { const availableAmount = inventory[slot].amount; if (availableAmount <= requiredAmount) { requiredAmount -= availableAmount; inventory[slot] = "Empty"; // Очищаем слот document.getElementById(slot).innerHTML = "Empty"; // Обновляем UI } else { inventory[slot].amount -= requiredAmount; requiredAmount = 0; document.getElementById(slot).innerHTML = `${inventory[slot].name} ${inventory[slot].amount}x`; // Обновляем UI } if (requiredAmount === 0) break; } } } } // Добавляем результат крафта if (hasSpace = true) { for (let i = 0; i < outputItems.length; i += 2) { const itemName = outputItems[i]; let outputAmount = outputItems[i + 1]; for (let j = 0; j < inventory.length; j++) { if (inventory[j] === "Empty") { const toAdd = Math.min(64, outputAmount); inventory[j] = { name: itemName, amount: toAdd }; outputAmount -= toAdd; // Обновляем UI document.getElementById(j).innerHTML = `${itemName} ${toAdd}x`; if (outputAmount === 0) break; } else if (inventory[j].name === itemName && inventory[j].amount < 64) { const spaceLeft = 64 - inventory[j].amount; const toAdd = Math.min(spaceLeft, outputAmount); inventory[j].amount += toAdd; outputAmount -= toAdd; // Обновляем UI document.getElementById(j).innerHTML = `${itemName} ${inventory[j].amount}x`; if (outputAmount === 0) break; } } } } } </script> - Assistant
To fix the part of the code you mentioned so that it correctly checks whether there is enough space in the inventory for new crafted items — either by finding empty slots or by checking whether existing items in the inventory can accommodate more items (i.e., their amounts are less than 64) — we should modify the loop.
- User
what is "itemName"? where its defined
- Assistant