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';
|
2021-06-22 19:25:41 -04:00
|
|
|
import { Item, ItemState } from './registries/Items.js';
|
|
|
|
|
import { Popup } from './ui/Popup.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 {
|
2021-06-26 03:11:18 -04:00
|
|
|
items: ItemState<any>[];
|
2021-06-14 22:03:55 -04:00
|
|
|
|
2021-06-22 19:25:41 -04:00
|
|
|
ctor() {
|
|
|
|
|
this.items ??= [];
|
|
|
|
|
}
|
2021-06-14 22:03:55 -04:00
|
|
|
|
2021-06-22 19:25:41 -04:00
|
|
|
validate() {
|
2021-06-26 03:11:18 -04:00
|
|
|
const invalid: ItemState<any>[] = [];
|
2021-06-22 19:25:41 -04:00
|
|
|
for(const itemState of this.items) {
|
|
|
|
|
try {
|
|
|
|
|
itemState.item;
|
|
|
|
|
} catch {
|
|
|
|
|
invalid.push(itemState);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if(invalid.length === 0) return;
|
|
|
|
|
|
|
|
|
|
for(const itemState of invalid) {
|
|
|
|
|
this.remove(itemState);
|
|
|
|
|
}
|
|
|
|
|
Popup.show('Invalid ItemStates removed:\n\n' + invalid.map(itemState => itemState.qty + 'x ' + itemState.itemId).join('\n'));
|
|
|
|
|
}
|
2021-06-14 22:03:55 -04:00
|
|
|
|
2021-06-22 19:25:41 -04:00
|
|
|
static serializationDependencies() {
|
|
|
|
|
return [ItemState];
|
|
|
|
|
}
|
2021-06-14 22:03:55 -04:00
|
|
|
|
2021-06-26 03:11:18 -04:00
|
|
|
remove(itemState: ItemState<any>) {
|
2021-06-22 19:25:41 -04:00
|
|
|
this.items = this.items.filter(test => test !== itemState);
|
|
|
|
|
}
|
|
|
|
|
|
2021-06-26 03:11:18 -04:00
|
|
|
add(itemState: ItemState<any>) {
|
2021-06-25 20:28:29 -04:00
|
|
|
this.items.push(itemState);
|
|
|
|
|
this.reduceInv();
|
2021-06-22 19:25:41 -04:00
|
|
|
}
|
|
|
|
|
|
2021-06-25 20:28:29 -04:00
|
|
|
private reduceInv() {
|
2021-07-02 23:01:45 -04:00
|
|
|
this.items = this.items.reduce((items, itemState) => {
|
|
|
|
|
|
|
|
|
|
// TODO at some point, be able to merge data items?
|
|
|
|
|
|
|
|
|
|
const existing = items.find(testItemState => {
|
|
|
|
|
return itemState.itemId === testItemState.itemId
|
|
|
|
|
&& itemState.data === testItemState.data;
|
|
|
|
|
});
|
2021-06-25 20:28:29 -04:00
|
|
|
|
2021-07-02 23:01:45 -04:00
|
|
|
if(existing) {
|
|
|
|
|
existing.qty += itemState.qty;
|
|
|
|
|
} else {
|
|
|
|
|
items.push(itemState);
|
|
|
|
|
}
|
|
|
|
|
return items
|
|
|
|
|
}, [] as ItemState<any>[])
|
|
|
|
|
}
|
2021-06-25 20:28:29 -04:00
|
|
|
|
2021-06-22 19:25:41 -04:00
|
|
|
render() {
|
|
|
|
|
return this.items.map(item => item.render()).join('\n');
|
|
|
|
|
}
|
2021-06-14 22:03:55 -04:00
|
|
|
}
|