servicepoint-tanks/TanksServer/GameLogic/SpawnNewTanks.cs

54 lines
1.5 KiB
C#
Raw Normal View History

2024-04-10 19:25:45 +02:00
namespace TanksServer.GameLogic;
2024-04-07 13:02:49 +02:00
2024-04-11 20:48:21 +02:00
internal sealed class SpawnNewTanks(
TankManager tanks,
MapService map,
SpawnQueue queue,
BulletManager bullets
) : ITickStep
2024-04-07 13:02:49 +02:00
{
public Task TickAsync()
{
2024-04-11 20:48:21 +02:00
if (!queue.TryDequeueNext(out var player))
return Task.CompletedTask;
tanks.Add(new Tank(player, ChooseSpawnPosition())
2024-04-07 13:02:49 +02:00
{
2024-04-12 18:32:10 +02:00
Rotation = Random.Shared.NextDouble()
2024-04-11 20:48:21 +02:00
});
2024-04-07 13:02:49 +02:00
return Task.CompletedTask;
}
2024-04-07 17:17:11 +02:00
private FloatPosition ChooseSpawnPosition()
2024-04-07 13:02:49 +02:00
{
2024-04-11 20:48:21 +02:00
Dictionary<TilePosition, double> candidates = [];
2024-04-12 18:32:10 +02:00
for (ushort x = 0; x < MapService.TilesPerRow; x++)
for (ushort y = 0; y < MapService.TilesPerColumn; y++)
2024-04-07 13:02:49 +02:00
{
var tile = new TilePosition(x, y);
if (map.IsCurrentlyWall(tile))
continue;
2024-04-11 20:48:21 +02:00
var tilePixelCenter = tile.GetPixelRelative(4, 4);
var minDistance = bullets.GetAll()
.Cast<IMapEntity>()
.Concat(tanks)
.Select(entity => Math.Sqrt(
Math.Pow(entity.Position.X - tilePixelCenter.X, 2) +
Math.Pow(entity.Position.Y - tilePixelCenter.Y, 2)))
.Aggregate(double.MaxValue, Math.Min);
2024-04-07 13:02:49 +02:00
2024-04-11 20:48:21 +02:00
candidates.Add(tile, minDistance);
2024-04-07 13:02:49 +02:00
}
2024-04-11 20:48:21 +02:00
var min = candidates.MaxBy(kvp => kvp.Value).Key;
2024-04-07 17:17:11 +02:00
return new FloatPosition(
2024-04-11 20:48:21 +02:00
min.X * MapService.TileSize,
min.Y * MapService.TileSize
2024-04-07 13:02:49 +02:00
);
}
2024-04-11 20:48:21 +02:00
}