servicepoint-tanks/TanksServer/GameLogic/SpawnNewTanks.cs

49 lines
1.4 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
{
2024-04-16 19:40:08 +02:00
public Task TickAsync(TimeSpan _)
2024-04-07 13:02:49 +02:00
{
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);
2024-04-14 22:45:51 +02:00
if (map.Current.IsWall(tile))
2024-04-07 13:02:49 +02:00
continue;
2024-04-11 20:48:21 +02:00
2024-04-13 16:27:45 +02:00
var tilePixelCenter = tile.ToPixelPosition().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;
return min.ToPixelPosition().GetPixelRelative(4, 4).ToFloatPosition();
2024-04-07 13:02:49 +02:00
}
}