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 19:49:24 +02:00
|
|
|
for (ushort x = 1; x < MapService.TilesPerRow - 1; x++)
|
|
|
|
for (ushort y = 1; y < MapService.TilesPerColumn - 1; 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
|
|
|
|
2024-04-12 19:49:24 +02:00
|
|
|
var tilePixelCenter = tile.GetPixelRelative(4, 4).ToFloatPosition();
|
2024-04-11 20:48:21 +02:00
|
|
|
|
|
|
|
var minDistance = bullets.GetAll()
|
|
|
|
.Cast<IMapEntity>()
|
|
|
|
.Concat(tanks)
|
2024-04-12 19:49:24 +02:00
|
|
|
.Select(entity => entity.Position.Distance(tilePixelCenter))
|
2024-04-11 20:48:21 +02:00
|
|
|
.Aggregate(double.MaxValue, Math.Min);
|
2024-04-12 19:49:24 +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-13 14:07:14 +02:00
|
|
|
return min.ToPixelPosition().GetPixelRelative(4, 4).ToFloatPosition();
|
2024-04-07 13:02:49 +02:00
|
|
|
}
|
2024-04-13 14:07:14 +02:00
|
|
|
}
|