@shipload/sdk 0.7.1 → 2.0.0-rc1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/lib/shipload.d.ts +1651 -226
  2. package/lib/shipload.js +4958 -1971
  3. package/lib/shipload.js.map +1 -1
  4. package/lib/shipload.m.js +4787 -1940
  5. package/lib/shipload.m.js.map +1 -1
  6. package/package.json +5 -4
  7. package/src/contracts/server.ts +585 -203
  8. package/src/data/goods.json +23 -0
  9. package/src/data/syllables.json +1184 -0
  10. package/src/entities/cargo-utils.ts +47 -0
  11. package/src/entities/entity-inventory.ts +39 -0
  12. package/src/entities/gamestate.ts +152 -0
  13. package/src/entities/location.ts +241 -0
  14. package/src/entities/player.ts +287 -0
  15. package/src/entities/ship.ts +559 -0
  16. package/src/entities/warehouse.ts +205 -0
  17. package/src/errors.ts +46 -9
  18. package/src/index-module.ts +119 -7
  19. package/src/managers/actions.ts +168 -0
  20. package/src/managers/base.ts +25 -0
  21. package/src/managers/context.ts +104 -0
  22. package/src/managers/entities.ts +86 -0
  23. package/src/managers/epochs.ts +47 -0
  24. package/src/managers/index.ts +9 -0
  25. package/src/managers/locations.ts +103 -0
  26. package/src/managers/players.ts +13 -0
  27. package/src/managers/trades.ts +119 -0
  28. package/src/market/goods.ts +31 -0
  29. package/src/{market.ts → market/market.ts} +32 -37
  30. package/src/{rolls.ts → market/rolls.ts} +3 -3
  31. package/src/{epoch.ts → scheduling/epoch.ts} +1 -1
  32. package/src/scheduling/projection.ts +218 -0
  33. package/src/scheduling/schedule.ts +155 -0
  34. package/src/shipload.ts +39 -157
  35. package/src/trading/collect.ts +939 -0
  36. package/src/trading/deal.ts +208 -0
  37. package/src/trading/trade.ts +203 -0
  38. package/src/travel/travel.ts +425 -0
  39. package/src/types.ts +60 -25
  40. package/src/utils/system.ts +27 -0
  41. package/src/goods.ts +0 -124
  42. package/src/ship.ts +0 -36
  43. package/src/state.ts +0 -0
  44. package/src/syllables.ts +0 -1184
  45. package/src/system.ts +0 -37
  46. package/src/travel.ts +0 -259
  47. /package/src/{hash.ts → utils/hash.ts} +0 -0
