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() {
|
|
|
|
|
// TODO deduplicate itemstates...
|
|
|
|
|
// use a reduce to reconstruct the array.
|
|
|
|
|
// REMEMBER TO MAINTAIN THE OBJECTs!
|
|
|
|
|
// dont do immutability to it, as the objects
|
|
|
|
|
// may have crossreferences! (maybe)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// add(item: Item, qty: number = 1) {
|
|
|
|
|
// const id = item.id;
|
|
|
|
|
// 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-22 19:25:41 -04:00
|
|
|
render() {
|
|
|
|
|
return this.items.map(item => item.render()).join('\n');
|
|
|
|
|
}
|
2021-06-14 22:03:55 -04:00
|
|
|
}
|