add bullet timeout

This commit is contained in:
Vinzenz Schroeter 2024-04-19 13:32:41 +02:00
parent 61f90b99af
commit 0aac6f780b
4 changed files with 20 additions and 3 deletions

View file

@ -13,9 +13,20 @@ internal sealed class CollideBullets(
{
entityManager.RemoveBulletsWhere(BulletHitsTank);
entityManager.RemoveBulletsWhere(TryHitAndDestroyWall);
entityManager.RemoveBulletsWhere(TimeoutBullet);
return Task.CompletedTask;
}
private bool TimeoutBullet(Bullet bullet)
{
if (bullet.Timeout > DateTime.Now)
return false;
var radius = bullet.IsExplosive ? ExplosionRadius : 0;
ExplodeAt(bullet.Position.ToPixelPosition(), radius, bullet.Owner);
return true;
}
private bool TryHitAndDestroyWall(Bullet bullet)
{
var pixel = bullet.Position.ToPixelPosition();

View file

@ -7,4 +7,6 @@ internal sealed class GameRules
public double PowerUpSpawnChance { get; set; }
public int MaxPowerUpCount { get; set; } = int.MaxValue;
public int BulletTimeoutMs { get; set; } = int.MaxValue;
}

View file

@ -2,12 +2,14 @@ namespace TanksServer.GameLogic;
internal sealed class MapEntityManager(
ILogger<MapEntityManager> logger,
MapService map
MapService map,
IOptions<GameRules> options
)
{
private readonly HashSet<Bullet> _bullets = [];
private readonly HashSet<Tank> _tanks = [];
private readonly HashSet<PowerUp> _powerUps = [];
private readonly TimeSpan _bulletTimeout = TimeSpan.FromMilliseconds(options.Value.BulletTimeoutMs);
public IEnumerable<Bullet> Bullets => _bullets;
public IEnumerable<Tank> Tanks => _tanks;
@ -19,7 +21,7 @@ internal sealed class MapEntityManager(
.Concat(PowerUps);
public void SpawnBullet(Player tankOwner, FloatPosition position, double rotation, bool isExplosive)
=> _bullets.Add(new Bullet(tankOwner, position, rotation, isExplosive));
=> _bullets.Add(new Bullet(tankOwner, position, rotation, isExplosive, DateTime.Now + _bulletTimeout));
public void RemoveBulletsWhere(Predicate<Bullet> predicate) => _bullets.RemoveWhere(predicate);

View file

@ -1,6 +1,6 @@
namespace TanksServer.Models;
internal sealed class Bullet(Player tankOwner, FloatPosition position, double rotation, bool isExplosive) : IMapEntity
internal sealed class Bullet(Player tankOwner, FloatPosition position, double rotation, bool isExplosive, DateTime timeout) : IMapEntity
{
public Player Owner { get; } = tankOwner;
@ -10,5 +10,7 @@ internal sealed class Bullet(Player tankOwner, FloatPosition position, double ro
public bool IsExplosive { get; } = isExplosive;
public DateTime Timeout { get; } = timeout;
public PixelBounds Bounds => new (Position.ToPixelPosition(), Position.ToPixelPosition());
}