@@ -0,0 +1,205 @@
1
+ import {Name, NameType, UInt32, UInt64, UInt64Type} from '@wharfkit/antelope'
2
+ import {ServerContract} from '../contracts'
3
+ import {Coordinates, CoordinatesType, TaskType} from '../types'
4
+ import {Location} from './location'
5
+ import {getGood} from '../market/goods'
6
+ import * as schedule from '../scheduling/schedule'
7
+ import {Scheduleable} from '../scheduling/schedule'
8
+ import {EntityInventory} from './entity-inventory'
9
+
10
+ export interface WarehouseStateInput {
11
+ id: UInt64Type
12
+ owner: NameType
13
+ name: string
14
+ location: CoordinatesType | {x: number; y: number; z?: number}
15
+ capacity: number
16
+ loaders: ServerContract.Types.loader_stats
17
+ schedule?: ServerContract.Types.schedule
18
+ cargo?: ServerContract.Types.cargo_item[]
19
+ }
20
+
21
+ export class Warehouse extends ServerContract.Types.entity_info implements Scheduleable {
22
+ static fromState(state: WarehouseStateInput): Warehouse {
23
+ const entityInfo = ServerContract.Types.entity_info.from({
24
+ type: Name.from('warehouse'),
25
+ id: UInt64.from(state.id),
26
+ owner: Name.from(state.owner),
27
+ entity_name: state.name,
28
+ location: ServerContract.Types.coordinates.from(state.location),
29
+ capacity: UInt32.from(state.capacity),
30
+ cargomass: UInt32.from(0),
31
+ cargo: state.cargo || [],
32
+ loaders: state.loaders,
33
+ is_idle: !state.schedule,
34
+ current_task_elapsed: UInt32.from(0),
35
+ current_task_remaining: UInt32.from(0),
36
+ pending_tasks: [],
37
+ schedule: state.schedule,
38
+ mass: UInt32.from(0),
39
+ energy: 0,
40
+ engines: ServerContract.Types.movement_stats.from({
41
+ thrust: 0,
42
+ drain: 0,
43
+ maxmass: 0,
44
+ }),
45
+ generator: ServerContract.Types.energy_stats.from({
46
+ capacity: 0,
47
+ recharge: 0,
48
+ }),
49
+ })
50
+ return new Warehouse(entityInfo)
51
+ }
52
+
53
+ private _location?: Location
54
+ private _inventory?: EntityInventory[]
55
+
56
+ get name(): string {
57
+ return this.entity_name
58
+ }
59
+
60
+ get inventory(): EntityInventory[] {
61
+ if (!this._inventory) {
62
+ this._inventory = this.cargo.map((item) => new EntityInventory(item))
63
+ }
64
+ return this._inventory
65
+ }
66
+
67
+ get hasSchedule(): boolean {
68
+ return schedule.hasSchedule(this)
69
+ }
70
+
71
+ get isIdle(): boolean {
72
+ return this.is_idle
73
+ }
74
+
75
+ get tasks(): ServerContract.Types.task[] {
76
+ return schedule.getTasks(this)
77
+ }
78
+
79
+ scheduleDuration(): number {
80
+ return schedule.scheduleDuration(this)
81
+ }
82
+
83
+ scheduleElapsed(now: Date): number {
84
+ return schedule.scheduleElapsed(this, now)
85
+ }
86
+
87
+ scheduleRemaining(now: Date): number {
88
+ return schedule.scheduleRemaining(this, now)
89
+ }
90
+
91
+ scheduleComplete(now: Date): boolean {
92
+ return schedule.scheduleComplete(this, now)
93
+ }
94
+
95
+ currentTaskIndex(now: Date): number {
96
+ return schedule.currentTaskIndex(this, now)
97
+ }
98
+
99
+ currentTask(now: Date): ServerContract.Types.task | undefined {
100
+ return schedule.currentTask(this, now)
101
+ }
102
+
103
+ currentTaskType(now: Date): TaskType | undefined {
104
+ return schedule.currentTaskType(this, now)
105
+ }
106
+
107
+ getTaskStartTime(index: number): number {
108
+ return schedule.getTaskStartTime(this, index)
109
+ }
110
+
111
+ getTaskElapsed(index: number, now: Date): number {
112
+ return schedule.getTaskElapsed(this, index, now)
113
+ }
114
+
115
+ getTaskRemaining(index: number, now: Date): number {
116
+ return schedule.getTaskRemaining(this, index, now)
117
+ }
118
+
119
+ isTaskComplete(index: number, now: Date): boolean {
120
+ return schedule.isTaskComplete(this, index, now)
121
+ }
122
+
123
+ isTaskInProgress(index: number, now: Date): boolean {
124
+ return schedule.isTaskInProgress(this, index, now)
125
+ }
126
+
127
+ currentTaskProgress(now: Date): number {
128
+ return schedule.currentTaskProgress(this, now)
129
+ }
130
+
131
+ scheduleProgress(now: Date): number {
132
+ return schedule.scheduleProgress(this, now)
133
+ }
134
+
135
+ isLoading(now: Date): boolean {
136
+ const taskType = this.currentTaskType(now)
137
+ return taskType === TaskType.LOAD
138
+ }
139
+
140
+ isUnloading(now: Date): boolean {
141
+ const taskType = this.currentTaskType(now)
142
+ return taskType === TaskType.UNLOAD
143
+ }
144
+
145
+ calcCargoMass(): UInt64 {
146
+ let mass = UInt64.from(0)
147
+ for (const item of this.cargo) {
148
+ const good = getGood(item.good_id)
149
+ mass = mass.adding(good.mass.multiplying(item.quantity))
150
+ }
151
+ return mass
152
+ }
153
+
154
+ get currentLocation(): Coordinates {
155
+ return this.location
156
+ }
157
+
158
+ get totalCargoMass(): UInt64 {
159
+ return this.inventory.reduce((sum, c) => sum.adding(c.totalMass), UInt64.from(0))
160
+ }
161
+
162
+ get cargoValue(): UInt64 {
163
+ return this.inventory.reduce((sum, c) => sum.adding(c.totalCost), UInt64.from(0))
164
+ }
165
+
166
+ get maxCapacity(): UInt64 {
167
+ return UInt64.from(this.capacity)
168
+ }
169
+
170
+ get availableCapacity(): UInt64 {
171
+ if (this.totalCargoMass.gte(this.maxCapacity)) {
172
+ return UInt64.from(0)
173
+ }
174
+ return this.maxCapacity.subtracting(this.totalCargoMass)
175
+ }
176
+
177
+ hasSpace(goodMass: UInt64, quantity: number): boolean {
178
+ const additionalMass = goodMass.multiplying(quantity)
179
+ const newTotal = this.totalCargoMass.adding(additionalMass)
180
+ return newTotal.lte(this.maxCapacity)
181
+ }
182
+
183
+ get isFull(): boolean {
184
+ return this.totalCargoMass.gte(this.maxCapacity)
185
+ }
186
+
187
+ get locationObject(): Location {
188
+ if (!this._location) {
189
+ this._location = Location.from(this.location)
190
+ }
191
+ return this._location
192
+ }
193
+
194
+ setLocation(location: Location): void {
195
+ this._location = location
196
+ }
197
+
198
+ getCargoForGood(goodId: UInt64Type): EntityInventory | undefined {
199
+ return this.inventory.find((c) => c.good_id.equals(goodId))
200
+ }
201
+
202
+ get orbitalAltitude(): number {
203
+ return this.location.z?.toNumber() || 0
204
+ }
205
+ }
package/src/errors.ts CHANGED
@@ -1,9 +1,46 @@
1
- export const ERROR_SYSTEM_NOT_INITIALIZED = 'System not initialized'
2
- export const GOOD_DOES_NOT_EXIST = 'Good does not exist'
3
- export const GOOD_NOT_AVAILABLE_AT_LOCATION = 'Good not available at location'
4
- export const PLAYER_NOT_FOUND = 'Player not found'
5
- export const SHIP_NOT_FOUND = 'Ship not found'
6
- export const SHIP_CANNOT_BUY_TRAVELING = 'Ship cannot buy while traveling'
7
- export const INSUFFICIENT_BALANCE = 'Insufficient balance'
8
- export const INSUFFICIENT_GOOD_QUANTITY = 'Insufficient good quantity'
9
- export const REQUIRES_MORE_THAN_ONE = 'Requires more than one'
1
+ export const COMPANY_NOT_FOUND = 'Cannot find company for given account.'
2
+ export const COMMIT_ALREADY_SET = 'Commit has already been set.'
3
+ export const COMMIT_CANNOT_MATCH = 'Next commit cannot match current commit.'
4
+ export const COMMIT_NOT_SET = 'Commit has not been set.'
5
+ export const EPOCH_NON_ZERO = 'Epoch must be greater than zero.'
6
+ export const EPOCH_NOT_READY = 'Current epoch is not ready to advance'
7
+ export const ERROR_SYSTEM_ALREADY_INITIALIZED = 'This game has already been initialized.'
8
+ export const ERROR_SYSTEM_DISABLED = 'This game is currently disabled.'
9
+ export const ERROR_SYSTEM_NOT_INITIALIZED = 'This game has not been initialized.'
10
+ export const GAME_NOT_FOUND = 'Cannot find game for given account name.'
11
+ export const GAME_SEED_NOT_SET = 'This game has not initialized an epoch seed value.'
12
+ export const GOOD_DOES_NOT_EXIST = 'Good does not exist.'
13
+ export const GOOD_NOT_AVAILABLE_AT_LOCATION = 'Good is not tradeable at ship location.'
14
+ export const INSUFFICIENT_BALANCE = 'Insufficient balance.'
15
+ export const INSUFFICIENT_GOOD_QUANTITY = 'Insufficient quantity in cargo.'
16
+ export const INSUFFICIENT_GOOD_SUPPLY = 'Insufficient supply of good at location.'
17
+ export const INVALID_AMOUNT = 'Invalid amount.'
18
+ export const REQUIRES_MORE_THAN_ONE = 'A value greater than one is required.'
19
+ export const REQUIRES_POSITIVE_VALUE = 'Value must be greater than zero.'
20
+ export const PLAYER_ALREADY_JOINED = 'Player has already joined the game.'
21
+ export const PLAYER_NOT_FOUND = 'Cannot find player for given account name.'
22
+ export const SHIP_ALREADY_THERE = 'Ship cannot travel to the location its already at.'
23
+ export const SHIP_ALREADY_TRAVELING = 'Ship is already traveling.'
24
+ export const SHIP_CANNOT_BUY_TRAVELING = 'Ship cannot buy goods while traveling.'
25
+ export const SHIP_CANNOT_UPDATE_TRAVELING = 'Ship cannot be updated while traveling.'
26
+ export const SHIP_INVALID_DESTINATION = 'Ship cannot travel, no system at specified destination.'
27
+ export const SHIP_INVALID_TRAVEL_DURATION =
28
+ 'This trip cannot be made as it would exceed the maximum travel duration.'
29
+ export const SHIP_NOT_ARRIVED = 'Ship has not yet arrived at its destination.'
30
+ export const SHIP_NOT_ENOUGH_ENERGY =
31
+ 'Ship does not have enough energy to travel to the destination.'
32
+ export const SHIP_NOT_ENOUGH_ENERGY_CAPACITY =
33
+ 'Ship does not have enough energy capacity to travel.'
34
+ export const SHIP_NOT_FOUND = 'Cannot find ship for given account.'
35
+ export const SHIP_NOT_OWNED = 'Ship is not owned by this account.'
36
+ export const NO_SCHEDULE = 'No scheduled tasks.'
37
+ export const SHIP_NOT_IDLE = 'Ship must be idle (no active schedule) for this action.'
38
+ export const SHIP_NO_COMPLETED_TASKS = 'No completed tasks to resolve.'
39
+ export const SHIP_CANNOT_CANCEL_TASK = 'Cannot cancel task that is immutable or in progress.'
40
+ export const SHIP_NO_TASKS_TO_CANCEL = 'No tasks to cancel.'
41
+ export const SHIP_INVALID_CARGO = 'Invalid cargo specified for load/unload.'
42
+ export const SHIP_CARGO_NOT_OWNED = 'Cannot load cargo that is not owned.'
43
+ export const SHIP_CARGO_NOT_LOADED = 'Cannot unload cargo that is not loaded.'
44
+ export const WAREHOUSE_NOT_FOUND = 'Cannot find warehouse for given id.'
45
+ export const WAREHOUSE_ALREADY_AT_LOCATION = 'Warehouse already exists at this location.'
46
+ export const WAREHOUSE_CAPACITY_EXCEEDED = 'Warehouse capacity would be exceeded.'
@@ -1,10 +1,122 @@
1
1
  export * from './contracts'
