grechka-game/src3d/ui/inventory.js

81 lines
2.8 KiB
JavaScript

// Inventory UI
import { state } from '../core/state.js';
import { BLOCKS } from '../data/blocks.js';
import { ITEMS } from '../data/items.js';
import { TOOLS } from '../data/tools.js';
import { tex, itemTex } from '../render/textures.js';
import { playSound } from '../audio/sound-engine.js';
import { rebuildHotbar } from './hotbar.js';
export function renderInventory() {
const inventoryGrid = state.inventoryGrid;
const inv = state.inv;
const selected = state.selected;
inventoryGrid.innerHTML = '';
const items = Object.keys(inv).filter(id => inv[id] > 0);
for (let i = 0; i < 21; i++) {
const slot = document.createElement('div');
slot.className = 'inv-slot' + (i < items.length && items[i] === selected ? ' sel' : '');
if (i < items.length) {
const id = items[i];
// Canvas sprite: block > itemTex > emoji fallback > unknown item fallback
if (BLOCKS[id] && tex[id]) {
slot.style.backgroundImage = `url(${tex[id].toDataURL()})`;
slot.style.backgroundSize = 'cover';
} else if (itemTex[id]) {
slot.style.backgroundImage = `url(${itemTex[id].toDataURL()})`;
slot.style.backgroundSize = 'cover';
} else if (ITEMS[id]) {
slot.textContent = ITEMS[id].icon || '📦';
} else if (TOOLS[id]) {
slot.textContent = TOOLS[id].icon || '🔧';
} else if (id === 'iron_armor') {
slot.textContent = '🛡️';
slot.style.background = 'linear-gradient(135deg, #95a5a6 0%, #7f8c8d 100%)';
} else {
// Unknown item fallback — grey box with first letter
slot.textContent = id.charAt(0).toUpperCase();
slot.style.background = '#555';
slot.style.color = '#fff';
slot.style.fontWeight = '700';
slot.style.fontSize = '14px';
}
const count = document.createElement('div');
count.className = 'inv-count';
count.textContent = inv[id];
slot.appendChild(count);
slot.onclick = () => {
playSound('click');
state.selected = id;
state.recentItems = state.recentItems.filter(item => item !== id);
state.recentItems.unshift(id);
state.recentItems = state.recentItems.slice(0, 5);
rebuildHotbar();
renderInventory();
};
// Двойной клик для надевания брони
slot.ondblclick = () => {
if (id === 'iron_armor' && inv.iron_armor > 0) {
if (state.player.equippedArmor === 'iron_armor') {
state.player.equippedArmor = null;
state.player.armor = 0;
} else {
state.player.equippedArmor = 'iron_armor';
state.player.armor = BLOCKS['iron_armor'].armor;
}
playSound('click');
renderInventory();
}
};
}
inventoryGrid.appendChild(slot);
}
}