diff --git a/src/core/game/Railroad.ts b/src/core/game/Railroad.ts index 2a271055d..8b0f3086a 100644 --- a/src/core/game/Railroad.ts +++ b/src/core/game/Railroad.ts @@ -20,8 +20,8 @@ export class Railroad { isActive: false, railTiles, }); - this.from.getRailroads().delete(this); - this.to.getRailroads().delete(this); + this.from.removeRailroad(this); + this.to.removeRailroad(this); } } @@ -29,14 +29,11 @@ export function getOrientedRailroad( from: TrainStation, to: TrainStation, ): OrientedRailroad | null { - for (const railroad of from.getRailroads()) { - if (railroad.from === to) { - return new OrientedRailroad(railroad, false); - } else if (railroad.to === to) { - return new OrientedRailroad(railroad, true); - } - } - return null; + const railroad = from.getRailroadTo(to); + if (!railroad) return null; + // If tiles are stored from -> to, we go forward when railroad.to === to + const forward = railroad.to === to; + return new OrientedRailroad(railroad, forward); } /** diff --git a/src/core/game/TrainStation.ts b/src/core/game/TrainStation.ts index 0181137c7..9318fab25 100644 --- a/src/core/game/TrainStation.ts +++ b/src/core/game/TrainStation.ts @@ -76,6 +76,8 @@ export class TrainStation { {}; private cluster: Cluster | null; private railroads: Set = new Set(); + // Quick lookup from neighboring station to connecting railroad + private railroadByNeighbor: Map = new Map(); constructor( private mg: Game, @@ -91,10 +93,19 @@ export class TrainStation { clearRailroads() { this.railroads.clear(); + this.railroadByNeighbor.clear(); } addRailroad(railRoad: Railroad) { this.railroads.add(railRoad); + const neighbor = railRoad.from === this ? railRoad.to : railRoad.from; + this.railroadByNeighbor.set(neighbor, railRoad); + } + + removeRailroad(railRoad: Railroad) { + this.railroads.delete(railRoad); + const neighbor = railRoad.from === this ? railRoad.to : railRoad.from; + this.railroadByNeighbor.delete(neighbor); } removeNeighboringRails(station: TrainStation) { @@ -111,7 +122,7 @@ export class TrainStation { isActive: false, railTiles, }); - this.railroads.delete(toRemove); + this.removeRailroad(toRemove); } } @@ -139,6 +150,10 @@ export class TrainStation { return this.railroads; } + getRailroadTo(station: TrainStation): Railroad | null { + return this.railroadByNeighbor.get(station) ?? null; + } + setCluster(cluster: Cluster | null) { this.cluster = cluster; }