An inventory plugin that never lies: transactional add, equip and use in a vanilla JS 2D engine
Описание и применение
Плагин BeeInventory обеспечивает атомарные операции с инвентарём в 2D‑играх, предотвращая исчезновение предметов и неконсистентные состояния. Он возвращает точные результаты добавления, откатывает при ошибках использования и сохраняет только данные, необходимые для загрузки.
Задача
Typical 2D game inventories often end up in inconsistent states: items disappear silently when the bag is full, equip operations fail halfway leaving items in neither slot nor hand, and use callbacks can throw after the item has been removed.
Результат
The plugin ensures inventory operations are atomic and transparent, preventing silent failures and state corruption while keeping the engine core untouched.
Рабочий процесс
- 1. Create a BeeEngine instance and register the BeeInventory plugin with desired slots and equipSlots.
- 2. Define item types with properties like name, maxStack, consumable, and onUse callbacks.
- 3. Use inventory.add(itemId, quantity) to add items; it returns {added, left} indicating how many were added and how many could not fit.
- 4. Use inventory.use(slotIndex, target) to consume an item; the operation rolls back if onUse throws or returns false.
- 5. Use inventory.move, equip, unequip for atomic transfers between slots and equipment.
- 6. Query inventory.get, list, equipped for read‑only copies of state.
- 7. Persist inventory state via inventory.toJSON(), which stores only slots and equipment.
- 8. Handle UI and game logic (e.g., showing “Bag full” messages) based on the returned leftovers or operation success.
- 9. Run provided Node tests to verify correctness.
- 10. Extend the engine with additional plugins without modifying core engine code.
Доказательства
Every 2D game ends up with an inventory. And almost every first inventory looks the same: an items[] array living in the scene, a few push calls, and a growing pile of if statements around it.
add fills existing stacks first, then empty slots. If there's no room left, it doesn't throw the extra items away. It returns them as left.
These three either succeed completely or leave the state exactly as it was. No half‑moved stacks, no item that vanished between the bag and the hand.
if onUse throws, the error is not swallowed: it propagates to the caller, and the inventory is restored to a snapshot taken before the call
get, list and equipped return copies. Code outside can't mutate the inventory by accident by editing an object it got back.
- Дата записи: 2026-10-10T17:56:18.548Z