@supalosa/chronodivide-bot 0.5.3 → 0.6.4

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 (134) hide show
  1. package/.env.template +4 -4
  2. package/.github/workflows/npm-publish.yml +24 -0
  3. package/README.md +108 -97
  4. package/dist/bot/bot.js +105 -105
  5. package/dist/bot/bot.js.map +1 -1
  6. package/dist/bot/logic/awareness.js +136 -136
  7. package/dist/bot/logic/building/antiAirStaticDefence.js +42 -42
  8. package/dist/bot/logic/building/antiGroundStaticDefence.js +34 -30
  9. package/dist/bot/logic/building/antiGroundStaticDefence.js.map +1 -1
  10. package/dist/bot/logic/building/{ArtilleryUnit.js → artilleryUnit.js} +18 -18
  11. package/dist/bot/logic/building/basicAirUnit.js +19 -19
  12. package/dist/bot/logic/building/basicBuilding.js +26 -26
  13. package/dist/bot/logic/building/basicGroundUnit.js +19 -19
  14. package/dist/bot/logic/building/buildingRules.js +175 -174
  15. package/dist/bot/logic/building/buildingRules.js.map +1 -1
  16. package/dist/bot/logic/building/common.js +19 -18
  17. package/dist/bot/logic/building/common.js.map +1 -1
  18. package/dist/bot/logic/building/harvester.js +16 -16
  19. package/dist/bot/logic/building/powerPlant.js +20 -20
  20. package/dist/bot/logic/building/queueController.js +183 -183
  21. package/dist/bot/logic/building/resourceCollectionBuilding.js +36 -36
  22. package/dist/bot/logic/common/scout.js +126 -126
  23. package/dist/bot/logic/common/utils.js +95 -85
  24. package/dist/bot/logic/common/utils.js.map +1 -1
  25. package/dist/bot/logic/composition/alliedCompositions.js +12 -12
  26. package/dist/bot/logic/composition/common.js +1 -1
  27. package/dist/bot/logic/composition/sovietCompositions.js +12 -12
  28. package/dist/bot/logic/map/map.js +44 -44
  29. package/dist/bot/logic/map/sector.js +137 -137
  30. package/dist/bot/logic/mission/actionBatcher.js +91 -91
  31. package/dist/bot/logic/mission/mission.js +122 -122
  32. package/dist/bot/logic/mission/missionController.js +321 -321
  33. package/dist/bot/logic/mission/missionFactories.js +12 -12
  34. package/dist/bot/logic/mission/missions/attackMission.js +214 -214
  35. package/dist/bot/logic/mission/missions/defenceMission.js +82 -82
  36. package/dist/bot/logic/mission/missions/engineerMission.js +63 -63
  37. package/dist/bot/logic/mission/missions/expansionMission.js +60 -60
  38. package/dist/bot/logic/mission/missions/retreatMission.js +33 -33
  39. package/dist/bot/logic/mission/missions/scoutingMission.js +133 -133
  40. package/dist/bot/logic/mission/missions/squads/combatSquad.js +115 -115
  41. package/dist/bot/logic/mission/missions/squads/common.js +57 -57
  42. package/dist/bot/logic/mission/missions/squads/squad.js +1 -1
  43. package/dist/bot/logic/threat/threat.js +22 -22
  44. package/dist/bot/logic/threat/threatCalculator.js +73 -73
  45. package/dist/exampleBot.js +100 -112
  46. package/dist/exampleBot.js.map +1 -1
  47. package/package.json +32 -29
  48. package/src/bot/bot.ts +161 -161
  49. package/src/bot/logic/awareness.ts +245 -245
  50. package/src/bot/logic/building/antiAirStaticDefence.ts +64 -64
  51. package/src/bot/logic/building/antiGroundStaticDefence.ts +55 -51
  52. package/src/bot/logic/building/artilleryUnit.ts +39 -39
  53. package/src/bot/logic/building/basicAirUnit.ts +39 -39
  54. package/src/bot/logic/building/basicBuilding.ts +49 -49
  55. package/src/bot/logic/building/basicGroundUnit.ts +39 -39
  56. package/src/bot/logic/building/buildingRules.ts +250 -247
  57. package/src/bot/logic/building/common.ts +21 -23
  58. package/src/bot/logic/building/harvester.ts +31 -31
  59. package/src/bot/logic/building/powerPlant.ts +32 -32
  60. package/src/bot/logic/building/queueController.ts +297 -297
  61. package/src/bot/logic/building/resourceCollectionBuilding.ts +52 -52
  62. package/src/bot/logic/common/scout.ts +183 -183
  63. package/src/bot/logic/common/utils.ts +120 -112
  64. package/src/bot/logic/composition/alliedCompositions.ts +22 -22
  65. package/src/bot/logic/composition/common.ts +3 -3
  66. package/src/bot/logic/composition/sovietCompositions.ts +21 -21
  67. package/src/bot/logic/map/map.ts +66 -66
  68. package/src/bot/logic/map/sector.ts +174 -174
  69. package/src/bot/logic/mission/actionBatcher.ts +124 -124
  70. package/src/bot/logic/mission/mission.ts +232 -232
  71. package/src/bot/logic/mission/missionController.ts +413 -413
  72. package/src/bot/logic/mission/missionFactories.ts +51 -51
  73. package/src/bot/logic/mission/missions/attackMission.ts +336 -336
  74. package/src/bot/logic/mission/missions/defenceMission.ts +151 -151
  75. package/src/bot/logic/mission/missions/engineerMission.ts +113 -113
  76. package/src/bot/logic/mission/missions/expansionMission.ts +104 -104
  77. package/src/bot/logic/mission/missions/retreatMission.ts +54 -54
  78. package/src/bot/logic/mission/missions/scoutingMission.ts +186 -186
  79. package/src/bot/logic/mission/missions/squads/combatSquad.ts +160 -160
  80. package/src/bot/logic/mission/missions/squads/common.ts +63 -63
  81. package/src/bot/logic/mission/missions/squads/squad.ts +19 -19
  82. package/src/bot/logic/threat/threatCalculator.ts +100 -100
  83. package/src/exampleBot.ts +111 -124
  84. package/tsconfig.json +73 -73
  85. package/dist/bot/logic/building/building.js +0 -82
  86. package/dist/bot/logic/building/massedAntiGroundUnit.js +0 -20
  87. package/dist/bot/logic/building/queues.js +0 -19
  88. package/dist/bot/logic/knowledge.js +0 -1
  89. package/dist/bot/logic/mission/basicMission.js +0 -26
  90. package/dist/bot/logic/mission/behaviours/combatSquad.js +0 -124
  91. package/dist/bot/logic/mission/behaviours/combatSquad.js.map +0 -1
  92. package/dist/bot/logic/mission/behaviours/common.js +0 -56
  93. package/dist/bot/logic/mission/behaviours/common.js.map +0 -1
  94. package/dist/bot/logic/mission/behaviours/engineerSquad.js +0 -39
  95. package/dist/bot/logic/mission/behaviours/engineerSquad.js.map +0 -1
  96. package/dist/bot/logic/mission/behaviours/expansionSquad.js +0 -46
  97. package/dist/bot/logic/mission/behaviours/expansionSquad.js.map +0 -1
  98. package/dist/bot/logic/mission/behaviours/retreatSquad.js +0 -31
  99. package/dist/bot/logic/mission/behaviours/retreatSquad.js.map +0 -1
  100. package/dist/bot/logic/mission/behaviours/scoutingSquad.js +0 -94
  101. package/dist/bot/logic/mission/behaviours/scoutingSquad.js.map +0 -1
  102. package/dist/bot/logic/mission/expansionMission.js +0 -32
  103. package/dist/bot/logic/mission/missions/basicMission.js +0 -13
  104. package/dist/bot/logic/mission/missions/basicMission.js.map +0 -1
  105. package/dist/bot/logic/mission/missions/missionBehaviour.js +0 -2
  106. package/dist/bot/logic/mission/missions/missionBehaviour.js.map +0 -1
  107. package/dist/bot/logic/mission/missions/oneTimeMission.js +0 -27
  108. package/dist/bot/logic/mission/missions/oneTimeMission.js.map +0 -1
  109. package/dist/bot/logic/squad/behaviours/actionBatcher.js +0 -36
  110. package/dist/bot/logic/squad/behaviours/actionBatcher.js.map +0 -1
  111. package/dist/bot/logic/squad/behaviours/attackSquad.js +0 -82
  112. package/dist/bot/logic/squad/behaviours/combatSquad.js +0 -106
  113. package/dist/bot/logic/squad/behaviours/combatSquad.js.map +0 -1
  114. package/dist/bot/logic/squad/behaviours/common.js +0 -55
  115. package/dist/bot/logic/squad/behaviours/common.js.map +0 -1
  116. package/dist/bot/logic/squad/behaviours/defenceSquad.js +0 -48
  117. package/dist/bot/logic/squad/behaviours/engineerSquad.js +0 -38
  118. package/dist/bot/logic/squad/behaviours/engineerSquad.js.map +0 -1
  119. package/dist/bot/logic/squad/behaviours/expansionSquad.js +0 -45
  120. package/dist/bot/logic/squad/behaviours/expansionSquad.js.map +0 -1
  121. package/dist/bot/logic/squad/behaviours/retreatSquad.js +0 -31
  122. package/dist/bot/logic/squad/behaviours/retreatSquad.js.map +0 -1
  123. package/dist/bot/logic/squad/behaviours/scoutingSquad.js +0 -93
  124. package/dist/bot/logic/squad/behaviours/scoutingSquad.js.map +0 -1
  125. package/dist/bot/logic/squad/behaviours/squadExpansion.js +0 -31
  126. package/dist/bot/logic/squad/behaviours/squadScouters.js +0 -8
  127. package/dist/bot/logic/squad/squad.js +0 -126
  128. package/dist/bot/logic/squad/squad.js.map +0 -1
  129. package/dist/bot/logic/squad/squadBehaviour.js +0 -6
  130. package/dist/bot/logic/squad/squadBehaviour.js.map +0 -1
  131. package/dist/bot/logic/squad/squadBehaviours.js +0 -7
  132. package/dist/bot/logic/squad/squadBehaviours.js.map +0 -1
  133. package/dist/bot/logic/squad/squadController.js +0 -215
  134. package/dist/bot/logic/squad/squadController.js.map +0 -1
