hadean-old/src/Inventory.ts

38 lines
850 B
TypeScript
Raw Normal View History

2021-06-14 22:03:55 -04:00
import { Serializable } from 'frigid';
2021-06-15 15:02:47 -04:00
import { Game } from './Game.js';
import { Item, ItemState } from './Item.js';
2021-06-16 15:26:42 -04:00
import { Renderable } from './ui/UI.js';
2021-06-14 22:03:55 -04:00
2021-06-15 15:02:47 -04:00
export class Inventory extends Serializable implements Renderable {
items: ItemState[];
2021-06-14 22:03:55 -04:00
2021-06-15 15:02:47 -04:00
ctor() {
this.items ??= [];
2021-06-14 22:03:55 -04:00
}
2021-06-15 15:02:47 -04:00
static serializationDependencies() {
return [ItemState];
2021-06-14 22:03:55 -04:00
}
2021-06-15 15:02:47 -04:00
add(item: Item, qty: number = 1) {
2021-06-14 22:03:55 -04:00
const id = item.id;
2021-06-15 15:02:47 -04:00
const existingArr = this.items.filter(itemState => {
return itemState.itemId === id;
});
let existing: ItemState = null;
if(existingArr.length === 1) {
existing = existingArr[0];
}
if(existing) {
existing.qty += qty;
} else {
this.items.push(new ItemState(item, qty, {}));
}
Game.current.sync();
2021-06-14 22:03:55 -04:00
}
2021-06-15 15:02:47 -04:00
render() {
return this.items.map(item => item.render()).join('\n');
2021-06-14 22:03:55 -04:00
}
}