2
- export * from './epoch'
3
2
  export * from './errors'
4
- export * from './goods'
5
- export * from './hash'
6
- export * from './system'
7
- export * from './market'
8
- export * from './ship'
9
- export * from './travel'
10
3
  export * from './types'
4
+
5
+ import {ServerContract} from './contracts'
6
+
7
+ export {Shipload} from './shipload'
8
+ export {Ship} from './entities/ship'
9
+ export type {ShipStateInput} from './entities/ship'
10
+ export {Warehouse} from './entities/warehouse'
11
+
12
+ export type movement_stats = ServerContract.Types.movement_stats
13
+ export type energy_stats = ServerContract.Types.energy_stats
14
+ export type loader_stats = ServerContract.Types.loader_stats
15
+ export type schedule = ServerContract.Types.schedule
16
+ export type task = ServerContract.Types.task
17
+ export type cargo_item = ServerContract.Types.cargo_item
18
+ export type warehouse_row = ServerContract.Types.warehouse_row
19
+ export {Player} from './entities/player'
20
+ export type {PlayerStateInput} from './entities/player'
21
+ export {EntityInventory} from './entities/entity-inventory'
22
+ export {Location, toLocation} from './entities/location'
23
+ export {GameState} from './entities/gamestate'
24
+
25
+ export {
26
+ EntitiesManager,
27
+ PlayersManager,
28
+ LocationsManager,
29
+ TradesManager,
30
+ EpochsManager,
31
+ ActionsManager,
32
+ } from './managers'
33
+ export type {EntityType} from './managers'
34
+
35
+ export {getGood, getGoods, goodIds} from './market/goods'
36
+ export {getCurrentEpoch, getEpochInfo} from './scheduling/epoch'
37
+ export type {EpochInfo} from './scheduling/epoch'
38
+ export {marketPrice, marketPrices, getRarity, Rarities} from './market/market'
39
+ export type {Rarity} from './market/market'
40
+ export {getSystemName, hasSystem} from './utils/system'
41
+
42
+ export {hash, hash512} from './utils/hash'
43
+
44
+ export type {Deal, FindDealsOptions} from './trading/deal'
45
+ export {findDealsForShip, findBestDeal} from './trading/deal'
46
+
47
+ export type {
48
+ CollectActionType,
49
+ CollectOption,
50
+ CollectAnalysis,
51
+ CollectAnalysisOptions,
52
+ CollectAnalysisCallbacks,
53
+ BetterSaleLocation,
54
+ RepositionLocation,
55
+ DiscountedGoodInfo,
56
+ PotentialDeal,
57
+ CargoSaleItem,
58
+ } from './trading/collect'
59
+ export {
60
+ analyzeCollectOptions,
61
+ analyzeCargoSale,
62
+ createSellAndTradeOption,
63
+ createTravelToSellOption,
64
+ createSellAndRepositionOption,
65
+ createSellAndStayOption,
66
+ createExploreOption,
67
+ } from './trading/collect'
68
+
69
+ export {
70
+ distanceBetweenCoordinates,
71
+ distanceBetweenPoints,
72
+ findNearbyPlanets,
73
+ lerp,
74
+ rotation,
75
+ calc_ship_mass,
76
+ calc_acceleration,
77
+ calc_flighttime,
78
+ calc_ship_flighttime,
79
+ calc_ship_acceleration,
80
+ calc_rechargetime,
81
+ calc_ship_rechargetime,
82
+ calc_loader_flighttime,
83
+ calc_loader_acceleration,
84
+ calc_energyusage,
85
+ calc_orbital_altitude,
86
+ calc_transfer_duration,
87
+ calculateTransferTime,
88
+ calculateLoadTimeBreakdown,
89
+ calculateRefuelingTime,
90
+ calculateFlightTime,
91
+ estimateTravelTime,
92
+ estimateDealTravelTime,
93
+ hasEnergyForDistance,
94
+ } from './travel/travel'
95
+ export type {
96
+ LoadTimeBreakdown,
97
+ EstimatedTravelTime,
98
+ EstimateTravelTimeOptions,
99
+ TransferEntity,
100
+ } from './travel/travel'
101
+
102
+ export {
103
+ calculateUpdatedCargoCost,
104
+ calculateMaxTradeQuantity,
105
+ calculateTradeProfit,
106
+ calculateProfitPerMass,
107
+ calculateProfitPerSecond,
108
+ findBestGoodToTrade,
109
+ calculateBreakEvenPrice,
110
+ isProfitable,
111
+ calculateROI,
112
+ } from './trading/trade'
113
+ export type {TradeCalculation, TradeProfitResult} from './trading/trade'
114
+
115
+ export * as schedule from './scheduling/schedule'
116
+ export type {Scheduleable, ScheduleData} from './scheduling/schedule'
117
+
118
+ export * as cargoUtils from './entities/cargo-utils'
119
+ export type {CargoData} from './entities/cargo-utils'
120
+
121
+ export {projectEntity, projectEntityAt, createProjectedEntity} from './scheduling/projection'
122
+ export type {Projectable, ProjectedEntity} from './scheduling/projection'
@@ -0,0 +1,168 @@
1
+ import {Action, Int64, Name, NameType, UInt16, UInt32, UInt64, UInt64Type} from '@wharfkit/antelope'
2
+ import {BaseManager} from './base'
3
+ import {Ship} from '../entities/ship'
4
+ import {CoordinatesType, EntityType, EntityTypeName} from '../types'
5
+ import {ServerContract} from '../contracts'
6
+
7
+ interface SellableCargo {
8
+ good_id: {toNumber(): number} | number
9
+ quantity: {toNumber(): number} | number
10
+ hasCargo: boolean
11
+ }
12
+
13
+ export type CargoItemInput = {
14
+ goodId: UInt64Type
15
+ quantity: UInt64Type
16
+ unitCost?: UInt64Type
17
+ }
18
+
19
+ export class ActionsManager extends BaseManager {
20
+ travel(shipId: UInt64Type, destination: CoordinatesType, recharge = true): Action {
21
+ const x = Int64.from(destination.x)
22
+ const y = Int64.from(destination.y)
23
+
24
+ return this.server.action('travel', {
25
+ entity_type: EntityType.SHIP,
26
+ id: UInt64.from(shipId),
27
+ x,
28
+ y,
29
+ recharge,
30
+ })
31
+ }
32
+
33
+ resolve(entityId: UInt64Type, entityType: EntityTypeName = EntityType.SHIP): Action {
34
+ return this.server.action('resolve', {
35
+ entity_type: entityType,
36
+ id: UInt64.from(entityId),
37
+ })
38
+ }
39
+
40
+ cancel(
41
+ entityId: UInt64Type,
42
+ count: UInt64Type,
43
+ entityType: EntityTypeName = EntityType.SHIP
44
+ ): Action {
45
+ return this.server.action('cancel', {
46
+ entity_type: entityType,
47
+ id: UInt64.from(entityId),
48
+ count: UInt64.from(count),
49
+ })
50
+ }
51
+
52
+ recharge(shipId: UInt64Type): Action {
53
+ return this.server.action('recharge', {
54
+ entity_type: EntityType.SHIP,
55
+ id: UInt64.from(shipId),
56
+ })
57
+ }
58
+
59
+ transfer(
60
+ sourceType: EntityTypeName,
61
+ sourceId: UInt64Type,
62
+ destType: EntityTypeName,
63
+ destId: UInt64Type,
64
+ cargo: CargoItemInput[]
65
+ ): Action {
66
+ const cargoItems = cargo.map((c) =>
67
+ ServerContract.Types.cargo_item.from({
68
+ good_id: UInt16.from(c.goodId),
69
+ quantity: UInt32.from(c.quantity),
70
+ unit_cost: UInt64.from(c.unitCost || 0),
71
+ })
72
+ )
73
+ return this.server.action('transfer', {
74
+ source_type: sourceType,
75
+ source_id: UInt64.from(sourceId),
76
+ dest_type: destType,
77
+ dest_id: UInt64.from(destId),
78
+ cargo: cargoItems,
79
+ })
80
+ }
81
+
82
+ buyGoods(shipId: UInt64Type, goodId: UInt64Type, quantity: UInt64Type): Action {
83
+ return this.server.action('buygoods', {
84
+ ship_id: UInt64.from(shipId),
85
+ good_id: UInt64.from(goodId),
86
+ quantity: UInt64.from(quantity),
87
+ })
88
+ }
89
+
90
+ sellGoods(shipId: UInt64Type, goodId: UInt64Type, quantity: UInt64Type): Action {
91
+ return this.server.action('sellgoods', {
92
+ ship_id: UInt64.from(shipId),
93
+ good_id: UInt64.from(goodId),
94
+ quantity: UInt64.from(quantity),
95
+ })
96
+ }
97
+
98
+ buyShip(account: NameType, name: string): Action {
99
+ return this.server.action('buyship', {
100
+ account: Name.from(account),
101
+ name,
102
+ })
103
+ }
104
+
105
+ buyWarehouse(account: NameType, shipId: UInt64Type, name: string): Action {
106
+ return this.server.action('buywarehouse', {
107
+ account: Name.from(account),
108
+ ship_id: UInt64.from(shipId),
109
+ name,
110
+ })
111
+ }
112
+
113
+ takeLoan(account: NameType, amount: UInt64Type): Action {
114
+ return this.server.action('takeloan', {
115
+ account: Name.from(account),
116
+ amount: UInt64.from(amount),
117
+ })
118
+ }
119
+
120
+ payLoan(account: NameType, amount: UInt64Type): Action {
121
+ return this.server.action('payloan', {
122
+ account: Name.from(account),
123
+ amount: UInt64.from(amount),
124
+ })
125
+ }
126
+
127
+ foundCompany(account: NameType, name: string): Action {
128
+ return this.platform.action('foundcompany', {
129
+ account: Name.from(account),
130
+ name,
131
+ })
132
+ }
133
+
134
+ join(account: NameType): Action {
135
+ return this.server.action('join', {
136
+ account: Name.from(account),
137
+ })
138
+ }
139
+
140
+ joinGame(account: NameType, companyName: string): Action[] {
141
+ return [this.foundCompany(account, companyName), this.join(account)]
142
+ }
143
+
144
+ sellAllCargo(ship: Ship | UInt64Type, cargo?: SellableCargo[]): Action[] {
145
+ let shipCargo: SellableCargo[]
146
+
147
+ if (ship instanceof Ship) {
148
+ shipCargo = cargo || ship.inventory
149
+ } else {
150
+ if (!cargo) {
151
+ throw new Error('cargo parameter required when ship is a UInt64Type')
152
+ }
153
+ shipCargo = cargo
154
+ }
155
+
156
+ const shipId = ship instanceof Ship ? ship.id : UInt64.from(ship)
157
+
158
+ return shipCargo
159
+ .filter((c) => c.hasCargo)
160
+ .map((c) =>
161
+ this.server.action('sellgoods', {
162
+ ship_id: shipId,
163
+ good_id: c.good_id,
164
+ quantity: c.quantity,
165
+ })
166
+ )
167
+ }
168
+ }
@@ -0,0 +1,25 @@
1
+ import {GameContext} from './context'
2
+
3
+ export abstract class BaseManager {
4
+ constructor(protected readonly context: GameContext) {}
5
+
6
+ protected get client() {
7
+ return this.context.client
8
+ }
9
+
10
+ protected get server() {
11
+ return this.context.server
12
+ }
13
+
14
+ protected get platform() {
15
+ return this.context.platform
16
+ }
17
+
18
+ protected async getGame() {
19
+ return this.context.getGame()
20
+ }
21
+
22
+ protected async getState() {
23
+ return this.context.getState()
24
+ }
25
+ }
@@ -0,0 +1,104 @@
1
+ import {APIClient} from '@wharfkit/antelope'
2
+ import {Contract} from '@wharfkit/contract'
3
+ import {PlatformContract} from '../contracts'
4
+ import {GameState} from '../entities/gamestate'
5
+
6
+ import {EntitiesManager} from './entities'
7
+ import {PlayersManager} from './players'
8
+ import {LocationsManager} from './locations'
9
+ import {TradesManager} from './trades'
10
+ import {EpochsManager} from './epochs'
11
+ import {ActionsManager} from './actions'
12
+
13
+ export class GameContext {
14
+ private _entities?: EntitiesManager
15
+ private _players?: PlayersManager
16
+ private _locations?: LocationsManager
17
+ private _trades?: TradesManager
18
+ private _epochs?: EpochsManager
19
+ private _actions?: ActionsManager
20
+
21
+ private _gameCache?: PlatformContract.Types.game_row
22
+ private _stateCache?: GameState
23
+
24
+ constructor(
25
+ public readonly client: APIClient,
26
+ public readonly server: Contract,
27
+ public readonly platform: Contract
28
+ ) {}
29
+
30
+ get entities(): EntitiesManager {
31
+ if (!this._entities) {
32
+ this._entities = new EntitiesManager(this)
33
+ }
34
+ return this._entities
35
+ }
36
+
37
+ get players(): PlayersManager {
38
+ if (!this._players) {
39
+ this._players = new PlayersManager(this)
40
+ }
41
+ return this._players
42
+ }
43
+
44
+ get locations(): LocationsManager {
45
+ if (!this._locations) {
46
+ this._locations = new LocationsManager(this)
47
+ }
48
+ return this._locations
49
+ }
50
+
51
+ get trades(): TradesManager {
52
+ if (!this._trades) {
53
+ this._trades = new TradesManager(this)
54
+ }
55
+ return this._trades
56
+ }
57
+
58
+ get epochs(): EpochsManager {
59
+ if (!this._epochs) {
60
+ this._epochs = new EpochsManager(this)
61
+ }
62
+ return this._epochs
63
+ }
64
+
65
+ get actions(): ActionsManager {
66
+ if (!this._actions) {
67
+ this._actions = new ActionsManager(this)
68
+ }
69
+ return this._actions
70
+ }
71
+
72
+ async getGame(reload = false): Promise<PlatformContract.Types.game_row> {
73
+ if (!reload && this._gameCache) {
74
+ return this._gameCache
75
+ }
76
+ const game = await this.platform.table('games').get()
77
+ if (!game) {
78
+ throw new Error('Game not initialized')
79
+ }
80
+ this._gameCache = game
81
+ return game
82
+ }
83
+
84
+ async getState(reload = false): Promise<GameState> {
85
+ if (!reload && this._stateCache) {
86
+ return this._stateCache
87
+ }
88
+ const state = await this.server.table('state').get()
89
+ if (!state) {
90
+ throw new Error('Game state not initialized')
91
+ }
92
+ const game = this._gameCache
93
+ this._stateCache = GameState.from(state, game)
94
+ return this._stateCache
95
+ }
96
+
97
+ get cachedGame(): PlatformContract.Types.game_row | undefined {
98
+ return this._gameCache
99
+ }
100
+
101
+ get cachedState(): GameState | undefined {
102
+ return this._stateCache
103
+ }
104
+ }