@@ -1,32 +1,32 @@
1
- import { GameApi, PlayerData, TechnoRules } from "@chronodivide/game-api";
2
- import { AiBuildingRules, getDefaultPlacementLocation } from "./buildingRules.js";
3
- import { GlobalThreat } from "../threat/threat.js";
4
-
5
- export class PowerPlant implements AiBuildingRules {
6
- getPlacementLocation(
7
- game: GameApi,
8
- playerData: PlayerData,
9
- technoRules: TechnoRules
10
- ): { rx: number; ry: number } | undefined {
11
- return getDefaultPlacementLocation(game, playerData, playerData.startLocation, technoRules);
12
- }
13
-
14
- getPriority(game: GameApi, playerData: PlayerData, technoRules: TechnoRules): number {
15
- if (playerData.power.total < playerData.power.drain) {
16
- return 100;
17
- } else if (playerData.power.total < playerData.power.drain + technoRules.power / 2) {
18
- return 20;
19
- } else {
20
- return 0;
21
- }
22
- }
23
-
24
- getMaxCount(
25
- game: GameApi,
26
- playerData: PlayerData,
27
- technoRules: TechnoRules,
28
- threatCache: GlobalThreat | null
29
- ): number | null {
30
- return null;
31
- }
32
- }
1
+ import { GameApi, PlayerData, TechnoRules } from "@chronodivide/game-api";
2
+ import { AiBuildingRules, getDefaultPlacementLocation } from "./buildingRules.js";
3
+ import { GlobalThreat } from "../threat/threat.js";
4
+
5
+ export class PowerPlant implements AiBuildingRules {
6
+ getPlacementLocation(
7
+ game: GameApi,
8
+ playerData: PlayerData,
9
+ technoRules: TechnoRules
10
+ ): { rx: number; ry: number } | undefined {
11
+ return getDefaultPlacementLocation(game, playerData, playerData.startLocation, technoRules);
12
+ }
13
+
14
+ getPriority(game: GameApi, playerData: PlayerData, technoRules: TechnoRules): number {
15
+ if (playerData.power.total < playerData.power.drain) {
16
+ return 100;
17
+ } else if (playerData.power.total < playerData.power.drain + technoRules.power / 2) {
18
+ return 20;
19
+ } else {
20
+ return 0;
21
+ }
22
+ }
23
+
24
+ getMaxCount(
25
+ game: GameApi,
26
+ playerData: PlayerData,
27
+ technoRules: TechnoRules,
28
+ threatCache: GlobalThreat | null
29
+ ): number | null {
30
+ return null;
31
+ }
32
+ }
@@ -1,297 +1,297 @@
1
- import {
2
- ActionsApi,
3
- GameApi,
4
- PlayerData,
5
- ProductionApi,
6
- QueueStatus,
7
- QueueType,
8
- TechnoRules,
9
- } from "@chronodivide/game-api";
10
- import { GlobalThreat } from "../threat/threat";
11
- import {
12
- TechnoRulesWithPriority,
13
- BUILDING_NAME_TO_RULES,
14
- DEFAULT_BUILDING_PRIORITY,
15
- getDefaultPlacementLocation,
16
- } from "./buildingRules.js";
17
- import { DebugLogger } from "../common/utils";
18
-
19
- export const QUEUES = [
20
- QueueType.Structures,
21
- QueueType.Armory,
22
- QueueType.Infantry,
23
- QueueType.Vehicles,
24
- QueueType.Aircrafts,
25
- QueueType.Ships,
26
- ];
27
-
28
- export const queueTypeToName = (queue: QueueType) => {
29
- switch (queue) {
30
- case QueueType.Structures:
31
- return "Structures";
32
- case QueueType.Armory:
33
- return "Armory";
34
- case QueueType.Infantry:
35
- return "Infantry";
36
- case QueueType.Vehicles:
37
- return "Vehicles";
38
- case QueueType.Aircrafts:
39
- return "Aircrafts";
40
- case QueueType.Ships:
41
- return "Ships";
42
- default:
43
- return "Unknown";
44
- }
45
- };
46
-
47
- type QueueState = {
48
- queue: QueueType;
49
- /** sorted in ascending order (last item is the topItem) */
50
- items: TechnoRulesWithPriority[];
51
- topItem: TechnoRulesWithPriority | undefined;
52
- };
53
-
54
- export class QueueController {
55
- private queueStates: QueueState[] = [];
56
-
57
- constructor() {}
58
-
59
- public onAiUpdate(
60
- game: GameApi,
61
- productionApi: ProductionApi,
62
- actionsApi: ActionsApi,
63
- playerData: PlayerData,
64
- threatCache: GlobalThreat | null,
65
- unitTypeRequests: Map<string, number>,
66
- logger: (message: string) => void,
67
- ) {
68
- this.queueStates = QUEUES.map((queueType) => {
69
- const options = productionApi.getAvailableObjects(queueType);
70
- const items = this.getPrioritiesForBuildingOptions(
71
- game,
72
- options,
73
- threatCache,
74
- playerData,
75
- unitTypeRequests,
76
- logger,
77
- );
78
- const topItem = items.length > 0 ? items[items.length - 1] : undefined;
79
- return {
80
- queue: queueType,
81
- items,
82
- // only if the top item has a priority above zero
83
- topItem: topItem && topItem.priority > 0 ? topItem : undefined,
84
- };
85
- });
86
- const totalWeightAcrossQueues = this.queueStates
87
- .map((decision) => decision.topItem?.priority!)
88
- .reduce((pV, cV) => pV + cV, 0);
89
- const totalCostAcrossQueues = this.queueStates
90
- .map((decision) => decision.topItem?.unit.cost!)
91
- .reduce((pV, cV) => pV + cV, 0);
92
-
93
- this.queueStates.forEach((decision) => {
94
- this.updateBuildQueue(
95
- game,
96
- productionApi,
97
- actionsApi,
98
- playerData,
99
- threatCache,
100
- decision.queue,
101
- decision.topItem,
102
- totalWeightAcrossQueues,
103
- totalCostAcrossQueues,
104
- logger,
105
- );
106
- });
107
-
108
- // Repair is simple - just repair everything that's damaged.
109
- if (playerData.credits > 0) {
110
- game.getVisibleUnits(playerData.name, "self", (r) => r.repairable).forEach((unitId) => {
111
- const unit = game.getUnitData(unitId);
112
- if (!unit || !unit.hitPoints || !unit.maxHitPoints || unit.hasWrenchRepair) {
113
- return;
114
- }
115
- if (unit.hitPoints < unit.maxHitPoints) {
116
- actionsApi.toggleRepairWrench(unitId);
117
- }
118
- });
119
- }
120
- }
121
-
122
- private updateBuildQueue(
123
- game: GameApi,
124
- productionApi: ProductionApi,
125
- actionsApi: ActionsApi,
126
- playerData: PlayerData,
127
- threatCache: GlobalThreat | null,
128
- queueType: QueueType,
129
- decision: TechnoRulesWithPriority | undefined,
130
- totalWeightAcrossQueues: number,
131
- totalCostAcrossQueues: number,
132
- logger: (message: string) => void,
133
- ): void {
134
- const myCredits = playerData.credits;
135
-
136
- const queueData = productionApi.getQueueData(queueType);
137
- if (queueData.status == QueueStatus.Idle) {
138
- // Start building the decided item.
139
- if (decision !== undefined) {
140
- logger(`Decision (${queueTypeToName(queueType)}): ${decision.unit.name}`);
141
- actionsApi.queueForProduction(queueType, decision.unit.name, decision.unit.type, 1);
142
- }
143
- } else if (queueData.status == QueueStatus.Ready && queueData.items.length > 0) {
144
- // Consider placing it.
145
- const objectReady: TechnoRules = queueData.items[0].rules;
146
- if (queueType == QueueType.Structures || queueType == QueueType.Armory) {
147
- let location: { rx: number; ry: number } | undefined = this.getBestLocationForStructure(
148
- game,
149
- playerData,
150
- objectReady,
151
- );
152
- if (location !== undefined) {
153
- logger(
154
- `Completed: ${queueTypeToName(queueType)}: ${objectReady.name}, placing at ${location.rx},${
155
- location.ry
156
- }`,
157
- );
158
- actionsApi.placeBuilding(objectReady.name, location.rx, location.ry);
159
- } else {
160
- logger(`Completed: ${queueTypeToName(queueType)}: ${objectReady.name} but nowhere to place it`);
161
- }
162
- }
163
- } else if (queueData.status == QueueStatus.Active && queueData.items.length > 0 && decision != null) {
164
- // Consider cancelling if something else is significantly higher priority than what is currently being produced.
165
- const currentProduction = queueData.items[0].rules;
166
- if (decision.unit != currentProduction) {
167
- // Changing our mind.
168
- let currentItemPriority = this.getPriorityForBuildingOption(
169
- currentProduction,
170
- game,
171
- playerData,
172
- threatCache,
173
- );
174
- let newItemPriority = decision.priority;
175
- if (newItemPriority > currentItemPriority * 2) {
176
- logger(
177
- `Dequeueing queue ${queueTypeToName(queueData.type)} unit ${currentProduction.name} because ${
178
- decision.unit.name
179
- } has 2x higher priority.`,
180
- );
181
- actionsApi.unqueueFromProduction(queueData.type, currentProduction.name, currentProduction.type, 1);
182
- }
183
- } else {
184
- // Not changing our mind, but maybe other queues are more important for now.
185
- if (totalCostAcrossQueues > myCredits && decision.priority < totalWeightAcrossQueues * 0.25) {
186
- logger(
187
- `Pausing queue ${queueTypeToName(queueData.type)} because weight is low (${
188
- decision.priority
189
- }/${totalWeightAcrossQueues})`,
190
- );
191
- actionsApi.pauseProduction(queueData.type);
192
- }
193
- }
194
- } else if (queueData.status == QueueStatus.OnHold) {
195
- // Consider resuming queue if priority is high relative to other queues.
196
- if (myCredits >= totalCostAcrossQueues) {
197
- logger(`Resuming queue ${queueTypeToName(queueData.type)} because credits are high`);
198
- actionsApi.resumeProduction(queueData.type);
199
- } else if (decision && decision.priority >= totalWeightAcrossQueues * 0.25) {
200
- logger(
201
- `Resuming queue ${queueTypeToName(queueData.type)} because weight is high (${
202
- decision.priority
203
- }/${totalWeightAcrossQueues})`,
204
- );
205
- actionsApi.resumeProduction(queueData.type);
206
- }
207
- }
208
- }
209
-
210
- private getPrioritiesForBuildingOptions(
211
- game: GameApi,
212
- options: TechnoRules[],
213
- threatCache: GlobalThreat | null,
214
- playerData: PlayerData,
215
- unitTypeRequests: Map<string, number>,
216
- logger: DebugLogger,
217
- ): TechnoRulesWithPriority[] {
218
- let priorityQueue: TechnoRulesWithPriority[] = [];
219
- options.forEach((option) => {
220
- const calculatedPriority = this.getPriorityForBuildingOption(option, game, playerData, threatCache);
221
- // Get the higher of the dynamic and the mission priority for the unit.
222
- const actualPriority = Math.max(
223
- calculatedPriority,
224
- unitTypeRequests.get(option.name) ?? calculatedPriority,
225
- );
226
- if (actualPriority > 0) {
227
- priorityQueue.push({ unit: option, priority: actualPriority });
228
- }
229
- });
230
-
231
- priorityQueue = priorityQueue.sort((a, b) => a.priority - b.priority);
232
- return priorityQueue;
233
- }
234
-
235
- private getPriorityForBuildingOption(
236
- option: TechnoRules,
237
- game: GameApi,
238
- playerStatus: PlayerData,
239
- threatCache: GlobalThreat | null,
240
- ) {
241
- if (BUILDING_NAME_TO_RULES.has(option.name)) {
242
- let logic = BUILDING_NAME_TO_RULES.get(option.name)!;
243
- return logic.getPriority(game, playerStatus, option, threatCache);
244
- } else {
245
- // Fallback priority when there are no rules.
246
- return (
247
- DEFAULT_BUILDING_PRIORITY - game.getVisibleUnits(playerStatus.name, "self", (r) => r == option).length
248
- );
249
- }
250
- }
251
-
252
- private getBestLocationForStructure(
253
- game: GameApi,
254
- playerData: PlayerData,
255
- objectReady: TechnoRules,
256
- ): { rx: number; ry: number } | undefined {
257
- if (BUILDING_NAME_TO_RULES.has(objectReady.name)) {
258
- let logic = BUILDING_NAME_TO_RULES.get(objectReady.name)!;
259
- return logic.getPlacementLocation(game, playerData, objectReady);
260
- } else {
261
- // fallback placement logic
262
- return getDefaultPlacementLocation(game, playerData, playerData.startLocation, objectReady);
263
- }
264
- }
265
-
266
- public getGlobalDebugText(gameApi: GameApi, productionApi: ProductionApi) {
267
- const productionState = QUEUES.reduce((prev, queueType) => {
268
- if (productionApi.getQueueData(queueType).size === 0) {
269
- return prev;
270
- }
271
- const paused = productionApi.getQueueData(queueType).status === QueueStatus.OnHold;
272
- return (
273
- prev +
274
- " [" +
275
- queueTypeToName(queueType) +
276
- (paused ? " PAUSED" : "") +
277
- ": " +
278
- productionApi
279
- .getQueueData(queueType)
280
- .items.map((item) => item.rules.name + (item.quantity > 1 ? "x" + item.quantity : "")) +
281
- "]"
282
- );
283
- }, "");
284
-
285
- const queueStates = this.queueStates
286
- .filter((queueState) => queueState.items.length > 0)
287
- .map((queueState) => {
288
- const queueString = queueState.items
289
- .map((item) => item.unit.name + "(" + Math.round(item.priority * 10) / 10 + ")")
290
- .join(", ");
291
- return `${queueTypeToName(queueState.queue)} Prios: ${queueString}\n`;
292
- })
293
- .join("");
294
-
295
- return `Production: ${productionState}\n${queueStates}`;
296
- }
297
- }
1
+ import {
2
+ ActionsApi,
3
+ GameApi,
4
+ PlayerData,
5
+ ProductionApi,
6
+ QueueStatus,
7
+ QueueType,
8
+ TechnoRules,
9
+ } from "@chronodivide/game-api";
10
+ import { GlobalThreat } from "../threat/threat";
11
+ import {
12
+ TechnoRulesWithPriority,
13
+ BUILDING_NAME_TO_RULES,
14
+ DEFAULT_BUILDING_PRIORITY,
15
+ getDefaultPlacementLocation,
16
+ } from "./buildingRules.js";
17
+ import { DebugLogger } from "../common/utils";
18
+
19
+ export const QUEUES = [
20
+ QueueType.Structures,
21
+ QueueType.Armory,
22
+ QueueType.Infantry,
23
+ QueueType.Vehicles,
24
+ QueueType.Aircrafts,
25
+ QueueType.Ships,
26
+ ];
27
+
28
+ export const queueTypeToName = (queue: QueueType) => {
29
+ switch (queue) {
30
+ case QueueType.Structures:
31
+ return "Structures";
32
+ case QueueType.Armory:
33
+ return "Armory";
34
+ case QueueType.Infantry:
35
+ return "Infantry";
36
+ case QueueType.Vehicles:
37
+ return "Vehicles";
38
+ case QueueType.Aircrafts:
39
+ return "Aircrafts";
40
+ case QueueType.Ships:
41
+ return "Ships";
42
+ default:
43
+ return "Unknown";
44
+ }
45
+ };
46
+
47
+ type QueueState = {
48
+ queue: QueueType;
49
+ /** sorted in ascending order (last item is the topItem) */
50
+ items: TechnoRulesWithPriority[];
51
+ topItem: TechnoRulesWithPriority | undefined;
52
+ };
53
+
54
+ export class QueueController {
55
+ private queueStates: QueueState[] = [];
56
+
57
+ constructor() {}
58
+
59
+ public onAiUpdate(
60
+ game: GameApi,
61
+ productionApi: ProductionApi,
62
+ actionsApi: ActionsApi,
63
+ playerData: PlayerData,
64
+ threatCache: GlobalThreat | null,
65
+ unitTypeRequests: Map<string, number>,
66
+ logger: (message: string) => void,
67
+ ) {
68
+ this.queueStates = QUEUES.map((queueType) => {
69
+ const options = productionApi.getAvailableObjects(queueType);
70
+ const items = this.getPrioritiesForBuildingOptions(
71
+ game,
72
+ options,
73
+ threatCache,
74
+ playerData,
75
+ unitTypeRequests,
76
+ logger,
77
+ );
78
+ const topItem = items.length > 0 ? items[items.length - 1] : undefined;
79
+ return {
80
+ queue: queueType,
81
+ items,
82
+ // only if the top item has a priority above zero
83
+ topItem: topItem && topItem.priority > 0 ? topItem : undefined,
84
+ };
85
+ });
86
+ const totalWeightAcrossQueues = this.queueStates
87
+ .map((decision) => decision.topItem?.priority!)
88
+ .reduce((pV, cV) => pV + cV, 0);
89
+ const totalCostAcrossQueues = this.queueStates
90
+ .map((decision) => decision.topItem?.unit.cost!)
91
+ .reduce((pV, cV) => pV + cV, 0);
92
+
93
+ this.queueStates.forEach((decision) => {
94
+ this.updateBuildQueue(
95
+ game,
96
+ productionApi,
97
+ actionsApi,
98
+ playerData,
99
+ threatCache,
100
+ decision.queue,
101
+ decision.topItem,
102
+ totalWeightAcrossQueues,
103
+ totalCostAcrossQueues,
104
+ logger,
105
+ );
106
+ });
107
+
108
+ // Repair is simple - just repair everything that's damaged.
109
+ if (playerData.credits > 0) {
110
+ game.getVisibleUnits(playerData.name, "self", (r) => r.repairable).forEach((unitId) => {
111
+ const unit = game.getUnitData(unitId);
112
+ if (!unit || !unit.hitPoints || !unit.maxHitPoints || unit.hasWrenchRepair) {
113
+ return;
114
+ }
115
+ if (unit.hitPoints < unit.maxHitPoints) {
116
+ actionsApi.toggleRepairWrench(unitId);
117
+ }
118
+ });
119
+ }
120
+ }
121
+
122
+ private updateBuildQueue(
123
+ game: GameApi,
124
+ productionApi: ProductionApi,
125
+ actionsApi: ActionsApi,
126
+ playerData: PlayerData,
127
+ threatCache: GlobalThreat | null,
128
+ queueType: QueueType,
129
+ decision: TechnoRulesWithPriority | undefined,
130
+ totalWeightAcrossQueues: number,
131
+ totalCostAcrossQueues: number,
132
+ logger: (message: string) => void,
133
+ ): void {
134
+ const myCredits = playerData.credits;
135
+
136
+ const queueData = productionApi.getQueueData(queueType);
137
+ if (queueData.status == QueueStatus.Idle) {
138
+ // Start building the decided item.
139
+ if (decision !== undefined) {
140
+ logger(`Decision (${queueTypeToName(queueType)}): ${decision.unit.name}`);
141
+ actionsApi.queueForProduction(queueType, decision.unit.name, decision.unit.type, 1);
142
+ }
143
+ } else if (queueData.status == QueueStatus.Ready && queueData.items.length > 0) {
144
+ // Consider placing it.
145
+ const objectReady: TechnoRules = queueData.items[0].rules;
146
+ if (queueType == QueueType.Structures || queueType == QueueType.Armory) {
147
+ let location: { rx: number; ry: number } | undefined = this.getBestLocationForStructure(
148
+ game,
149
+ playerData,
150
+ objectReady,
151
+ );
152
+ if (location !== undefined) {
153
+ logger(
154
+ `Completed: ${queueTypeToName(queueType)}: ${objectReady.name}, placing at ${location.rx},${
155
+ location.ry
156
+ }`,
157
+ );
158
+ actionsApi.placeBuilding(objectReady.name, location.rx, location.ry);
159
+ } else {
160
+ logger(`Completed: ${queueTypeToName(queueType)}: ${objectReady.name} but nowhere to place it`);
161
+ }
162
+ }
163
+ } else if (queueData.status == QueueStatus.Active && queueData.items.length > 0 && decision != null) {
164
+ // Consider cancelling if something else is significantly higher priority than what is currently being produced.
165
+ const currentProduction = queueData.items[0].rules;
166
+ if (decision.unit != currentProduction) {
167
+ // Changing our mind.
168
+ let currentItemPriority = this.getPriorityForBuildingOption(
169
+ currentProduction,
170
+ game,
171
+ playerData,
172
+ threatCache,
173
+ );
174
+ let newItemPriority = decision.priority;
175
+ if (newItemPriority > currentItemPriority * 2) {
176
+ logger(
177
+ `Dequeueing queue ${queueTypeToName(queueData.type)} unit ${currentProduction.name} because ${
178
+ decision.unit.name
179
+ } has 2x higher priority.`,
180
+ );
181
+ actionsApi.unqueueFromProduction(queueData.type, currentProduction.name, currentProduction.type, 1);
182
+ }
183
+ } else {
184
+ // Not changing our mind, but maybe other queues are more important for now.
185
+ if (totalCostAcrossQueues > myCredits && decision.priority < totalWeightAcrossQueues * 0.25) {
186
+ logger(
187
+ `Pausing queue ${queueTypeToName(queueData.type)} because weight is low (${
188
+ decision.priority
189
+ }/${totalWeightAcrossQueues})`,
190
+ );
191
+ actionsApi.pauseProduction(queueData.type);
192
+ }
193
+ }
194
+ } else if (queueData.status == QueueStatus.OnHold) {
195
+ // Consider resuming queue if priority is high relative to other queues.
196
+ if (myCredits >= totalCostAcrossQueues) {
197
+ logger(`Resuming queue ${queueTypeToName(queueData.type)} because credits are high`);
198
+ actionsApi.resumeProduction(queueData.type);
199
+ } else if (decision && decision.priority >= totalWeightAcrossQueues * 0.25) {
200
+ logger(
201
+ `Resuming queue ${queueTypeToName(queueData.type)} because weight is high (${
202
+ decision.priority
203
+ }/${totalWeightAcrossQueues})`,
204
+ );
205
+ actionsApi.resumeProduction(queueData.type);
206
+ }
207
+ }
208
+ }
209
+
210
+ private getPrioritiesForBuildingOptions(
211
+ game: GameApi,
212
+ options: TechnoRules[],
213
+ threatCache: GlobalThreat | null,
214
+ playerData: PlayerData,
215
+ unitTypeRequests: Map<string, number>,
216
+ logger: DebugLogger,
217
+ ): TechnoRulesWithPriority[] {
218
+ let priorityQueue: TechnoRulesWithPriority[] = [];
219
+ options.forEach((option) => {
220
+ const calculatedPriority = this.getPriorityForBuildingOption(option, game, playerData, threatCache);
221
+ // Get the higher of the dynamic and the mission priority for the unit.
222
+ const actualPriority = Math.max(
223
+ calculatedPriority,
224
+ unitTypeRequests.get(option.name) ?? calculatedPriority,
225
+ );
226
+ if (actualPriority > 0) {
227
+ priorityQueue.push({ unit: option, priority: actualPriority });
228
+ }
229
+ });
230
+
231
+ priorityQueue = priorityQueue.sort((a, b) => a.priority - b.priority);
232
+ return priorityQueue;
233
+ }
234
+
235
+ private getPriorityForBuildingOption(
236
+ option: TechnoRules,
237
+ game: GameApi,
238
+ playerStatus: PlayerData,
239
+ threatCache: GlobalThreat | null,
240
+ ) {
241
+ if (BUILDING_NAME_TO_RULES.has(option.name)) {
242
+ let logic = BUILDING_NAME_TO_RULES.get(option.name)!;
243
+ return logic.getPriority(game, playerStatus, option, threatCache);
244
+ } else {
245
+ // Fallback priority when there are no rules.
246
+ return (
247
+ DEFAULT_BUILDING_PRIORITY - game.getVisibleUnits(playerStatus.name, "self", (r) => r == option).length
248
+ );
249
+ }
250
+ }
251
+
252
+ private getBestLocationForStructure(
253
+ game: GameApi,
254
+ playerData: PlayerData,
255
+ objectReady: TechnoRules,
256
+ ): { rx: number; ry: number } | undefined {
257
+ if (BUILDING_NAME_TO_RULES.has(objectReady.name)) {
258
+ let logic = BUILDING_NAME_TO_RULES.get(objectReady.name)!;
259
+ return logic.getPlacementLocation(game, playerData, objectReady);
260
+ } else {
261
+ // fallback placement logic
262
+ return getDefaultPlacementLocation(game, playerData, playerData.startLocation, objectReady);
263
+ }
264
+ }
265
+
266
+ public getGlobalDebugText(gameApi: GameApi, productionApi: ProductionApi) {
267
+ const productionState = QUEUES.reduce((prev, queueType) => {
268
+ if (productionApi.getQueueData(queueType).size === 0) {
269
+ return prev;
270
+ }
271
+ const paused = productionApi.getQueueData(queueType).status === QueueStatus.OnHold;
272
+ return (
273
+ prev +
274
+ " [" +
275
+ queueTypeToName(queueType) +
276
+ (paused ? " PAUSED" : "") +
277
+ ": " +
278
+ productionApi
279
+ .getQueueData(queueType)
280
+ .items.map((item) => item.rules.name + (item.quantity > 1 ? "x" + item.quantity : "")) +
281
+ "]"
282
+ );
283
+ }, "");
284
+
285
+ const queueStates = this.queueStates
286
+ .filter((queueState) => queueState.items.length > 0)
287
+ .map((queueState) => {
288
+ const queueString = queueState.items
289
+ .map((item) => item.unit.name + "(" + Math.round(item.priority * 10) / 10 + ")")
290
+ .join(", ");
291
+ return `${queueTypeToName(queueState.queue)} Prios: ${queueString}\n`;
292
+ })
293
+ .join("");
294
+
295
+ return `Production: ${productionState}\n${queueStates}`;
296
+ }
297
+ }