diff --git a/src/core/PathFinding.ts b/src/core/PathFinding.ts index 0cfc2b8ba..7db19b4ff 100644 --- a/src/core/PathFinding.ts +++ b/src/core/PathFinding.ts @@ -69,3 +69,33 @@ export class AStar { return path; } } + +export class PathFinder { + + private curr: Tile = null + private dst: Tile = null + private path: Tile[] + private aStar: AStar + + constructor() { + + } + + nextTile(curr: Tile, dst: Tile): Tile { + if (curr != this.curr || dst != this.dst || this.path == null) { + this.curr = curr + this.dst = dst + this.path = null + this.aStar = new AStar(curr, dst) + if (this.aStar.compute(1000)) { + this.path = this.aStar.reconstructPath() + } else { + return null + } + } + if (this.path.length == 0) { + return null + } + return this.path.shift() + } +} diff --git a/src/core/execution/DestroyerExecution.ts b/src/core/execution/DestroyerExecution.ts index d25ddfd8e..3b5233da8 100644 --- a/src/core/execution/DestroyerExecution.ts +++ b/src/core/execution/DestroyerExecution.ts @@ -1,4 +1,6 @@ -import { Cell, Execution, MutableGame, MutablePlayer, MutableUnit, PlayerID, UnitType } from "../game/Game"; +import { Cell, Execution, MutableGame, MutablePlayer, MutableUnit, PlayerID, Tile, UnitType } from "../game/Game"; +import { AStar, PathFinder } from "../PathFinding"; +import { manhattanDist } from "../Util"; export class DestroyerExecution implements Execution { @@ -7,6 +9,12 @@ export class DestroyerExecution implements Execution { private destroyer: MutableUnit = null private mg: MutableGame = null + private target: MutableUnit = null + private pathfinder = new PathFinder() + + // TODO: put in config + private searchRange = 100 + constructor( private playerID: PlayerID, private cell: Cell, @@ -23,7 +31,28 @@ export class DestroyerExecution implements Execution { this.destroyer = this._owner.addUnit(UnitType.Destroyer, 0, this.mg.tile(this.cell)) return } - this.destroyer.move(this.destroyer.tile().neighbors()[0]) + if (!this.destroyer.isActive()) { + this.active = false + return + } + if (this.target == null) { + const ships = this.mg.units(UnitType.TransportShip) + .filter(u => manhattanDist(u.tile().cell(), this.destroyer.tile().cell())) + .filter(u => u.owner() != this.destroyer.owner()) + .filter(u => !u.owner().isAlliedWith(this.destroyer.owner())) + if (ships.length == 0) { + return + } + // TODO: sort by distance + this.target = ships[0] + } + const next = this.pathfinder.nextTile(this.destroyer.tile(), this.target.tile()) + if (next == null) { + this.target = null + return + } + + this.destroyer.move(next) } owner(): MutablePlayer {