From 603a53eef798dba40a25fca8bbfb57827bab4780 Mon Sep 17 00:00:00 2001 From: Vinzenz Schroeter Date: Mon, 22 Apr 2024 19:59:41 +0200 Subject: [PATCH] save tanks only once --- .../TanksServer/GameLogic/MapEntityManager.cs | 34 +++++++++---------- 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/tanks-backend/TanksServer/GameLogic/MapEntityManager.cs b/tanks-backend/TanksServer/GameLogic/MapEntityManager.cs index 9146166..9378f6c 100644 --- a/tanks-backend/TanksServer/GameLogic/MapEntityManager.cs +++ b/tanks-backend/TanksServer/GameLogic/MapEntityManager.cs @@ -7,20 +7,14 @@ internal sealed class MapEntityManager( ) { private readonly HashSet _bullets = []; - private readonly HashSet _tanks = []; private readonly HashSet _powerUps = []; private readonly Dictionary _playerTanks = []; private readonly TimeSpan _bulletTimeout = TimeSpan.FromMilliseconds(options.Value.BulletTimeoutMs); public IEnumerable Bullets => _bullets; - public IEnumerable Tanks => _tanks; + public IEnumerable Tanks => _playerTanks.Values; public IEnumerable PowerUps => _powerUps; - public IEnumerable AllEntities => Bullets - .Cast() - .Concat(Tanks) - .Concat(PowerUps); - public void SpawnBullet(Player tankOwner, FloatPosition position, double rotation, bool isExplosive) => _bullets.Add(new Bullet { @@ -40,7 +34,6 @@ internal sealed class MapEntityManager( { Rotation = Random.Shared.NextDouble() }; - _tanks.Add(tank); _playerTanks[player] = tank; logger.LogInformation("Tank added for player {}", player.Id); } @@ -52,14 +45,20 @@ internal sealed class MapEntityManager( public void Remove(Tank tank) { logger.LogInformation("Tank removed for player {}", tank.Owner.Id); - _tanks.Remove(tank); _playerTanks.Remove(tank.Owner); } - public FloatPosition ChooseSpawnPosition() - { - Dictionary candidates = []; + public Tank? GetCurrentTankOfPlayer(Player player) => _playerTanks.GetValueOrDefault(player); + private IEnumerable AllEntities => Bullets + .Cast() + .Concat(Tanks) + .Concat(PowerUps); + + private FloatPosition ChooseSpawnPosition() + { + var maxMinDistance = 0d; + TilePosition spawnTile = default; for (ushort x = 1; x < MapService.TilesPerRow - 1; x++) for (ushort y = 1; y < MapService.TilesPerColumn - 1; y++) { @@ -68,17 +67,16 @@ internal sealed class MapEntityManager( continue; var tilePixelCenter = tile.ToPixelPosition().GetPixelRelative(4, 4).ToFloatPosition(); - var minDistance = AllEntities .Select(entity => entity.Position.Distance(tilePixelCenter)) .Aggregate(double.MaxValue, Math.Min); + if (minDistance <= maxMinDistance) + continue; - candidates.Add(tile, minDistance); + maxMinDistance = minDistance; + spawnTile = tile; } - var min = candidates.MaxBy(pair => pair.Value).Key; - return min.ToPixelPosition().GetPixelRelative(4, 4).ToFloatPosition(); + return spawnTile.ToPixelPosition().GetPixelRelative(4, 4).ToFloatPosition(); } - - public Tank? GetCurrentTankOfPlayer(Player player) => _playerTanks.GetValueOrDefault(player); }