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