81 lines
1.9 KiB
TypeScript
81 lines
1.9 KiB
TypeScript
import { clampi, Node, StringName } from 'godot'
|
|
import ItemData from './item_data'
|
|
import { GArrayEnumerator } from './collection/enumerable'
|
|
import { Enumerable } from '../addons/enumerable-ts/src/index'
|
|
|
|
class ItemInstance {
|
|
readonly resource: ItemData
|
|
|
|
get name() {
|
|
return this.resource.name
|
|
}
|
|
|
|
get type() {
|
|
return this.resource.type
|
|
}
|
|
|
|
get max_quantity() {
|
|
return this.resource.max_quantity
|
|
}
|
|
|
|
quantity: number
|
|
|
|
constructor(resource: ItemData, quantity: number = 1) {
|
|
this.resource = resource
|
|
this.quantity = quantity
|
|
}
|
|
|
|
set_quantity(quantity: number = 1) {
|
|
this.quantity = clampi(quantity, 0, this.max_quantity)
|
|
}
|
|
|
|
increase_quantity(quantity: number = 1) {
|
|
this.set_quantity(this.quantity + quantity)
|
|
}
|
|
|
|
decrease_quantity(quantity: number = 1) {
|
|
this.set_quantity(this.quantity - quantity)
|
|
}
|
|
|
|
has_none(): boolean {
|
|
return this.quantity <= 0
|
|
}
|
|
}
|
|
|
|
export default class Inventory extends Node {
|
|
private static cache = new Map()
|
|
|
|
items: Map<StringName, ItemInstance> = new Map()
|
|
|
|
static find_inventory(root: Node): Inventory | null | undefined {
|
|
if (Inventory.cache.has(root)) {
|
|
return Inventory.cache.get(root)
|
|
}
|
|
|
|
const child_enumerator: GArrayEnumerator<Node> = new GArrayEnumerator(root.get_children())
|
|
const children = Enumerable.from(child_enumerator)
|
|
const inventory = children.find(child => child instanceof Inventory) as Inventory
|
|
|
|
if (inventory != null) {
|
|
Inventory.cache.set(root, inventory)
|
|
}
|
|
|
|
return inventory
|
|
}
|
|
|
|
add(item: ItemData, quantity: number = 1) {
|
|
const existing_item = this.items.get(item.name)
|
|
|
|
if (!existing_item) {
|
|
this.items.set(item.name, new ItemInstance(item, quantity))
|
|
} else {
|
|
existing_item.increase_quantity(quantity)
|
|
}
|
|
}
|
|
|
|
has(item: ItemData): boolean {
|
|
console.log('checking for', item.name)
|
|
return this.items.has(item.name)
|
|
}
|
|
}
|
|
|