@supalosa/chronodivide-bot 0.2.0 → 0.2.2

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 (121) hide show
  1. package/.prettierrc +5 -5
  2. package/README.md +11 -3
  3. package/dist/bot/bot.js +15 -7
  4. package/dist/bot/bot.js.map +1 -0
  5. package/dist/bot/logic/awareness.js +12 -2
  6. package/dist/bot/logic/awareness.js.map +1 -0
  7. package/dist/bot/logic/awarenessImpl.js +132 -0
  8. package/dist/bot/logic/awarenessImpl.js.map +1 -0
  9. package/dist/bot/logic/building/ArtilleryUnit.js +1 -0
  10. package/dist/bot/logic/building/ArtilleryUnit.js.map +1 -0
  11. package/dist/bot/logic/building/antiGroundStaticDefence.js +1 -0
  12. package/dist/bot/logic/building/antiGroundStaticDefence.js.map +1 -0
  13. package/dist/bot/logic/building/basicAirUnit.js +1 -0
  14. package/dist/bot/logic/building/basicAirUnit.js.map +1 -0
  15. package/dist/bot/logic/building/basicBuilding.js +1 -0
  16. package/dist/bot/logic/building/basicBuilding.js.map +1 -0
  17. package/dist/bot/logic/building/basicGroundUnit.js +1 -0
  18. package/dist/bot/logic/building/basicGroundUnit.js.map +1 -0
  19. package/dist/bot/logic/building/building.js +57 -11
  20. package/dist/bot/logic/building/building.js.map +1 -0
  21. package/dist/bot/logic/building/harvester.js +1 -0
  22. package/dist/bot/logic/building/harvester.js.map +1 -0
  23. package/dist/bot/logic/building/powerPlant.js +1 -0
  24. package/dist/bot/logic/building/powerPlant.js.map +1 -0
  25. package/dist/bot/logic/building/queueController.js +1 -0
  26. package/dist/bot/logic/building/queueController.js.map +1 -0
  27. package/dist/bot/logic/building/resourceCollectionBuilding.js +1 -0
  28. package/dist/bot/logic/building/resourceCollectionBuilding.js.map +1 -0
  29. package/dist/bot/logic/common/scout.js +100 -0
  30. package/dist/bot/logic/common/scout.js.map +1 -0
  31. package/dist/bot/logic/common/utils.js +2 -0
  32. package/dist/bot/logic/common/utils.js.map +1 -0
  33. package/dist/bot/logic/map/map.js +9 -25
  34. package/dist/bot/logic/map/map.js.map +1 -0
  35. package/dist/bot/logic/map/sector.js +33 -1
  36. package/dist/bot/logic/map/sector.js.map +1 -0
  37. package/dist/bot/logic/mission/mission.js +3 -1
  38. package/dist/bot/logic/mission/mission.js.map +1 -0
  39. package/dist/bot/logic/mission/missionController.js +5 -4
  40. package/dist/bot/logic/mission/missionController.js.map +1 -0
  41. package/dist/bot/logic/mission/missionFactories.js +1 -0
  42. package/dist/bot/logic/mission/missionFactories.js.map +1 -0
  43. package/dist/bot/logic/mission/missions/attackMission.js +7 -8
  44. package/dist/bot/logic/mission/missions/attackMission.js.map +1 -0
  45. package/dist/bot/logic/mission/missions/defenceMission.js +12 -7
  46. package/dist/bot/logic/mission/missions/defenceMission.js.map +1 -0
  47. package/dist/bot/logic/mission/missions/expansionMission.js +5 -4
  48. package/dist/bot/logic/mission/missions/expansionMission.js.map +1 -0
  49. package/dist/bot/logic/mission/missions/oneTimeMission.js +3 -2
  50. package/dist/bot/logic/mission/missions/oneTimeMission.js.map +1 -0
  51. package/dist/bot/logic/mission/missions/retreatMission.js +3 -2
  52. package/dist/bot/logic/mission/missions/retreatMission.js.map +1 -0
  53. package/dist/bot/logic/mission/missions/scoutingMission.js +8 -9
  54. package/dist/bot/logic/mission/missions/scoutingMission.js.map +1 -0
  55. package/dist/bot/logic/squad/behaviours/attackSquad.js +63 -56
  56. package/dist/bot/logic/squad/behaviours/combatSquad.js +6 -3
  57. package/dist/bot/logic/squad/behaviours/combatSquad.js.map +1 -0
  58. package/dist/bot/logic/squad/behaviours/common.js +7 -4
  59. package/dist/bot/logic/squad/behaviours/common.js.map +1 -0
  60. package/dist/bot/logic/squad/behaviours/defenceSquad.js +15 -2
  61. package/dist/bot/logic/squad/behaviours/expansionSquad.js +1 -0
  62. package/dist/bot/logic/squad/behaviours/expansionSquad.js.map +1 -0
  63. package/dist/bot/logic/squad/behaviours/retreatSquad.js +6 -10
  64. package/dist/bot/logic/squad/behaviours/retreatSquad.js.map +1 -0
  65. package/dist/bot/logic/squad/behaviours/scoutingSquad.js +66 -18
  66. package/dist/bot/logic/squad/behaviours/scoutingSquad.js.map +1 -0
  67. package/dist/bot/logic/squad/squad.js +3 -3
  68. package/dist/bot/logic/squad/squad.js.map +1 -0
  69. package/dist/bot/logic/squad/squadBehaviour.js +1 -0
  70. package/dist/bot/logic/squad/squadBehaviour.js.map +1 -0
  71. package/dist/bot/logic/squad/squadBehaviours.js +1 -0
  72. package/dist/bot/logic/squad/squadBehaviours.js.map +1 -0
  73. package/dist/bot/logic/squad/squadController.js +73 -23
  74. package/dist/bot/logic/squad/squadController.js.map +1 -0
  75. package/dist/bot/logic/threat/threat.js +1 -0
  76. package/dist/bot/logic/threat/threat.js.map +1 -0
  77. package/dist/bot/logic/threat/threatCalculator.js +1 -0
  78. package/dist/bot/logic/threat/threatCalculator.js.map +1 -0
  79. package/dist/exampleBot.js +24 -7
  80. package/dist/exampleBot.js.map +1 -0
  81. package/package.json +9 -6
  82. package/src/bot/bot.ts +17 -11
  83. package/src/bot/logic/awareness.ts +22 -5
  84. package/src/bot/logic/building/ArtilleryUnit.ts +43 -43
  85. package/src/bot/logic/building/antiGroundStaticDefence.ts +60 -60
  86. package/src/bot/logic/building/basicAirUnit.ts +68 -68
  87. package/src/bot/logic/building/basicBuilding.ts +47 -47
  88. package/src/bot/logic/building/building.ts +72 -12
  89. package/src/bot/logic/building/powerPlant.ts +32 -32
  90. package/src/bot/logic/building/resourceCollectionBuilding.ts +56 -56
  91. package/src/bot/logic/common/scout.ts +127 -1
  92. package/src/bot/logic/common/utils.ts +1 -0
  93. package/src/bot/logic/map/map.ts +70 -84
  94. package/src/bot/logic/map/sector.ts +46 -4
  95. package/src/bot/logic/mission/mission.ts +2 -2
  96. package/src/bot/logic/mission/missionController.ts +7 -6
  97. package/src/bot/logic/mission/missionFactories.ts +3 -0
  98. package/src/bot/logic/mission/missions/attackMission.ts +19 -13
  99. package/src/bot/logic/mission/missions/defenceMission.ts +35 -15
  100. package/src/bot/logic/mission/missions/expansionMission.ts +6 -4
  101. package/src/bot/logic/mission/missions/oneTimeMission.ts +3 -2
  102. package/src/bot/logic/mission/missions/retreatMission.ts +3 -2
  103. package/src/bot/logic/mission/missions/scoutingMission.ts +9 -6
  104. package/src/bot/logic/squad/behaviours/combatSquad.ts +6 -2
  105. package/src/bot/logic/squad/behaviours/common.ts +6 -4
  106. package/src/bot/logic/squad/behaviours/retreatSquad.ts +10 -12
  107. package/src/bot/logic/squad/behaviours/scoutingSquad.ts +81 -23
  108. package/src/bot/logic/squad/squad.ts +3 -2
  109. package/src/bot/logic/squad/squadBehaviour.ts +3 -1
  110. package/src/bot/logic/squad/squadController.ts +136 -69
  111. package/src/bot/logic/threat/threat.ts +15 -15
  112. package/src/bot/logic/threat/threatCalculator.ts +99 -99
  113. package/src/exampleBot.ts +25 -6
  114. package/tsconfig.json +73 -73
  115. package/dist/bot/logic/building/massedAntiGroundUnit.js +0 -20
  116. package/dist/bot/logic/building/queues.js +0 -19
  117. package/dist/bot/logic/knowledge.js +0 -1
  118. package/dist/bot/logic/mission/basicMission.js +0 -26
  119. package/dist/bot/logic/mission/expansionMission.js +0 -32
  120. package/dist/bot/logic/squad/behaviours/squadExpansion.js +0 -31
  121. package/dist/bot/logic/squad/behaviours/squadScouters.js +0 -8
