@supalosa/chronodivide-bot 0.1.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 (56) hide show
  1. package/.prettierrc +5 -0
  2. package/README.md +46 -0
  3. package/dist/bot/bot.js +269 -0
  4. package/dist/bot/logic/building/ArtilleryUnit.js +24 -0
  5. package/dist/bot/logic/building/antiGroundStaticDefence.js +40 -0
  6. package/dist/bot/logic/building/basicAirUnit.js +39 -0
  7. package/dist/bot/logic/building/basicBuilding.js +25 -0
  8. package/dist/bot/logic/building/basicGroundUnit.js +57 -0
  9. package/dist/bot/logic/building/building.js +77 -0
  10. package/dist/bot/logic/building/harvester.js +15 -0
  11. package/dist/bot/logic/building/massedAntiGroundUnit.js +20 -0
  12. package/dist/bot/logic/building/powerPlant.js +20 -0
  13. package/dist/bot/logic/building/queueController.js +168 -0
  14. package/dist/bot/logic/building/queues.js +19 -0
  15. package/dist/bot/logic/building/resourceCollectionBuilding.js +34 -0
  16. package/dist/bot/logic/map/map.js +57 -0
  17. package/dist/bot/logic/map/sector.js +104 -0
  18. package/dist/bot/logic/mission/basicMission.js +30 -0
  19. package/dist/bot/logic/mission/expansionMission.js +14 -0
  20. package/dist/bot/logic/mission/mission.js +2 -0
  21. package/dist/bot/logic/mission/missionController.js +47 -0
  22. package/dist/bot/logic/squad/behaviours/squadExpansion.js +18 -0
  23. package/dist/bot/logic/squad/behaviours/squadScouters.js +8 -0
  24. package/dist/bot/logic/squad/squad.js +73 -0
  25. package/dist/bot/logic/squad/squadBehaviour.js +5 -0
  26. package/dist/bot/logic/squad/squadController.js +58 -0
  27. package/dist/bot/logic/threat/threat.js +22 -0
  28. package/dist/bot/logic/threat/threatCalculator.js +72 -0
  29. package/dist/exampleBot.js +38 -0
  30. package/package.json +24 -0
  31. package/rules.ini +23126 -0
  32. package/src/bot/bot.ts +378 -0
  33. package/src/bot/logic/building/ArtilleryUnit.ts +43 -0
  34. package/src/bot/logic/building/antiGroundStaticDefence.ts +60 -0
  35. package/src/bot/logic/building/basicAirUnit.ts +68 -0
  36. package/src/bot/logic/building/basicBuilding.ts +47 -0
  37. package/src/bot/logic/building/basicGroundUnit.ts +78 -0
  38. package/src/bot/logic/building/building.ts +120 -0
  39. package/src/bot/logic/building/harvester.ts +27 -0
  40. package/src/bot/logic/building/powerPlant.ts +32 -0
  41. package/src/bot/logic/building/queueController.ts +255 -0
  42. package/src/bot/logic/building/resourceCollectionBuilding.ts +56 -0
  43. package/src/bot/logic/map/map.ts +76 -0
  44. package/src/bot/logic/map/sector.ts +130 -0
  45. package/src/bot/logic/mission/basicMission.ts +42 -0
  46. package/src/bot/logic/mission/expansionMission.ts +25 -0
  47. package/src/bot/logic/mission/mission.ts +47 -0
  48. package/src/bot/logic/mission/missionController.ts +51 -0
  49. package/src/bot/logic/squad/behaviours/squadExpansion.ts +33 -0
  50. package/src/bot/logic/squad/squad.ts +97 -0
  51. package/src/bot/logic/squad/squadBehaviour.ts +43 -0
  52. package/src/bot/logic/squad/squadController.ts +66 -0
  53. package/src/bot/logic/threat/threat.ts +15 -0
  54. package/src/bot/logic/threat/threatCalculator.ts +99 -0
  55. package/src/exampleBot.ts +44 -0
  56. package/tsconfig.json +73 -0
