@supalosa/chronodivide-bot 0.1.0 → 0.2.0

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 (74) hide show
  1. package/README.md +71 -46
  2. package/dist/bot/bot.js +27 -183
  3. package/dist/bot/logic/awareness.js +122 -0
  4. package/dist/bot/logic/building/basicGroundUnit.js +8 -6
  5. package/dist/bot/logic/building/building.js +6 -3
  6. package/dist/bot/logic/building/harvester.js +1 -1
  7. package/dist/bot/logic/building/queueController.js +4 -21
  8. package/dist/bot/logic/common/scout.js +10 -0
  9. package/dist/bot/logic/knowledge.js +1 -0
  10. package/dist/bot/logic/map/map.js +6 -0
  11. package/dist/bot/logic/map/sector.js +6 -1
  12. package/dist/bot/logic/mission/basicMission.js +1 -5
  13. package/dist/bot/logic/mission/expansionMission.js +22 -4
  14. package/dist/bot/logic/mission/mission.js +49 -2
  15. package/dist/bot/logic/mission/missionController.js +67 -34
  16. package/dist/bot/logic/mission/missionFactories.js +10 -0
  17. package/dist/bot/logic/mission/missions/attackMission.js +109 -0
  18. package/dist/bot/logic/mission/missions/defenceMission.js +62 -0
  19. package/dist/bot/logic/mission/missions/expansionMission.js +24 -0
  20. package/dist/bot/logic/mission/missions/oneTimeMission.js +26 -0
  21. package/dist/bot/logic/mission/missions/retreatMission.js +7 -0
  22. package/dist/bot/logic/mission/missions/scoutingMission.js +38 -0
  23. package/dist/bot/logic/squad/behaviours/attackSquad.js +82 -0
  24. package/dist/bot/logic/squad/behaviours/combatSquad.js +99 -0
  25. package/dist/bot/logic/squad/behaviours/common.js +37 -0
  26. package/dist/bot/logic/squad/behaviours/defenceSquad.js +48 -0
  27. package/dist/bot/logic/squad/behaviours/expansionSquad.js +42 -0
  28. package/dist/bot/logic/squad/behaviours/retreatSquad.js +32 -0
  29. package/dist/bot/logic/squad/behaviours/scoutingSquad.js +38 -0
  30. package/dist/bot/logic/squad/behaviours/squadExpansion.js +26 -13
  31. package/dist/bot/logic/squad/squad.js +68 -15
  32. package/dist/bot/logic/squad/squadBehaviour.js +5 -5
  33. package/dist/bot/logic/squad/squadBehaviours.js +6 -0
  34. package/dist/bot/logic/squad/squadController.js +106 -15
  35. package/dist/exampleBot.js +22 -7
  36. package/package.json +29 -24
  37. package/src/bot/bot.ts +178 -378
  38. package/src/bot/logic/awareness.ts +220 -0
  39. package/src/bot/logic/building/ArtilleryUnit.ts +2 -2
  40. package/src/bot/logic/building/antiGroundStaticDefence.ts +2 -2
  41. package/src/bot/logic/building/basicAirUnit.ts +2 -2
  42. package/src/bot/logic/building/basicBuilding.ts +2 -2
  43. package/src/bot/logic/building/basicGroundUnit.ts +83 -78
  44. package/src/bot/logic/building/building.ts +125 -120
  45. package/src/bot/logic/building/harvester.ts +27 -27
  46. package/src/bot/logic/building/powerPlant.ts +1 -1
  47. package/src/bot/logic/building/queueController.ts +17 -38
  48. package/src/bot/logic/building/resourceCollectionBuilding.ts +1 -1
  49. package/src/bot/logic/common/scout.ts +12 -0
  50. package/src/bot/logic/map/map.ts +11 -3
  51. package/src/bot/logic/map/sector.ts +136 -130
  52. package/src/bot/logic/mission/mission.ts +83 -47
  53. package/src/bot/logic/mission/missionController.ts +103 -51
  54. package/src/bot/logic/mission/missionFactories.ts +46 -0
  55. package/src/bot/logic/mission/missions/attackMission.ts +152 -0
  56. package/src/bot/logic/mission/missions/defenceMission.ts +104 -0
  57. package/src/bot/logic/mission/missions/expansionMission.ts +49 -0
  58. package/src/bot/logic/mission/missions/oneTimeMission.ts +32 -0
  59. package/src/bot/logic/mission/missions/retreatMission.ts +9 -0
  60. package/src/bot/logic/mission/missions/scoutingMission.ts +59 -0
  61. package/src/bot/logic/squad/behaviours/combatSquad.ts +125 -0
  62. package/src/bot/logic/squad/behaviours/common.ts +37 -0
  63. package/src/bot/logic/squad/behaviours/expansionSquad.ts +59 -0
  64. package/src/bot/logic/squad/behaviours/retreatSquad.ts +46 -0
  65. package/src/bot/logic/squad/behaviours/scoutingSquad.ts +56 -0
  66. package/src/bot/logic/squad/squad.ts +163 -97
  67. package/src/bot/logic/squad/squadBehaviour.ts +61 -43
  68. package/src/bot/logic/squad/squadBehaviours.ts +8 -0
  69. package/src/bot/logic/squad/squadController.ts +190 -66
  70. package/src/exampleBot.ts +19 -4
  71. package/tsconfig.json +1 -1
  72. package/src/bot/logic/mission/basicMission.ts +0 -42
  73. package/src/bot/logic/mission/expansionMission.ts +0 -25
  74. package/src/bot/logic/squad/behaviours/squadExpansion.ts +0 -33