@@ -1,4 +1,7 @@
1
- import { GameApi, PlayerData } from "@chronodivide/game-api";
1
+ import { GameApi, PlayerData, Point2D } from "@chronodivide/game-api";
2
+ import { Sector, SectorCache } from "../map/sector";
3
+ import { DebugLogger } from "./utils";
4
+ import { PriorityQueue } from "@datastructures-js/priority-queue";
2
5
 
3
6
  export const getUnseenStartingLocations = (gameApi: GameApi, playerData: PlayerData) => {
4
7
  const unseenStartingLocations = gameApi.mapApi.getStartingLocations().filter((startingLocation) => {
@@ -10,3 +13,126 @@ export const getUnseenStartingLocations = (gameApi: GameApi, playerData: PlayerD
10
13
  });
11
14
  return unseenStartingLocations;
12
15
  };
16
+
17
+ class PrioritisedScoutTarget {
18
+ private _targetPoint2D?: Point2D;
19
+ private _targetSector?: Sector;
20
+ private _priority: number;
21
+
22
+ constructor(priority: number, target: Point2D | Sector) {
23
+ if (target.hasOwnProperty("x") && target.hasOwnProperty("y")) {
24
+ this._targetPoint2D = target as Point2D;
25
+ } else if (target.hasOwnProperty("sectorStartPoint")) {
26
+ this._targetSector = target as Sector;
27
+ } else {
28
+ throw new TypeError(`invalid object passed as target: ${target}`);
29
+ }
30
+ this._priority = priority;
31
+ }
32
+
33
+ get priority() {
34
+ return this._priority;
35
+ }
36
+
37
+ asPoint2D() {
38
+ return this._targetPoint2D ?? this._targetSector?.sectorStartPoint ?? null;
39
+ }
40
+
41
+ get targetSector() {
42
+ return this._targetSector;
43
+ }
44
+ }
45
+
46
+ const ENEMY_SPAWN_POINT_PRIORITY = 100;
47
+
48
+ // Amount of sectors around the starting sector to try to scout.
49
+ const NEARBY_SECTOR_RADIUS = 2;
50
+ const NEARBY_SECTOR_BASE_PRIORITY = 1000;
51
+
52
+ export class ScoutingManager {
53
+ private scoutingQueue: PriorityQueue<PrioritisedScoutTarget>;
54
+
55
+ constructor(private logger: DebugLogger) {
56
+ // Order by descending priority.
57
+ this.scoutingQueue = new PriorityQueue((a: PrioritisedScoutTarget, b: PrioritisedScoutTarget) => b.priority - a.priority);
58
+ }
59
+
60
+ onGameStart(gameApi: GameApi, playerData: PlayerData, sectorCache: SectorCache) {
61
+ // Queue hostile starting locations with high priority.
62
+ gameApi.mapApi
63
+ .getStartingLocations()
64
+ .filter((startingLocation) => {
65
+ if (startingLocation == playerData.startLocation) {
66
+ return false;
67
+ }
68
+ let tile = gameApi.mapApi.getTile(startingLocation.x, startingLocation.y);
69
+ return tile ? !gameApi.mapApi.isVisibleTile(tile, playerData.name) : false;
70
+ })
71
+ .map((tile) => new PrioritisedScoutTarget(ENEMY_SPAWN_POINT_PRIORITY, tile))
72
+ .forEach((target) => {
73
+ this.logger(`Adding ${target.asPoint2D()?.x},${target.asPoint2D()?.y} to initial scouting queue`);
74
+ this.scoutingQueue.enqueue(target);
75
+ });
76
+
77
+ // Queue nearby sectors.
78
+ const { x: startX, y: startY } = playerData.startLocation;
79
+ const { x: sectorsX, y: sectorsY } = sectorCache.getSectorBounds();
80
+ const startingSector = sectorCache.getSectorCoordinatesForWorldPosition(startX, startY);
81
+
82
+ if (!startingSector) {
83
+ return;
84
+ }
85
+
86
+ for (
87
+ let x: number = Math.max(0, startingSector.sectorX - NEARBY_SECTOR_RADIUS);
88
+ x <= Math.min(sectorsX, startingSector.sectorX + NEARBY_SECTOR_RADIUS);
89
+ ++x
90
+ ) {
91
+ for (
92
+ let y: number = Math.max(0, startingSector.sectorY - NEARBY_SECTOR_RADIUS);
93
+ y <= Math.min(sectorsY, startingSector.sectorY + NEARBY_SECTOR_RADIUS);
94
+ ++y
95
+ ) {
96
+ if (x === startingSector?.sectorX && y === startingSector?.sectorY) {
97
+ continue;
98
+ }
99
+ // Make it scout closer sectors first.
100
+ const distanceFactor = Math.pow(x - startingSector.sectorX, 2) + Math.pow(y - startingSector.sectorY, 2);
101
+ const sector = sectorCache.getSector(x, y);
102
+ if (sector) {
103
+ const maybeTarget = new PrioritisedScoutTarget(NEARBY_SECTOR_BASE_PRIORITY - distanceFactor, sector);
104
+ const maybePoint = maybeTarget.asPoint2D();
105
+ if (maybePoint && gameApi.mapApi.getTile(maybePoint.x, maybePoint.y)) {
106
+ this.scoutingQueue.enqueue(maybeTarget);
107
+ }
108
+ }
109
+ }
110
+ }
111
+ }
112
+
113
+ onAiUpdate(gameApi: GameApi, playerData: PlayerData) {
114
+ const currentHead = this.scoutingQueue.front();
115
+ if (!currentHead) {
116
+ return;
117
+ }
118
+ const head = currentHead.asPoint2D();
119
+ if (!head) {
120
+ this.scoutingQueue.dequeue();
121
+ return;
122
+ }
123
+ const { x, y } = head;
124
+ const tile = gameApi.mapApi.getTile(x, y);
125
+ if (tile && gameApi.mapApi.isVisibleTile(tile, playerData.name)) {
126
+ this.logger(`head point is visible, dequeueing`);
127
+ this.scoutingQueue.dequeue();
128
+ }
129
+ }
130
+
131
+ getNewScoutTarget() {
132
+ return this.scoutingQueue.dequeue();
133
+ }
134
+
135
+ hasScoutTargets() {
136
+ return !this.scoutingQueue.isEmpty();
137
+ }
138
+ }
@@ -0,0 +1 @@
1
+ export type DebugLogger = (message: string, sayInGame?: boolean) => void;
@@ -1,84 +1,70 @@
1
- import { GameApi, MapApi, PlayerData, Point2D, UnitData } from "@chronodivide/game-api";
2
-
3
- // Expensive one-time call to determine the size of the map.
4
- // The result is a point just outside the bounds of the map.
5
- export function determineMapBounds(mapApi: MapApi): Point2D {
6
- // TODO Binary Search this.
7
- // Start from the last spawn positions to save time.
8
- let maxX: number = 0;
9
- let maxY: number = 0;
10
- mapApi.getStartingLocations().forEach((point) => {
11
- if (point.x > maxX) {
12
- maxX = point.x;
13
- }
14
- if (point.y > maxY) {
15
- maxY = point.y;
16
- }
17
- });
18
- // Expand outwards until we find the bounds.
19
- for (let testX = maxX; testX < 10000; ++testX) {
20
- if (mapApi.getTile(testX, 0) == undefined) {
21
- maxX = testX;
22
- break;
23
- }
24
- }
25
- for (let testY = maxY; testY < 10000; ++testY) {
26
- if (mapApi.getTile(testY, 0) == undefined) {
27
- maxY = testY;
28
- break;
29
- }
30
- }
31
- return { x: maxX, y: maxY };
32
- }
33
-
34
- export function calculateAreaVisibility(
35
- mapApi: MapApi,
36
- playerData: PlayerData,
37
- startPoint: Point2D,
38
- endPoint: Point2D
39
- ): { visibleTiles: number; validTiles: number } {
40
- let validTiles: number = 0,
41
- visibleTiles: number = 0;
42
- for (let xx = startPoint.x; xx < endPoint.x; ++xx) {
43
- for (let yy = startPoint.y; yy < endPoint.y; ++yy) {
44
- let tile = mapApi.getTile(xx, yy);
45
- if (tile) {
46
- ++validTiles;
47
- if (mapApi.isVisibleTile(tile, playerData.name)) {
48
- ++visibleTiles;
49
- }
50
- }
51
- }
52
- }
53
- let result = { visibleTiles, validTiles };
54
- return result;
55
- }
56
-
57
- export function getPointTowardsOtherPoint(
58
- gameApi: GameApi,
59
- startLocation: Point2D,
60
- endLocation: Point2D,
61
- minRadius: number,
62
- maxRadius: number,
63
- randomAngle: number
64
- ): Point2D {
65
- let radius = minRadius + Math.round(gameApi.generateRandom() * (maxRadius - minRadius));
66
- let directionToSpawn = Math.atan2(endLocation.y - startLocation.y, endLocation.x - startLocation.x);
67
- let randomisedDirection =
68
- directionToSpawn - (randomAngle * (Math.PI / 12) + 2 * randomAngle * gameApi.generateRandom() * (Math.PI / 12));
69
- let candidatePointX = Math.round(startLocation.x + Math.cos(randomisedDirection) * radius);
70
- let candidatePointY = Math.round(startLocation.y + Math.sin(randomisedDirection) * radius);
71
- return { x: candidatePointX, y: candidatePointY };
72
- }
73
-
74
- export function getDistanceBetweenPoints(startLocation: Point2D, endLocation: Point2D): number {
75
- return Math.sqrt((startLocation.x - endLocation.x) ** 2 + (startLocation.y - endLocation.y) ** 2);
76
- }
77
-
78
- export function getDistanceBetweenUnits(unit1: UnitData, unit2: UnitData): number {
79
- return getDistanceBetweenPoints({ x: unit1.tile.rx, y: unit1.tile.ry }, { x: unit2.tile.rx, y: unit2.tile.ry });
80
- }
81
-
82
- export function getDistanceBetween(unit: UnitData, point: Point2D): number {
83
- return getDistanceBetweenPoints({ x: unit.tile.rx, y: unit.tile.ry }, point);
84
- }
1
+ import { GameApi, MapApi, PlayerData, Point2D, Tile, UnitData } from "@chronodivide/game-api";
2
+ import _ from "lodash";
3
+
4
+ const MAX_WIDTH_AND_HEIGHT = 500;
5
+
6
+ // Expensive one-time call to determine the size of the map.
7
+ // The result is a point just outside the bounds of the map.
8
+ export function determineMapBounds(mapApi: MapApi): Point2D {
9
+ // Probably want to ask for an API change to get this.
10
+ // Note that the maps is not always a rectangle!
11
+ const zeroTile = { rx: 0, ry: 0 } as Tile;
12
+ const allTiles = mapApi.getTilesInRect(zeroTile, { width: MAX_WIDTH_AND_HEIGHT, height: MAX_WIDTH_AND_HEIGHT });
13
+
14
+ const maxX = _.maxBy(allTiles, (tile) => tile.rx)?.rx!;
15
+ const maxY = _.maxBy(allTiles, (tile) => tile.ry)?.ry!;
16
+
17
+ return { x: maxX, y: maxY };
18
+ }
19
+
20
+ export function calculateAreaVisibility(
21
+ mapApi: MapApi,
22
+ playerData: PlayerData,
23
+ startPoint: Point2D,
24
+ endPoint: Point2D,
25
+ ): { visibleTiles: number; validTiles: number } {
26
+ let validTiles: number = 0,
27
+ visibleTiles: number = 0;
28
+ for (let xx = startPoint.x; xx < endPoint.x; ++xx) {
29
+ for (let yy = startPoint.y; yy < endPoint.y; ++yy) {
30
+ let tile = mapApi.getTile(xx, yy);
31
+ if (tile) {
32
+ ++validTiles;
33
+ if (mapApi.isVisibleTile(tile, playerData.name)) {
34
+ ++visibleTiles;
35
+ }
36
+ }
37
+ }
38
+ }
39
+ let result = { visibleTiles, validTiles };
40
+ return result;
41
+ }
42
+
43
+ export function getPointTowardsOtherPoint(
44
+ gameApi: GameApi,
45
+ startLocation: Point2D,
46
+ endLocation: Point2D,
47
+ minRadius: number,
48
+ maxRadius: number,
49
+ randomAngle: number,
50
+ ): Point2D {
51
+ let radius = minRadius + Math.round(gameApi.generateRandom() * (maxRadius - minRadius));
52
+ let directionToSpawn = Math.atan2(endLocation.y - startLocation.y, endLocation.x - startLocation.x);
53
+ let randomisedDirection =
54
+ directionToSpawn - (randomAngle * (Math.PI / 12) + 2 * randomAngle * gameApi.generateRandom() * (Math.PI / 12));
55
+ let candidatePointX = Math.round(startLocation.x + Math.cos(randomisedDirection) * radius);
56
+ let candidatePointY = Math.round(startLocation.y + Math.sin(randomisedDirection) * radius);
57
+ return { x: candidatePointX, y: candidatePointY };
58
+ }
59
+
60
+ export function getDistanceBetweenPoints(startLocation: Point2D, endLocation: Point2D): number {
61
+ return Math.sqrt((startLocation.x - endLocation.x) ** 2 + (startLocation.y - endLocation.y) ** 2);
62
+ }
63
+
64
+ export function getDistanceBetweenUnits(unit1: UnitData, unit2: UnitData): number {
65
+ return getDistanceBetweenPoints({ x: unit1.tile.rx, y: unit1.tile.ry }, { x: unit2.tile.rx, y: unit2.tile.ry });
66
+ }
67
+
68
+ export function getDistanceBetween(unit: UnitData, point: Point2D): number {
69
+ return getDistanceBetweenPoints({ x: unit.tile.rx, y: unit.tile.ry }, point);
70
+ }
@@ -6,12 +6,36 @@ import { calculateAreaVisibility } from "./map.js";
6
6
  export const SECTOR_SIZE = 8;
7
7
 
8
8
  export class Sector {
9
+ // How many times we've attempted to enter the sector.
10
+ private sectorExploreAttempts: number;
11
+ private sectorLastExploredAt: number | undefined;
12
+
9
13
  constructor(
10
14
  public sectorStartPoint: Point2D,
11
15
  public sectorStartTile: Tile | undefined,
12
16
  public sectorVisibilityPct: number | undefined,
13
- public sectorVisibilityLastCheckTick: number | undefined
14
- ) {}
17
+ public sectorVisibilityLastCheckTick: number | undefined,
18
+ ) {
19
+ this.sectorExploreAttempts = 0;
20
+ }
21
+
22
+ public onExploreAttempted(currentTick: number) {
23
+ this.sectorExploreAttempts++;
24
+ this.sectorLastExploredAt = currentTick;
25
+ }
26
+
27
+ // Whether we should attempt to explore this sector, given the cooldown and limit of attempts.
28
+ public shouldAttemptExploration(currentTick: number, cooldown: number, limit: number) {
29
+ if (limit >= this.sectorExploreAttempts) {
30
+ return false;
31
+ }
32
+
33
+ if (this.sectorLastExploredAt && currentTick < this.sectorLastExploredAt + cooldown) {
34
+ return false;
35
+ }
36
+
37
+ return true;
38
+ }
15
39
  }