package/src/bot/bot.ts ADDED
@@ -0,0 +1,378 @@
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
+ }
@@ -0,0 +1,43 @@
1
+ import { GameApi, PlayerData, TechnoRules } from "@chronodivide/game-api";
2
+ import { GlobalThreat } from "../threat/threat.js";
3
+ import { AiBuildingRules, getDefaultPlacementLocation, numBuildingsOwnedOfType } from "./building.js";
4
+
5
+ export class ArtilleryUnit implements AiBuildingRules {
6
+ constructor(private basePriority: number, private baseAmount: number) {}
7
+
8
+ getPlacementLocation(
9
+ game: GameApi,
10
+ playerData: PlayerData,
11
+ technoRules: TechnoRules
12
+ ): { rx: number; ry: number } | undefined {
13
+ return undefined;
14
+ }
15
+
16
+ getPriority(
17
+ game: GameApi,
18
+ playerData: PlayerData,
19
+ technoRules: TechnoRules,
20
+ threatCache: GlobalThreat | undefined
21
+ ): number {
22
+ // If the enemy's defensive power is increasing we will start to build these.
23
+ if (threatCache) {
24
+ if (threatCache.totalDefensivePower > threatCache.totalAvailableAntiGroundFirepower) {
25
+ return (
26
+ this.basePriority *
27
+ (threatCache.totalAvailableAntiGroundFirepower / Math.max(1, threatCache.totalDefensivePower))
28
+ );
29
+ }
30
+ }
31
+ const numOwned = numBuildingsOwnedOfType(game, playerData, technoRules);
32
+ return this.basePriority * (1.0 - numOwned / this.baseAmount);
33
+ }
34
+
35
+ getMaxCount(
36
+ game: GameApi,
37
+ playerData: PlayerData,
38
+ technoRules: TechnoRules,
39
+ threatCache: GlobalThreat | undefined
40
+ ): number | null {
41
+ return null;
42
+ }
43
+ }
@@ -0,0 +1,60 @@
1
+ import { GameApi, PlayerData, Point2D, TechnoRules } from "@chronodivide/game-api";
2
+ import { getPointTowardsOtherPoint } from "../map/map.js";
3
+ import { GlobalThreat } from "../threat/threat.js";
4
+ import { AiBuildingRules, getDefaultPlacementLocation, numBuildingsOwnedOfType } from "./building.js";
5
+
6
+ export class AntiGroundStaticDefence implements AiBuildingRules {
7
+ constructor(private basePriority: number, private baseAmount: number, private strength: number) {}
8
+
9
+ getPlacementLocation(
10
+ game: GameApi,
11
+ playerData: PlayerData,
12
+ technoRules: TechnoRules
13
+ ): { rx: number; ry: number } | undefined {
14
+ // Prefer front towards enemy.
15
+ let startLocation = playerData.startLocation;
16
+ let players = game.getPlayers();
17
+ let enemyFacingLocationCandidates: Point2D[] = [];
18
+ for (let i = 0; i < players.length; ++i) {
19
+ let playerName = players[i];
20
+ if (playerName == playerData.name) {
21
+ continue;
22
+ }
23
+ let enemyPlayer = game.getPlayerData(playerName);
24
+ enemyFacingLocationCandidates.push(
25
+ getPointTowardsOtherPoint(game, startLocation, enemyPlayer.startLocation, 4, 16, 1.5)
26
+ );
27
+ }
28
+ let selectedLocation =
29
+ enemyFacingLocationCandidates[Math.floor(game.generateRandom() * enemyFacingLocationCandidates.length)];
30
+ return getDefaultPlacementLocation(game, playerData, selectedLocation, technoRules);
31
+ }
32
+
33
+ getPriority(
34
+ game: GameApi,
35
+ playerData: PlayerData,
36
+ technoRules: TechnoRules,
37
+ threatCache: GlobalThreat | undefined
38
+ ): number {
39
+ // If the enemy's ground power is increasing we should try to keep up.
40
+ if (threatCache) {
41
+ let denominator =
42
+ threatCache.totalAvailableAntiGroundFirepower + threatCache.totalDefensivePower + this.strength;
43
+ if (threatCache.totalOffensiveLandThreat > denominator * 1.1) {
44
+ return this.basePriority * (threatCache.totalOffensiveLandThreat / Math.max(1, denominator));
45
+ }
46
+ }
47
+ const strengthPerCost = (this.strength / technoRules.cost) * 1000;
48
+ const numOwned = numBuildingsOwnedOfType(game, playerData, technoRules);
49
+ return this.basePriority * (1.0 - numOwned / this.baseAmount) * strengthPerCost;
50
+ }
51
+
52
+ getMaxCount(
53
+ game: GameApi,
54
+ playerData: PlayerData,
55
+ technoRules: TechnoRules,
56
+ threatCache: GlobalThreat | undefined
57
+ ): number | null {
58
+ return null;
59
+ }
60
+ }
@@ -0,0 +1,68 @@
1
+ import { GameApi, PlayerData, TechnoRules } from "@chronodivide/game-api";
2
+ import { GlobalThreat } from "../threat/threat.js";
3
+ import { AiBuildingRules, getDefaultPlacementLocation, numBuildingsOwnedOfType } from "./building.js";
4
+
5
+ export class BasicAirUnit implements AiBuildingRules {
6
+ constructor(
7
+ private basePriority: number,
8
+ private baseAmount: number,
9
+ private antiGroundPower: number = 1, // boolean for now, but will eventually be used in weighting.
10
+ private antiAirPower: number = 0
11
+ ) {}
12
+
13
+ getPlacementLocation(
14
+ game: GameApi,
15
+ playerData: PlayerData,
16
+ technoRules: TechnoRules
17
+ ): { rx: number; ry: number } | undefined {
18
+ return undefined;
19
+ }
20
+
21
+ getPriority(
22
+ game: GameApi,
23
+ playerData: PlayerData,
24
+ technoRules: TechnoRules,
25
+ threatCache: GlobalThreat | undefined
26
+ ): number {
27
+ // If the enemy's anti-air power is low we might build more.
28
+ if (threatCache) {
29
+ let priority = 0;
30
+ if (
31
+ this.antiGroundPower > 0 &&
32
+ threatCache.totalOffensiveLandThreat > threatCache.totalAvailableAntiGroundFirepower
33
+ ) {
34
+ priority +=
35
+ this.basePriority *
36
+ (threatCache.totalOffensiveLandThreat / Math.max(1, threatCache.totalAvailableAntiGroundFirepower));
37
+ }
38
+ if (
39
+ this.antiAirPower > 0 &&
40
+ threatCache.totalOffensiveAirThreat > threatCache.totalAvailableAntiAirFirepower
41
+ ) {
42
+ priority +=
43
+ this.basePriority *
44
+ (threatCache.totalOffensiveAirThreat / Math.max(1, threatCache.totalAvailableAntiAirFirepower));
45
+ }
46
+ // sqrt so we don't build too much of one unit type.
47
+ priority += Math.min(
48
+ 1.0,
49
+ Math.max(
50
+ 1,
51
+ Math.sqrt(threatCache.totalAvailableAirPower / Math.max(1, threatCache.totalOffensiveAntiAirThreat))
52
+ )
53
+ );
54
+ return this.baseAmount * priority;
55
+ }
56
+ const numOwned = numBuildingsOwnedOfType(game, playerData, technoRules);
57
+ return this.basePriority * (1.0 - numOwned / this.baseAmount);
58
+ }
59
+
60
+ getMaxCount(
61
+ game: GameApi,
62
+ playerData: PlayerData,
63
+ technoRules: TechnoRules,
64
+ threatCache: GlobalThreat | undefined
65
+ ): number | null {
66
+ return null;
67
+ }
68
+ }
@@ -0,0 +1,47 @@
1
+ import { GameApi, PlayerData, TechnoRules } from "@chronodivide/game-api";
2
+ import { AiBuildingRules, getDefaultPlacementLocation, numBuildingsOwnedOfType } from "./building.js";
3
+ import { GlobalThreat } from "../threat/threat.js";
4
+
5
+ export class BasicBuilding implements AiBuildingRules {
6
+ constructor(
7
+ protected basePriority: number,
8
+ protected maxNeeded: number,
9
+ protected onlyBuildWhenFloatingCreditsAmount?: number
10
+ ) {}
11
+
12
+ getPlacementLocation(
13
+ game: GameApi,
14
+ playerData: PlayerData,
15
+ technoRules: TechnoRules
16
+ ): { rx: number; ry: number } | undefined {
17
+ return getDefaultPlacementLocation(game, playerData, playerData.startLocation, technoRules);
18
+ }
19
+
20
+ getPriority(
21
+ game: GameApi,
22
+ playerData: PlayerData,
23
+ technoRules: TechnoRules,
24
+ threatCache: GlobalThreat | undefined
25
+ ): number {
26
+ const numOwned = numBuildingsOwnedOfType(game, playerData, technoRules);
27
+ const calcMaxCount = this.getMaxCount(game, playerData, technoRules, threatCache);
28
+ if (numOwned >= (calcMaxCount ?? this.maxNeeded)) {
29
+ return -100;
30
+ }
31
+
32
+ if (this.onlyBuildWhenFloatingCreditsAmount && playerData.credits < this.onlyBuildWhenFloatingCreditsAmount) {
33
+ return -100;
34
+ }
35
+
36
+ return this.basePriority * (1.0 - numOwned / this.maxNeeded);
37
+ }
38
+
39
+ getMaxCount(
40
+ game: GameApi,
41
+ playerData: PlayerData,
42
+ technoRules: TechnoRules,
43
+ threatCache: GlobalThreat | undefined
44
+ ): number | null {
45
+ return this.maxNeeded;
46
+ }
47
+ }
@@ -0,0 +1,78 @@
1
+ import { GameApi, PlayerData, TechnoRules } from "@chronodivide/game-api";
2
+ import { GlobalThreat } from "../threat/threat.js";
3
+ import { AiBuildingRules, getDefaultPlacementLocation, numBuildingsOwnedOfType } from "./building.js";
4
+
5
+ export class BasicGroundUnit implements AiBuildingRules {
6
+ constructor(
7
+ protected basePriority: number,
8
+ protected baseAmount: number,
9
+ protected antiGroundPower: number = 1, // boolean for now, but will eventually be used in weighting.
10
+ protected antiAirPower: number = 0
11
+ ) {}
12
+
13
+ getPlacementLocation(
14
+ game: GameApi,
15
+ playerData: PlayerData,
16
+ technoRules: TechnoRules
17
+ ): { rx: number; ry: number } | undefined {
18
+ return undefined;
19
+ }
20
+
21
+ getPriority(
22
+ game: GameApi,
23
+ playerData: PlayerData,
24
+ technoRules: TechnoRules,
25
+ threatCache: GlobalThreat | undefined
26
+ ): number {
27
+ if (threatCache) {
28
+ let priority = 1;
29
+ if (this.antiGroundPower > 0) {
30
+ // If the enemy's power is increasing we should try to keep up.
31
+ if (threatCache.totalOffensiveLandThreat > threatCache.totalAvailableAntiGroundFirepower) {
32
+ priority +=
33
+ this.antiGroundPower *
34
+ this.basePriority *
35
+ (threatCache.totalOffensiveLandThreat /
36
+ Math.max(1, threatCache.totalAvailableAntiGroundFirepower));
37
+ } else {
38
+ // But also, if our power dwarfs the enemy, keep pressing the advantage.
39
+ priority +=
40
+ this.antiGroundPower *
41
+ this.basePriority *
42
+ Math.sqrt(
43
+ threatCache.totalAvailableAntiGroundFirepower /
44
+ Math.max(1, threatCache.totalOffensiveLandThreat + threatCache.totalDefensiveThreat)
45
+ );
46
+ }
47
+ }
48
+ if (this.antiAirPower > 0) {
49
+ if (threatCache.totalOffensiveAirThreat > threatCache.totalAvailableAntiAirFirepower) {
50
+ priority +=
51
+ this.antiAirPower *
52
+ this.basePriority *
53
+ (threatCache.totalOffensiveAirThreat / Math.max(1, threatCache.totalAvailableAntiAirFirepower));
54
+ } else {
55
+ priority +=
56
+ this.antiAirPower *
57
+ this.basePriority *
58
+ Math.sqrt(
59
+ threatCache.totalAvailableAntiAirFirepower /
60
+ Math.max(1, threatCache.totalOffensiveAirThreat + threatCache.totalDefensiveThreat)
61
+ );
62
+ }
63
+ }
64
+ return priority;
65
+ }
66
+ const numOwned = numBuildingsOwnedOfType(game, playerData, technoRules);
67
+ return this.basePriority * (1.0 - numOwned / this.baseAmount);
68
+ }
69
+
70
+ getMaxCount(
71
+ game: GameApi,
72
+ playerData: PlayerData,
73
+ technoRules: TechnoRules,
74
+ threatCache: GlobalThreat | undefined
75
+ ): number | null {
76
+ return null;
77
+ }
78
+ }