88 lines
1.8 KiB
JavaScript
88 lines
1.8 KiB
JavaScript
|
import RES from './resource'
|
||
|
|
||
|
const MAX_STACK_SIZE = 999
|
||
|
|
||
|
const ItemRegistry = new (class ItemRegistry {
|
||
|
constructor () {
|
||
|
this.items = {}
|
||
|
}
|
||
|
|
||
|
register (name, item) {
|
||
|
this.items[name] = item
|
||
|
}
|
||
|
|
||
|
get (name) {
|
||
|
return this.items[name]
|
||
|
}
|
||
|
})()
|
||
|
|
||
|
class Item {
|
||
|
constructor (name, img, description) {
|
||
|
this.name = name
|
||
|
this._img = img
|
||
|
this.description = description
|
||
|
ItemRegistry.register(name, this)
|
||
|
}
|
||
|
|
||
|
get image () {
|
||
|
return RES.loadImage(this._img, true)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
class ItemPlaceable extends Item {
|
||
|
constructor (tile, name, img, description) {
|
||
|
super(name, img, description)
|
||
|
this.placeable = tile
|
||
|
}
|
||
|
}
|
||
|
|
||
|
class ItemStack {
|
||
|
static fromIString (str) {
|
||
|
if (typeof str !== 'string') return
|
||
|
let strpl = str.split(' ')
|
||
|
let iname = strpl[0]
|
||
|
let count = strpl[1]
|
||
|
let item = ItemRegistry.get(iname)
|
||
|
let istack = new ItemStack()
|
||
|
istack.item = item
|
||
|
istack.count = count || 1
|
||
|
return istack
|
||
|
}
|
||
|
|
||
|
static new (itemdef, count = 1, metadata) {
|
||
|
if (itemdef instanceof ItemStack) return itemdef.copy()
|
||
|
if (typeof itemdef === 'string') return ItemStack.fromIString(itemdef)
|
||
|
if (!(itemdef instanceof Item)) throw new Error('Invalid Item Definition!')
|
||
|
let istack = new ItemStack()
|
||
|
istack.item = itemdef
|
||
|
istack.count = count
|
||
|
istack.metadata = metadata
|
||
|
return istack
|
||
|
}
|
||
|
|
||
|
copy () {
|
||
|
return ItemStack.new(this.item, this.count, this.metadata)
|
||
|
}
|
||
|
|
||
|
get name () {
|
||
|
return this.item ? this.item.name : ''
|
||
|
}
|
||
|
|
||
|
isEmpty () {
|
||
|
return this.item === null || this.count === 0
|
||
|
}
|
||
|
|
||
|
takeItem (c) {
|
||
|
let a = this.copy()
|
||
|
if (c > this.count) {
|
||
|
this.count = 0
|
||
|
return a
|
||
|
}
|
||
|
this.count -= c
|
||
|
a.count = c
|
||
|
return a
|
||
|
}
|
||
|
}
|
||
|
|
||
|
export { Item, ItemPlaceable, ItemStack, ItemRegistry, MAX_STACK_SIZE }
|