16
40
 
17
41
  export class SectorCache {
@@ -34,7 +58,7 @@ export class SectorCache {
34
58
  { x: xx * SECTOR_SIZE, y: yy * SECTOR_SIZE },
35
59
  mapApi.getTile(xx * SECTOR_SIZE, yy * SECTOR_SIZE),
36
60
  undefined,
37
- undefined
61
+ undefined,
38
62
  );
39
63
  }
40
64
  }
@@ -127,10 +151,28 @@ export class SectorCache {
127
151
  return this.sectors[sectorX][sectorY];
128
152
  }
129
153
 
130
- public getSectorForWorldPosition(x: number, y: number): Sector | undefined {
154
+ public getSectorBounds(): Point2D {
155
+ return {
156
+ x: this.sectorsX,
157
+ y: this.sectorsY,
158
+ }
159
+ }
160
+
161
+ public getSectorCoordinatesForWorldPosition(x: number, y: number) {
131
162
  if (x < 0 || x >= this.mapBounds.x || y < 0 || y >= this.mapBounds.y) {
132
163
  return undefined;
133
164
  }
165
+ return {
166
+ sectorX: Math.floor(x / SECTOR_SIZE),
167
+ sectorY: Math.floor(y / SECTOR_SIZE)
168
+ }
169
+ }
170
+
171
+ public getSectorForWorldPosition(x: number, y: number): Sector | undefined {
172
+ const sectorCoordinates = this.getSectorCoordinatesForWorldPosition(x, y);
173
+ if (!sectorCoordinates) {
174
+ return undefined;
175
+ }
134
176
  return this.sectors[Math.floor(x / SECTOR_SIZE)][Math.floor(y / SECTOR_SIZE)];
135
177
  }
136
178
  }
