save tanks only once

This commit is contained in:
Vinzenz Schroeter 2024-04-22 19:59:41 +02:00
parent 0f4eec6343
commit 603a53eef7

View file

@ -7,20 +7,14 @@ internal sealed class MapEntityManager(
)
{
private readonly HashSet<Bullet> _bullets = [];
private readonly HashSet<Tank> _tanks = [];
private readonly HashSet<PowerUp> _powerUps = [];
private readonly Dictionary<Player, Tank> _playerTanks = [];
private readonly TimeSpan _bulletTimeout = TimeSpan.FromMilliseconds(options.Value.BulletTimeoutMs);
public IEnumerable<Bullet> Bullets => _bullets;
public IEnumerable<Tank> Tanks => _tanks;
public IEnumerable<Tank> Tanks => _playerTanks.Values;
public IEnumerable<PowerUp> PowerUps => _powerUps;
public IEnumerable<IMapEntity> AllEntities => Bullets
.Cast<IMapEntity>()
.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<TilePosition, double> candidates = [];
public Tank? GetCurrentTankOfPlayer(Player player) => _playerTanks.GetValueOrDefault(player);
private IEnumerable<IMapEntity> AllEntities => Bullets
.Cast<IMapEntity>()
.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);
}