package/src/bot/bot.ts CHANGED
@@ -1,378 +1,178 @@
1
- import {
2
- OrderType,
3
- ApiEventType,
4
- Bot,
5
- GameApi,
6
- ApiEvent,
7
- TechnoRules,
8
- QueueType,
9
- QueueStatus,
10
- Point2D,
11
- MapApi,
12
- ObjectType,
13
- FactoryType,
14
- AttackState,
15
- PlayerData,
16
- } from "@chronodivide/game-api";
17
- import PriorityQueue from "priority-queue-typescript";
18
-
19
- import { Duration } from "luxon";
20
-
21
- import { determineMapBounds, getDistanceBetweenPoints, getPointTowardsOtherPoint } from "./logic/map/map.js";
22
- import { SectorCache } from "./logic/map/sector.js";
23
- import { missionFactories } from "./logic/mission/mission.js";
24
- import { MissionController } from "./logic/mission/missionController.js";
25
- import { SquadController } from "./logic/squad/squadController.js";
26
- import { GlobalThreat } from "./logic/threat/threat.js";
27
- import { calculateGlobalThreat } from "./logic/threat/threatCalculator.js";
28
- import { QUEUES, QueueController, queueTypeToName } from "./logic/building/queueController.js";
29
-
30
- enum BotState {
31
- Initial = "init",
32
- Deployed = "deployed",
33
- Attacking = "attack",
34
- Defending = "defend",
35
- Scouting = "scout",
36
- Defeated = "defeat",
37
- }
38
-
39
- const DEBUG_TIMESTAMP_OUTPUT_INTERVAL_SECONDS = 60;
40
- const NATURAL_TICK_RATE = 15;
41
- const BOT_AUTO_SURRENDER_TIME_SECONDS = 7200; // 2 hours (approx 30 mins in real game)
42
-
43
- export class SupalosaBot extends Bot {
44
- private botState = BotState.Initial;
45
- private tickRatio!: number;
46
- private enemyPlayers!: string[];
47
- private knownMapBounds: Point2D | undefined;
48
- private sectorCache: SectorCache | undefined;
49
- private threatCache: GlobalThreat | undefined;
50
- private missionController: MissionController;
51
- private squadController: SquadController;
52
- private queueController: QueueController;
53
- private tickOfLastAttackOrder: number = 0;
54
-
55
- private enableLogging: boolean;
56
-
57
- constructor(name: string, country: string, enableLogging = true) {
58
- super(name, country);
59
- this.squadController = new SquadController();
60
- this.missionController = new MissionController();
61
- this.queueController = new QueueController();
62
- this.enableLogging = enableLogging;
63
- }
64
-
65
- override onGameStart(game: GameApi) {
66
- const gameRate = game.getTickRate();
67
- const botApm = 300;
68
- const botRate = botApm / 60;
69
- this.tickRatio = Math.ceil(gameRate / botRate);
70
-
71
- this.enemyPlayers = game.getPlayers().filter((p) => p !== this.name && !game.areAlliedPlayers(this.name, p));
72
-
73
- this.knownMapBounds = determineMapBounds(game.mapApi);
74
- this.sectorCache = new SectorCache(game.mapApi, this.knownMapBounds);
75
- this.threatCache = undefined;
76
-
77
- this.logBotStatus(`Map bounds: ${this.knownMapBounds.x}, ${this.knownMapBounds.y}`);
78
- }
79
-
80
- override onGameTick(game: GameApi) {
81
- if ((game.getCurrentTick() / NATURAL_TICK_RATE) % DEBUG_TIMESTAMP_OUTPUT_INTERVAL_SECONDS === 0) {
82
- this.logDebugState(game);
83
- }
84
- if (game.getCurrentTick() % this.tickRatio === 0) {
85
- const myPlayer = game.getPlayerData(this.name);
86
- const sectorsToUpdatePerCycle = 8; // TODO tune this
87
- this.sectorCache?.updateSectors(game.getCurrentTick(), sectorsToUpdatePerCycle, game.mapApi, myPlayer);
88
- let updateRatio = this.sectorCache?.getSectorUpdateRatio(game.getCurrentTick() - game.getTickRate() * 60);
89
- if (updateRatio && updateRatio < 1.0) {
90
- this.logBotStatus(`${updateRatio * 100.0}% of sectors updated in last 60 seconds.`);
91
- }
92
-
93
- // Threat decays over time if we haven't killed anything
94
- let boredomFactor =
95
- 1.0 -
96
- Math.min(1.0, Math.max(0.0, (this.gameApi.getCurrentTick() - this.tickOfLastAttackOrder) / 1600.0));
97
- let shouldAttack = this.threatCache ? this.isWorthAttacking(this.threatCache, boredomFactor) : false;
98
- if (game.getCurrentTick() % (this.tickRatio * 150) == 0) {
99
- let visibility = this.sectorCache?.getOverallVisibility();
100
- if (visibility) {
101
- this.logBotStatus(`${Math.round(visibility * 1000.0) / 10}% of tiles visible. Calculating threat.`);
102
- this.threatCache = calculateGlobalThreat(game, myPlayer, visibility);
103
- this.logBotStatus(
104
- `Threat LAND: Them ${Math.round(this.threatCache.totalOffensiveLandThreat)}, us: ${Math.round(
105
- this.threatCache.totalAvailableAntiGroundFirepower
106
- )}.`
107
- );
108
- this.logBotStatus(
109
- `Threat DEFENSIVE: Them ${Math.round(this.threatCache.totalDefensiveThreat)}, us: ${Math.round(
110
- this.threatCache.totalDefensivePower
111
- )}.`
112
- );
113
- this.logBotStatus(
114
- `Threat AIR: Them ${Math.round(this.threatCache.totalOffensiveAirThreat)}, us: ${Math.round(
115
- this.threatCache.totalAvailableAntiAirFirepower
116
- )}.`
117
- );
118
- this.logBotStatus(`Boredom: ${boredomFactor}`);
119
- }
120
- }
121
- if (game.getCurrentTick() / NATURAL_TICK_RATE > BOT_AUTO_SURRENDER_TIME_SECONDS) {
122
- this.logBotStatus(`Auto-surrendering after ${BOT_AUTO_SURRENDER_TIME_SECONDS} seconds.`);
123
- this.botState = BotState.Defeated;
124
- this.actionsApi.quitGame();
125
- }
126
-
127
- // hacky resign condition
128
- const armyUnits = game.getVisibleUnits(this.name, "self", (r) => r.isSelectableCombatant);
129
- const mcvUnits = game.getVisibleUnits(
130
- this.name,
131
- "self",
132
- (r) => !!r.deploysInto && game.getGeneralRules().baseUnit.includes(r.name)
133
- );
134
- const productionBuildings = game.getVisibleUnits(
135
- this.name,
136
- "self",
137
- (r) => r.type == ObjectType.Building && r.factory != FactoryType.None
138
- );
139
- if (armyUnits.length == 0 && productionBuildings.length == 0 && mcvUnits.length == 0) {
140
- this.logBotStatus(`No army or production left, quitting.`);
141
- this.botState = BotState.Defeated;
142
- this.actionsApi.quitGame();
143
- }
144
-
145
- // Build logic.
146
- this.queueController.onAiUpdate(
147
- game,
148
- this.productionApi,
149
- this.actionsApi,
150
- myPlayer,
151
- this.threatCache,
152
- (message) => this.logBotStatus(message)
153
- );
154
-
155
- // Mission logic.
156
- this.missionController.onAiUpdate(game, myPlayer, this.threatCache);
157
-
158
- // Squad logic.
159
- this.squadController.onAiUpdate(game, myPlayer, this.threatCache);
160
-
161
- switch (this.botState) {
162
- case BotState.Initial: {
163
- const baseUnits = game.getGeneralRules().baseUnit;
164
- let conYards = game.getVisibleUnits(this.name, "self", (r) => r.constructionYard);
165
- if (conYards.length) {
166
- this.botState = BotState.Deployed;
167
- break;
168
- }
169
- const units = game.getVisibleUnits(this.name, "self", (r) => baseUnits.includes(r.name));
170
- if (units.length) {
171
- this.actionsApi.orderUnits([units[0]], OrderType.DeploySelected);
172
- }
173
- break;
174
- }
175
- case BotState.Deployed: {
176
- this.botState = BotState.Attacking;
177
- break;
178
- }
179
- case BotState.Attacking: {
180
- const armyUnits = game.getVisibleUnits(this.name, "self", (r) => r.isSelectableCombatant);
181
- if (!shouldAttack) {
182
- this.logBotStatus(`Not worth attacking, reverting to defence.`);
183
- this.botState = BotState.Defending;
184
- }
185
- const enemyBuildings = game.getVisibleUnits(this.name, "hostile");
186
- let foundTarget = false;
187
- if (enemyBuildings.length) {
188
- const weightedTargets = enemyBuildings
189
- .filter((unit) => this.isHostileUnit(game, unit))
190
- .map((unitId) => {
191
- let unit = game.getUnitData(unitId);
192
- return {
193
- unit,
194
- unitId: unitId,
195
- weight: getDistanceBetweenPoints(myPlayer.startLocation, {
196
- x: unit!.tile.rx,
197
- y: unit!.tile.rx,
198
- }),
199
- };
200
- })
201
- .filter((unit) => unit.unit != null);
202
- weightedTargets.sort((targetA, targetB) => {
203
- return targetA.weight - targetB.weight;
204
- });
205
- const target = weightedTargets.find((_) => true);
206
- if (target !== undefined) {
207
- let targetData = target.unit;
208
- for (const unitId of armyUnits) {
209
- const unit = game.getUnitData(unitId);
210
- foundTarget = true;
211
- if (shouldAttack && unit?.isIdle) {
212
- let orderType: OrderType = OrderType.AttackMove;
213
- if (targetData?.type == ObjectType.Building) {
214
- orderType = OrderType.Attack;
215
- } else if (targetData?.rules.canDisguise) {
216
- // Special case for mirage tank/spy as otherwise they just sit next to it.
217
- orderType = OrderType.Attack;
218
- }
219
- this.actionsApi.orderUnits([unitId], orderType, target.unitId);
220
- }
221
- }
222
- }
223
- }
224
- if (!foundTarget) {
225
- this.logBotStatus(`Can't see any targets, scouting.`);
226
- this.botState = BotState.Scouting;
227
- }
228
- break;
229
- }
230
- case BotState.Defending: {
231
- const armyUnits = game.getVisibleUnits(this.name, "self", (r) => r.isSelectableCombatant);
232
- const enemy = game.getPlayerData(this.enemyPlayers[0]);
233
- const fallbackPoint = getPointTowardsOtherPoint(
234
- game,
235
- myPlayer.startLocation,
236
- enemy.startLocation,
237
- 10,
238
- 10,
239
- 0
240
- );
241
-
242
- armyUnits.forEach((armyUnitId) => {
243
- let unit = game.getUnitData(armyUnitId);
244
- if (unit && !unit.guardMode) {
245
- let distanceToFallback = getDistanceBetweenPoints(
246
- { x: unit.tile.rx, y: unit.tile.ry },
247
- fallbackPoint
248
- );
249
- if (distanceToFallback > 10) {
250
- this.actionsApi.orderUnits(
251
- [armyUnitId],
252
- OrderType.GuardArea,
253
- fallbackPoint.x,
254
- fallbackPoint.y
255
- );
256
- }
257
- }
258
- });
259
- if (shouldAttack) {
260
- this.logBotStatus(`Finished defending, ready to attack.`);
261
- this.botState = BotState.Attacking;
262
- }
263
- break;
264
- }
265
- case BotState.Scouting: {
266
- const armyUnits = game.getVisibleUnits(this.name, "self", (r) => r.isSelectableCombatant);
267
- let candidatePoints: Point2D[] = [];
268
-
269
- // Move to an unseen starting location.
270
- const unseenStartingLocations = game.mapApi.getStartingLocations().filter((startingLocation) => {
271
- if (startingLocation == game.getPlayerData(this.name).startLocation) {
272
- return false;
273
- }
274
- let tile = game.mapApi.getTile(startingLocation.x, startingLocation.y);
275
- return tile ? !game.mapApi.isVisibleTile(tile, this.name) : false;
276
- });
277
- candidatePoints.push(...unseenStartingLocations);
278
-
279
- armyUnits.forEach((unitId) => {
280
- if (candidatePoints.length > 0) {
281
- const unit = game.getUnitData(unitId);
282
- if (unit?.isIdle) {
283
- const scoutLocation =
284
- candidatePoints[Math.floor(game.generateRandom() * candidatePoints.length)];
285
- this.actionsApi.orderUnits(
286
- [unitId],
287
- OrderType.AttackMove,
288
- scoutLocation.x,
289
- scoutLocation.y
290
- );
291
- }
292
- }
293
- });
294
- const enemyBuildings = game
295
- .getVisibleUnits(this.name, "hostile")
296
- .filter((unit) => this.isHostileUnit(game, unit));
297
- if (enemyBuildings.length > 0) {
298
- this.logBotStatus(`Scouted a target, reverting to attack mode.`);
299
- this.botState = BotState.Attacking;
300
- }
301
- break;
302
- }
303
-
304
- default:
305
- break;
306
- }
307
- }
308
- }
309
-
310
- private getHumanTimestamp(game: GameApi) {
311
- return Duration.fromMillis((game.getCurrentTick() / NATURAL_TICK_RATE) * 1000).toFormat("hh:mm:ss");
312
- }
313
-
314
- private logBotStatus(message: string) {
315
- if (!this.enableLogging) {
316
- return;
317
- }
318
- console.log(`[${this.getHumanTimestamp(this.gameApi)} ${this.name} ${this.botState}] ${message}`);
319
- }
320
-
321
- private logDebugState(game: GameApi) {
322
- const myPlayer = game.getPlayerData(this.name);
323
- const queueState = QUEUES.reduce((prev, queueType) => {
324
- if (this.productionApi.getQueueData(queueType).size === 0) {
325
- return prev;
326
- }
327
- const paused = this.productionApi.getQueueData(queueType).status === QueueStatus.OnHold;
328
- return (
329
- prev +
330
- " [" +
331
- queueTypeToName(queueType) +
332
- (paused ? " PAUSED" : "") +
333
- ": " +
334
- this.productionApi.getQueueData(queueType).items.map((item) => item.rules.name + "x" + item.quantity) +
335
- "]"
336
- );
337
- }, "");
338
- this.logBotStatus(`----- Cash: ${myPlayer.credits} ----- | Queues: ${queueState}`);
339
- const harvesters = game.getVisibleUnits(this.name, "self", (r) => r.harvester).length;
340
- this.logBotStatus(`Harvesters: ${harvesters}`);
341
- this.logBotStatus(`----- End -----`);
342
- }
343
-
344
- private isWorthAttacking(threatCache: GlobalThreat, threatFactor: number) {
345
- let scaledGroundPower = Math.pow(threatCache.totalAvailableAntiGroundFirepower, 1.125);
346
- let scaledGroundThreat =
347
- (threatFactor * threatCache.totalOffensiveLandThreat + threatCache.totalDefensiveThreat) * 1.1;
348
-
349
- let scaledAirPower = Math.pow(threatCache.totalAvailableAirPower, 1.125);
350
- let scaledAirThreat =
351
- (threatFactor * threatCache.totalOffensiveAntiAirThreat + threatCache.totalDefensiveThreat) * 1.1;
352
-
353
- return scaledGroundPower > scaledGroundThreat || scaledAirPower > scaledAirThreat;
354
- }
355
-
356
- private isHostileUnit(game: GameApi, unitId: number) {
357
- const unitData = game.getUnitData(unitId);
358
- if (!unitData) {
359
- return false;
360
- }
361
-
362
- return unitData.owner != this.name && game.getPlayerData(unitData.owner)?.isCombatant;
363
- }
364
-
365
- override onGameEvent(ev: ApiEvent) {
366
- switch (ev.type) {
367
- case ApiEventType.ObjectDestroy: {
368
- // Add to the stalemate detection.
369
- if (ev.attackerInfo?.playerName == this.name) {
370
- this.tickOfLastAttackOrder += (this.gameApi.getCurrentTick() - this.tickOfLastAttackOrder) / 2;
371
- }
372
- break;
373
- }
374
- default:
375
- break;
376
- }
377
- }
378
- }
1
+ import {
2
+ OrderType,
3
+ ApiEventType,
4
+ Bot,
5
+ GameApi,
6
+ ApiEvent,
7
+ QueueStatus,
8
+ Point2D,
9
+ ObjectType,
10
+ FactoryType,
11
+ } from "@chronodivide/game-api";
12
+
13
+ import { Duration } from "luxon";
14
+
15
+ import { determineMapBounds } from "./logic/map/map.js";
16
+ import { SectorCache } from "./logic/map/sector.js";
17
+ import { MissionController } from "./logic/mission/missionController.js";
18
+ import { SquadController } from "./logic/squad/squadController.js";
19
+ import { QUEUES, QueueController, queueTypeToName } from "./logic/building/queueController.js";
20
+ import { MatchAwareness as MatchAwareness, MatchAwarenessImpl } from "./logic/awareness.js";
21
+
22
+ const DEBUG_TIMESTAMP_OUTPUT_INTERVAL_SECONDS = 60;
23
+ const NATURAL_TICK_RATE = 15;
24
+ const BOT_AUTO_SURRENDER_TIME_SECONDS = 7200; // 7200; // 2 hours (approx 30 mins in real game)
25
+
26
+ export class SupalosaBot extends Bot {
27
+ private tickRatio!: number;
28
+ private knownMapBounds: Point2D | undefined;
29
+ private missionController: MissionController;
30
+ private squadController: SquadController;
31
+ private queueController: QueueController;
32
+ private tickOfLastAttackOrder: number = 0;
33
+
34
+ private matchAwareness: MatchAwareness | null = null;
35
+
36
+ private enableLogging: boolean;
37
+
38
+ constructor(name: string, country: string, enableLogging = true) {
39
+ super(name, country);
40
+ this.missionController = new MissionController((message) => this.logBotStatus(message));
41
+ this.squadController = new SquadController();
42
+ this.queueController = new QueueController();
43
+ this.enableLogging = enableLogging;
44
+ }
45
+
46
+ override onGameStart(game: GameApi) {
47
+ const gameRate = game.getTickRate();
48
+ const botApm = 300;
49
+ const botRate = botApm / 60;
50
+ this.tickRatio = Math.ceil(gameRate / botRate);
51
+
52
+ this.knownMapBounds = determineMapBounds(game.mapApi);
53
+
54
+ this.matchAwareness = new MatchAwarenessImpl(
55
+ null,
56
+ new SectorCache(game.mapApi, this.knownMapBounds),
57
+ game.getPlayerData(this.name).startLocation,
58
+ (msg) => this.logBotStatus(msg),
59
+ );
60
+
61
+ this.logBotStatus(`Map bounds: ${this.knownMapBounds.x}, ${this.knownMapBounds.y}`);
62
+ }
63
+
64
+ override onGameTick(game: GameApi) {
65
+ if (!this.matchAwareness) {
66
+ return;
67
+ }
68
+
69
+ const threatCache = this.matchAwareness.getThreatCache();
70
+
71
+ if ((game.getCurrentTick() / NATURAL_TICK_RATE) % DEBUG_TIMESTAMP_OUTPUT_INTERVAL_SECONDS === 0) {
72
+ this.logDebugState(game);
73
+ }
74
+
75
+ if (game.getCurrentTick() % this.tickRatio === 0) {
76
+ const myPlayer = game.getPlayerData(this.name);
77
+
78
+ this.matchAwareness.onAiUpdate(game, myPlayer);
79
+
80
+ if (game.getCurrentTick() / NATURAL_TICK_RATE > BOT_AUTO_SURRENDER_TIME_SECONDS) {
81
+ this.logBotStatus(`Auto-surrendering after ${BOT_AUTO_SURRENDER_TIME_SECONDS} seconds.`);
82
+ this.actionsApi.quitGame();
83
+ }
84
+
85
+ // hacky resign condition
86
+ const armyUnits = game.getVisibleUnits(this.name, "self", (r) => r.isSelectableCombatant);
87
+ const mcvUnits = game.getVisibleUnits(
88
+ this.name,
89
+ "self",
90
+ (r) => !!r.deploysInto && game.getGeneralRules().baseUnit.includes(r.name),
91
+ );
92
+ const productionBuildings = game.getVisibleUnits(
93
+ this.name,
94
+ "self",
95
+ (r) => r.type == ObjectType.Building && r.factory != FactoryType.None,
96
+ );
97
+ if (armyUnits.length == 0 && productionBuildings.length == 0 && mcvUnits.length == 0) {
98
+ this.logBotStatus(`No army or production left, quitting.`);
99
+ this.actionsApi.quitGame();
100
+ }
101
+
102
+ // Build logic.
103
+ this.queueController.onAiUpdate(
104
+ game,
105
+ this.productionApi,
106
+ this.actionsApi,
107
+ myPlayer,
108
+ threatCache,
109
+ (message) => this.logBotStatus(message),
110
+ );
111
+
112
+ // Mission logic every 6 ticks
113
+ if (this.gameApi.getCurrentTick() % 6 === 0) {
114
+ this.missionController.onAiUpdate(game, myPlayer, this.matchAwareness, this.squadController);
115
+ }
116
+
117
+ // Squad logic every 3 ticks
118
+ if (this.gameApi.getCurrentTick() % 3 === 0) {
119
+ this.squadController.onAiUpdate(game, this.actionsApi, myPlayer, this.matchAwareness, (message) =>
120
+ this.logBotStatus(message),
121
+ );
122
+ }
123
+ }
124
+ }
125
+
126
+ private getHumanTimestamp(game: GameApi) {
127
+ return Duration.fromMillis((game.getCurrentTick() / NATURAL_TICK_RATE) * 1000).toFormat("hh:mm:ss");
128
+ }
129
+
130
+ private logBotStatus(message: string) {
131
+ if (!this.enableLogging) {
132
+ return;
133
+ }
134
+ console.log(`[${this.getHumanTimestamp(this.gameApi)} ${this.name}] ${message}`);
135
+ }
136
+
137
+ private logDebugState(game: GameApi) {
138
+ if (!this.enableLogging) {
139
+ return;
140
+ }
141
+ const myPlayer = game.getPlayerData(this.name);
142
+ const queueState = QUEUES.reduce((prev, queueType) => {
143
+ if (this.productionApi.getQueueData(queueType).size === 0) {
144
+ return prev;
145
+ }
146
+ const paused = this.productionApi.getQueueData(queueType).status === QueueStatus.OnHold;
147
+ return (
148
+ prev +
149
+ " [" +
150
+ queueTypeToName(queueType) +
151
+ (paused ? " PAUSED" : "") +
152
+ ": " +
153
+ this.productionApi.getQueueData(queueType).items.map((item) => item.rules.name + "x" + item.quantity) +
154
+ "]"
155
+ );
156
+ }, "");
157
+ this.logBotStatus(`----- Cash: ${myPlayer.credits} ----- | Queues: ${queueState}`);
158
+ const harvesters = game.getVisibleUnits(this.name, "self", (r) => r.harvester).length;
159
+ this.logBotStatus(`Harvesters: ${harvesters}`);
160
+ this.logBotStatus(`----- End -----`);
161
+ this.missionController.logDebugOutput();
162
+ this.actionsApi.sayAll(`Cash: ${myPlayer.credits}`);
163
+ }
164
+
165
+ override onGameEvent(ev: ApiEvent) {
166
+ switch (ev.type) {
167
+ case ApiEventType.ObjectDestroy: {
168
+ // Add to the stalemate detection.
169
+ if (ev.attackerInfo?.playerName == this.name) {
170
+ this.tickOfLastAttackOrder += (this.gameApi.getCurrentTick() - this.tickOfLastAttackOrder) / 2;
171
+ }
172
+ break;
173
+ }
174
+ default:
175
+ break;
176
+ }
177
+ }
178
+ }