tilegame/src/inventory.js

91 lines
2.3 KiB
JavaScript

import { canvas, ctx } from './canvas'
import { Item, ItemTool, ItemStack, MAX_STACK_SIZE } from './items'
const SLOT_SIZE = 32
class Inventory {
constructor (size) {
this.size = size
this.items = []
this.selected = 0
}
addItem (i) {
if (typeof i === 'string' || i instanceof Item) i = ItemStack.new(i)
let addedTo = false
let leftover = null
for (let k in this.items) {
if (addedTo) break
let itm = this.items[k]
if (itm.name === i.name || itm.isEmpty()) {
if (itm.isEmpty()) itm.item = i.item
let addedCount = itm.count + i.count
if (addedCount > MAX_STACK_SIZE) {
let m = addedCount - MAX_STACK_SIZE
let n = itm.copy()
n.count = m
itm.count = MAX_STACK_SIZE
if (this.items.length >= this.size) {
leftover = n
addedTo = true
} else {
continue
}
} else {
itm.count += i.count
addedTo = true
}
}
}
if (!addedTo) {
if (this.items.length >= this.size) {
return i
}
this.items.push(i)
}
return leftover
}
getItem (slot) {
if (this.isEmpty(slot)) return null
return this.items[slot]
}
takeItem (slot, count) {
if (this.isEmpty(slot)) return null
let i = this.items[slot]
if (!count || count > i.count) return i
i.count -= count
let copied = i.copy()
copied.count = count
return copied
}
isEmpty (slot) {
if (!this.items[slot] || this.items[slot].isEmpty()) return true
return false
}
draw () {
for (let i = 0; i < this.size; i++) {
let stack = this.items[i]
let x = canvas.width / 2 + i * (SLOT_SIZE + 8) - this.size / 2 * SLOT_SIZE
ctx.fillStyle = (this.selected === i) ? '#f00' : '#ddd'
ctx.fillRect(x, 16, SLOT_SIZE, SLOT_SIZE)
if (!stack || stack.isEmpty()) continue
ctx.drawImage(stack.item.image, x, 16, SLOT_SIZE, SLOT_SIZE)
if (stack.item instanceof ItemTool) continue
ctx.font = '16px sans'
let measure = ctx.measureText(stack.count)
ctx.fillStyle = '#000'
ctx.fillText(stack.count, x + SLOT_SIZE / 2 - measure.width / 2, 8 + SLOT_SIZE)
ctx.fillStyle = '#fff'
ctx.fillText(stack.count, x + SLOT_SIZE / 2 - measure.width / 2 + 1, 8 + SLOT_SIZE + 1)
}
}
}
export { Inventory }