2021-08-20 20:47:02 -05:00
|
|
|
/// <reference path="./resource/IResource.ts" />
|
2021-08-18 15:36:02 -05:00
|
|
|
|
|
|
|
class GameState {
|
2021-08-20 20:47:02 -05:00
|
|
|
private _resources: Record<string, IResource> = { };
|
|
|
|
private _resourceKeys: string[] = [];
|
|
|
|
|
2021-08-20 23:00:24 -05:00
|
|
|
public onResourceClick: (() => void)[] = [];
|
2021-08-18 15:36:02 -05:00
|
|
|
|
|
|
|
public addResource (key: string, resource: IResource): void {
|
2021-08-20 20:47:02 -05:00
|
|
|
this._resourceKeys.push(key);
|
2021-08-18 15:36:02 -05:00
|
|
|
this._resources[key] = resource;
|
|
|
|
}
|
|
|
|
|
|
|
|
public advance (time: number): void {
|
2021-08-20 20:47:02 -05:00
|
|
|
for (const rkey of this._resourceKeys) {
|
|
|
|
if (this._resources[rkey].advanceAction !== null) {
|
|
|
|
this._resources[rkey].advanceAction(time, this);
|
|
|
|
}
|
2021-08-20 23:30:32 -05:00
|
|
|
if (this._resources[rkey].inc > 0) {
|
|
|
|
this._resources[rkey].value += this._resources[rkey].inc * time / 1000;
|
|
|
|
}
|
2021-08-20 20:47:02 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public getResources (): string[] {
|
|
|
|
return this._resourceKeys;
|
|
|
|
}
|
|
|
|
|
|
|
|
public getResource (key: string): IResource {
|
|
|
|
return this._resources[key];
|
|
|
|
}
|
|
|
|
|
|
|
|
public performClick (resourceKey: string): void {
|
|
|
|
if (this._resources[resourceKey].clickAction !== null) {
|
|
|
|
this._resources[resourceKey].clickAction(this);
|
2021-08-20 23:00:24 -05:00
|
|
|
for (const callback of this.onResourceClick) {
|
|
|
|
callback();
|
2021-08-20 20:47:02 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public deductCost (cost: { [rkey: string]: number }): boolean {
|
2021-08-20 23:00:24 -05:00
|
|
|
if (cost === null || Object.keys(cost) === null) return true;
|
|
|
|
if (!this.isPurchasable(cost)) return false;
|
|
|
|
for (const rkey of Object.keys(cost)) {
|
|
|
|
this._resources[rkey].value -= cost[rkey];
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
public isPurchasable (cost: { [rkey: string]: number }): boolean {
|
2021-08-20 20:47:02 -05:00
|
|
|
if (cost === null || Object.keys(cost) === null) return true;
|
|
|
|
for (const rkey of Object.keys(cost)) {
|
|
|
|
if (this._resources[rkey].value < cost[rkey]) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true;
|
2021-08-18 15:36:02 -05:00
|
|
|
}
|
|
|
|
}
|