@@ -1,7 +1,7 @@
1
1
  import { GameApi, PlayerData } from "@chronodivide/game-api";
2
2
  import { Squad } from "../squad/squad.js";
3
- import { GlobalThreat } from "../threat/threat.js";
4
3
  import { MatchAwareness } from "../awareness.js";
4
+ import { DebugLogger } from "../common/utils.js";
5
5
 
6
6
  // AI starts Missions based on heuristics, which have one or more squads.
7
7
  // Missions can create squads (but squads will disband themselves).
@@ -11,7 +11,7 @@ export abstract class Mission<FailureReasons = undefined> {
11
11
 
12
12
  private onFinish: (reason: FailureReasons, squad: Squad | null) => void = () => {};
13
13
 
14
- constructor(private uniqueName: string, private priority: number = 1) {}
14
+ constructor(private uniqueName: string, private priority: number, protected logger: DebugLogger) {}
15
15
 
16
16
  abstract onAiUpdate(gameApi: GameApi, playerData: PlayerData, matchAwareness: MatchAwareness): MissionAction;
17
17
 
@@ -1,7 +1,6 @@
1
1
  // Meta-controller for forming and controlling squads.
2
2
 
3
3
  import { GameApi, PlayerData } from "@chronodivide/game-api";
4
- import { GlobalThreat } from "../threat/threat.js";
5
4
  import { Mission, MissionAction, MissionActionDisband, MissionActionRegisterSquad } from "./mission.js";
6
5
  import { SquadController } from "../squad/squadController.js";
7
6
  import { MatchAwareness } from "../awareness.js";
@@ -13,7 +12,7 @@ export class MissionController {
13
12
 
14
13
  private forceDisbandedMissions: string[] = [];
15
14
 
16
- constructor(private logger: (message: string) => void) {
15
+ constructor(private logger: (message: string, sayInGame?: boolean) => void) {
17
16
  this.missionFactories = createMissionFactories();
18
17
  }
19
18
 
@@ -48,11 +47,13 @@ export class MissionController {
48
47
  this.missions
49
48
  .filter((missions) => disbandedMissions.has(missions.getUniqueName()))
50
49
  .forEach((disbandedMission) => {
51
- this.logger(`mission disbanded: ${disbandedMission.getUniqueName()}`);
52
50
  const reason = disbandedMissions.get(disbandedMission.getUniqueName());
51
+ this.logger(
52
+ `mission disbanded: ${disbandedMission.getUniqueName()}, reason: ${reason}, hasSquad: ${!!disbandedMission.getSquad}`,
53
+ );
53
54
  disbandedMissionsArray.push({ mission: disbandedMission, reason });
54
- disbandedMission.getSquad()?.setMission(null);
55
55
  disbandedMission.endMission(disbandedMissions.get(disbandedMission.getUniqueName()));
56
+ disbandedMission.getSquad()?.setMission(null);
56
57
  });
57
58
  this.missions = this.missions.filter((missions) => !disbandedMissions.has(missions.getUniqueName()));
58
59
 
@@ -68,9 +69,9 @@ export class MissionController {
68
69
 
69
70
  // Create dynamic missions.
70
71
  this.missionFactories.forEach((missionFactory) => {
71
- missionFactory.maybeCreateMissions(gameApi, playerData, matchAwareness, this);
72
+ missionFactory.maybeCreateMissions(gameApi, playerData, matchAwareness, this, this.logger);
72
73
  disbandedMissionsArray.forEach(({ reason, mission }) => {
73
- missionFactory.onMissionFailed(gameApi, playerData, matchAwareness, mission, reason, this);
74
+ missionFactory.onMissionFailed(gameApi, playerData, matchAwareness, mission, reason, this, this.logger);
74
75
  });
75
76
  });
76
77
  }
@@ -6,6 +6,7 @@ import { ScoutingMissionFactory } from "./missions/scoutingMission.js";
6
6
  import { AttackMissionFactory } from "./missions/attackMission.js";
7
7
  import { MissionController } from "./missionController.js";
8
8
  import { DefenceMissionFactory } from "./missions/defenceMission.js";
9
+ import { DebugLogger } from "../common/utils.js";
9
10
 
10
11
  export interface MissionFactory {
11
12
  getName(): string;
@@ -23,6 +24,7 @@ export interface MissionFactory {
23
24
  playerData: PlayerData,
24
25
  matchAwareness: MatchAwareness,
25
26
  missionController: MissionController,
27
+ logger: DebugLogger
26
28
  ): void;
27
29
 
28
30
  /**
@@ -35,6 +37,7 @@ export interface MissionFactory {
35
37
  failedMission: Mission,
36
38
  failureReason: any,
37
39
  missionController: MissionController,
40
+ logger: DebugLogger
38
41
  ): void;
39
42
  }
40
43
 
@@ -11,6 +11,7 @@ import { MissionController } from "../missionController.js";
11
11
  import { match } from "assert";
12
12
  import { RetreatMission } from "./retreatMission.js";
13
13
  import _ from "lodash";
14
+ import { DebugLogger } from "../../common/utils.js";
14
15
 
15
16
  export enum AttackFailReason {
16
17
  NoTargets = 0,
@@ -31,8 +32,9 @@ export class AttackMission extends Mission<AttackFailReason> {
31
32
  private rallyArea: Point2D,
32
33
  private attackArea: Point2D,
33
34
  private radius: number,
35
+ logger: DebugLogger
34
36
  ) {
35
- super(uniqueName, priority);
37
+ super(uniqueName, priority, logger);
36
38
  }
37
39
 
38
40
  onAiUpdate(gameApi: GameApi, playerData: PlayerData, matchAwareness: MatchAwareness): MissionAction {
@@ -104,6 +106,7 @@ export class AttackMissionFactory implements MissionFactory {
104
106
  playerData: PlayerData,
105
107
  matchAwareness: MatchAwareness,
106
108
  missionController: MissionController,
109
+ logger: DebugLogger
107
110
  ): void {
108
111
  if (!matchAwareness.shouldAttack()) {
109
112
  return;
@@ -124,18 +127,21 @@ export class AttackMissionFactory implements MissionFactory {
124
127
  // TODO: not using a fixed value here. But performance slows to a crawl when this is unique.
125
128
  const squadName = "globalAttack";
126
129
 
127
- const tryAttack = missionController
128
- .addMission(new AttackMission(squadName, 100, matchAwareness.getMainRallyPoint(), attackArea, attackRadius))
129
- ?.then((reason, squad) => {
130
- missionController.addMission(
131
- new RetreatMission(
132
- "retreat-from-" + squadName + gameApi.getCurrentTick(),
133
- 100,
134
- matchAwareness.getMainRallyPoint(),
135
- squad?.getUnitIds() ?? [],
136
- ),
137
- );
138
- });
130
+ const tryAttack = missionController.addMission(
131
+ new AttackMission(squadName, 100, matchAwareness.getMainRallyPoint(), attackArea, attackRadius, logger).then(
132
+ (reason, squad) => {
133
+ missionController.addMission(
134
+ new RetreatMission(
135
+ "retreat-from-" + squadName + gameApi.getCurrentTick(),
136
+ 100,
137
+ matchAwareness.getMainRallyPoint(),
138
+ squad?.getUnitIds() ?? [],
139
+ logger,
140
+ ),
141
+ );
142
+ },
143
+ ),
144
+ );
139
145
  if (tryAttack) {
140
146
  this.lastAttackAt = gameApi.getCurrentTick();
141
147
  }
@@ -6,6 +6,7 @@ import { MissionFactory } from "../missionFactories.js";
6
6
  import { Squad } from "../../squad/squad.js";
7
7
  import { CombatSquad } from "../../squad/behaviours/combatSquad.js";
8
8
  import { RetreatMission } from "./retreatMission.js";
9
+ import { DebugLogger } from "../../common/utils.js";
9
10
 
10
11
  export enum DefenceFailReason {
11
12
  NoTargets,
@@ -22,8 +23,9 @@ export class DefenceMission extends Mission<DefenceFailReason> {
22
23
  priority: number,
23
24
  private defenceArea: Point2D,
24
25
  private radius: number,
26
+ logger: DebugLogger,
25
27
  ) {
26
- super(uniqueName, priority);
28
+ super(uniqueName, priority, logger);
27
29
  }
28
30
 
29
31
  onAiUpdate(gameApi: GameApi, playerData: PlayerData, matchAwareness: MatchAwareness): MissionAction {
@@ -35,8 +37,15 @@ export class DefenceMission extends Mission<DefenceFailReason> {
35
37
  const foundTargets = matchAwareness.getHostilesNearPoint2d(this.defenceArea, this.radius);
36
38
 
37
39
  if (foundTargets.length === 0) {
40
+ this.logger(`(Defence Mission ${this.getUniqueName()}): No targets found, disbanding.`);
38
41
  return disbandMission(DefenceFailReason.NoTargets);
39
42
  } else {
43
+ const targetUnit = gameApi.getUnitData(foundTargets[0].unitId);
44
+ this.logger(
45
+ `(Defence Mission ${this.getUniqueName()}): Focused on target ${targetUnit?.name} (${
46
+ foundTargets.length
47
+ } found in area ${this.radius})`,
48
+ );
40
49
  this.combatSquad?.setAttackArea({ x: foundTargets[0].x, y: foundTargets[0].y });
41
50
  }
42
51
  }
@@ -47,9 +56,9 @@ export class DefenceMission extends Mission<DefenceFailReason> {
47
56
  const DEFENCE_CHECK_TICKS = 30;
48
57
 
49
58
  // Starting radius around the player's base to trigger defense.
50
- const DEFENCE_STARTING_RADIUS = 20;
59
+ const DEFENCE_STARTING_RADIUS = 10;
51
60
  // Every game tick, we increase the defendable area by this amount.
52
- const DEFENCE_RADIUS_INCREASE_PER_GAME_TICK = 0.005;
61
+ const DEFENCE_RADIUS_INCREASE_PER_GAME_TICK = 0.001;
53
62
 
54
63
  export class DefenceMissionFactory implements MissionFactory {
55
64
  private lastDefenceCheckAt = 0;
@@ -65,6 +74,7 @@ export class DefenceMissionFactory implements MissionFactory {
65
74
  playerData: PlayerData,
66
75
  matchAwareness: MatchAwareness,
67
76
  missionController: MissionController,
77
+ logger: DebugLogger,
68
78
  ): void {
69
79
  if (gameApi.getCurrentTick() < this.lastDefenceCheckAt + DEFENCE_CHECK_TICKS) {
70
80
  return;
@@ -76,19 +86,29 @@ export class DefenceMissionFactory implements MissionFactory {
76
86
  const enemiesNearSpawn = matchAwareness.getHostilesNearPoint2d(playerData.startLocation, defendableRadius);
77
87
 
78
88
  if (enemiesNearSpawn.length > 0) {
89
+ logger(
90
+ `Starting defence mission, ${
91
+ enemiesNearSpawn.length
92
+ } found in radius ${defendableRadius} (tick ${gameApi.getCurrentTick()})`,
93
+ );
79
94
  missionController.addMission(
80
- new DefenceMission("globalDefence", 1000, playerData.startLocation, defendableRadius * 1.2)?.then(
81
- (reason, squad) => {
82
- missionController.addMission(
83
- new RetreatMission(
84
- "retreat-from-globalDefence" + gameApi.getCurrentTick(),
85
- 100,
86
- matchAwareness.getMainRallyPoint(),
87
- squad?.getUnitIds() ?? [],
88
- ),
89
- );
90
- },
91
- ),
95
+ new DefenceMission(
96
+ "globalDefence",
97
+ 1000,
98
+ playerData.startLocation,
99
+ defendableRadius * 1.2,
100
+ logger,
101
+ ).then((reason, squad) => {
102
+ missionController.addMission(
103
+ new RetreatMission(
104
+ "retreat-from-globalDefence" + gameApi.getCurrentTick(),
105
+ 100,
106
+ matchAwareness.getMainRallyPoint(),
107
+ squad?.getUnitIds() ?? [],
108
+ logger,
109
+ ),
110
+ );
111
+ }),
92
112
  );
93
113
  }
94
114
  }
@@ -5,15 +5,16 @@ import { ExpansionSquad } from "../../squad/behaviours/expansionSquad.js";
5
5
  import { MissionFactory } from "../missionFactories.js";
6
6
  import { OneTimeMission } from "./oneTimeMission.js";
7
7
  import { MatchAwareness } from "../../awareness.js";
8
- import { AttackFailReason, AttackMission } from "./attackMission.js";
9
8
  import { MissionController } from "../missionController.js";
9
+ import { DebugLogger } from "../../common/utils.js";
10
10
 
11
11
  /**
12
12
  * A mission that tries to create an MCV (if it doesn't exist) and deploy it somewhere it can be deployed.
13
13
  */
14
14
  export class ExpansionMission extends OneTimeMission {
15
- constructor(uniqueName: string, priority: number, selectedMcv: number | null) {
16
- super(uniqueName, priority, () => new ExpansionSquad(selectedMcv));
15
+ constructor(uniqueName: string, priority: number, selectedMcv: number | null,
16
+ logger: DebugLogger) {
17
+ super(uniqueName, priority, () => new ExpansionSquad(selectedMcv), logger);
17
18
  }
18
19
  }
19
20
 
@@ -27,13 +28,14 @@ export class ExpansionMissionFactory implements MissionFactory {
27
28
  playerData: PlayerData,
28
29
  matchAwareness: MatchAwareness,
29
30
  missionController: MissionController,
31
+ logger: DebugLogger
30
32
  ): void {
31
33
  // At this point, only expand if we have a loose MCV.
32
34
  const mcvs = gameApi.getVisibleUnits(playerData.name, "self", (r) =>
33
35
  gameApi.getGeneralRules().baseUnit.includes(r.name)
34
36
  );
35
37
  mcvs.forEach((mcv) => {
36
- missionController.addMission(new ExpansionMission("expand-with-" + mcv, 100, mcv));
38
+ missionController.addMission(new ExpansionMission("expand-with-" + mcv, 100, mcv, logger));
37
39
  });
38
40
  }
39
41