hadean-old/src/registries/Items.ts

97 lines
2.2 KiB
TypeScript
Raw Normal View History

2021-06-22 19:25:41 -04:00
import { Serializable } from 'frigid';
2021-06-26 03:11:18 -04:00
import { getTheme } from '@themes';
2021-07-20 16:37:38 -04:00
import { Renderable } from '@ui';
import { osrsNumber } from '../Util.js';
2021-06-22 19:25:41 -04:00
export type ItemID = string;
2021-06-26 03:11:18 -04:00
const items = new Map<ItemID, Item<any>>();
2021-06-22 19:25:41 -04:00
// ITEMS SHALL BE SINGULAR
2021-07-20 16:37:38 -04:00
export class Item<Data = any> {
2021-06-22 19:25:41 -04:00
2021-07-19 01:53:30 -04:00
name = {
singular: '',
plural: ''
}
2021-06-22 19:25:41 -04:00
id: ItemID = '';
2021-07-02 23:01:45 -04:00
props: Map<string, any> = new Map();
2021-06-22 19:25:41 -04:00
2021-06-26 13:07:11 -04:00
setName(name: string) {
2021-07-19 01:53:30 -04:00
this.name.singular = name;
this.name.plural = name;
2021-06-22 19:25:41 -04:00
this.register(false);
return this;
}
2021-07-19 01:53:30 -04:00
plural(name: string) {
this.name.plural = name;
return this;
}
2021-06-22 19:25:41 -04:00
setId(id: ItemID) {
this.id = id;
this.register(false);
return this;
}
register(force = true) {
if((!this.id || !this.name) && !force) return;
2021-07-19 01:53:30 -04:00
console.log('Added item', (this.name.singular ?? "[No Name]").padStart(20, ' '), `| (${this.id})`)
2021-06-22 19:25:41 -04:00
items.set(this.id, this);
return this;
}
2021-06-24 17:34:05 -04:00
setProperty(prop: ItemProperty, value: any) {
2021-06-26 13:07:11 -04:00
this.props.set(prop.name, value);
return this;
2021-06-24 17:34:05 -04:00
}
getProperty(prop: ItemProperty) {
if(this.props.has(prop.name)) return this.props.get(prop.name);
else return null;
2021-06-24 17:34:05 -04:00
}
2021-06-22 19:25:41 -04:00
}
2021-06-26 03:11:18 -04:00
export class ItemState<Data> extends Serializable implements Renderable {
2021-06-22 19:25:41 -04:00
qty: number;
itemId: ItemID;
2021-06-26 03:11:18 -04:00
data: Data;
2021-06-22 19:25:41 -04:00
2021-07-02 23:01:45 -04:00
take(qty: number) {
if(this.qty < qty) throw new Error('cant split more than stack from stack...');
this.qty -= qty;
return new ItemState<Data>(this.item, qty, this.data);
}
2021-06-22 19:25:41 -04:00
get item() {
if(!items.has(this.itemId))
throw new Error('unknown item: ' + this.itemId);
return items.get(this.itemId);
}
2021-07-16 20:49:29 -04:00
constructor(item: Item<Data>, amount: number, data: Data = null) {
2021-06-22 19:25:41 -04:00
super();
this.qty = amount;
this.itemId = item.id;
this.data = data;
}
render() {
2021-07-20 16:37:38 -04:00
return getTheme().normal(` ${osrsNumber(this.qty)} ${(() => {
if(this.qty === 1) return this.item.name.singular;
else return this.item.name.plural;
})()} `);
2021-06-22 19:25:41 -04:00
}
}
2021-06-24 17:34:05 -04:00
export class ItemProperty {
name: string;
constructor(name: string) {
this.name = name;
}
}
2021-06-26 03:11:18 -04:00
export type ItemFilter = (itemState: ItemState<any>) => boolean;