2024-05-03 15:47:33 +02:00
|
|
|
using System.Diagnostics.CodeAnalysis;
|
2024-04-14 18:50:20 +02:00
|
|
|
using System.IO;
|
2024-05-03 15:47:33 +02:00
|
|
|
using TanksServer.Graphics;
|
2024-04-14 18:50:20 +02:00
|
|
|
|
2024-04-10 19:25:45 +02:00
|
|
|
namespace TanksServer.GameLogic;
|
2024-04-06 13:46:34 +02:00
|
|
|
|
2024-05-03 15:47:33 +02:00
|
|
|
internal abstract class MapPrototype
|
|
|
|
{
|
|
|
|
public abstract Map CreateInstance();
|
|
|
|
}
|
|
|
|
|
2024-04-07 13:02:49 +02:00
|
|
|
internal sealed class MapService
|
2024-04-06 13:46:34 +02:00
|
|
|
{
|
2024-04-12 18:32:10 +02:00
|
|
|
public const ushort TilesPerRow = 44;
|
|
|
|
public const ushort TilesPerColumn = 20;
|
|
|
|
public const ushort TileSize = 8;
|
|
|
|
public const ushort PixelsPerRow = TilesPerRow * TileSize;
|
|
|
|
public const ushort PixelsPerColumn = TilesPerColumn * TileSize;
|
2024-04-14 18:50:20 +02:00
|
|
|
|
2024-05-03 15:47:33 +02:00
|
|
|
private readonly Dictionary<string, MapPrototype> _maps = new();
|
2024-04-14 23:11:00 +02:00
|
|
|
|
2024-04-16 18:55:34 +02:00
|
|
|
public IEnumerable<string> MapNames => _maps.Keys;
|
|
|
|
|
|
|
|
public Map Current { get; private set; }
|
2024-04-14 18:50:20 +02:00
|
|
|
|
2024-04-14 21:10:21 +02:00
|
|
|
public MapService()
|
2024-04-14 18:50:20 +02:00
|
|
|
{
|
2024-04-16 18:55:34 +02:00
|
|
|
foreach (var file in Directory.EnumerateFiles("./assets/maps/", "*.txt"))
|
|
|
|
LoadMapString(file);
|
|
|
|
foreach (var file in Directory.EnumerateFiles("./assets/maps/", "*.png"))
|
|
|
|
LoadMapPng(file);
|
|
|
|
|
|
|
|
var chosenMapIndex = Random.Shared.Next(_maps.Count);
|
|
|
|
var chosenMapName = _maps.Keys.Skip(chosenMapIndex).First();
|
2024-05-03 15:47:33 +02:00
|
|
|
Current = _maps[chosenMapName].CreateInstance();
|
2024-04-14 21:10:21 +02:00
|
|
|
}
|
|
|
|
|
2024-05-03 15:47:33 +02:00
|
|
|
public bool TryGetMapByName(string name, [MaybeNullWhen(false)] out MapPrototype map)
|
|
|
|
=> _maps.TryGetValue(name, out map);
|
2024-04-14 21:10:21 +02:00
|
|
|
|
2024-05-03 15:47:33 +02:00
|
|
|
public void SwitchTo(MapPrototype prototype) => Current = prototype.CreateInstance();
|
2024-04-14 22:45:51 +02:00
|
|
|
|
2024-05-03 15:47:33 +02:00
|
|
|
private void LoadMapPng(string file)
|
|
|
|
{
|
|
|
|
var name = Path.GetFileName(file);
|
|
|
|
var prototype = new SpriteMapPrototype(name, Sprite.FromImageFile(file));
|
|
|
|
_maps.Add(Path.GetFileName(file), prototype);
|
2024-04-14 18:50:20 +02:00
|
|
|
}
|
2024-04-06 13:46:34 +02:00
|
|
|
|
2024-04-16 18:55:34 +02:00
|
|
|
private void LoadMapString(string file)
|
2024-04-14 18:50:20 +02:00
|
|
|
{
|
2024-04-14 21:10:21 +02:00
|
|
|
var map = File.ReadAllText(file).ReplaceLineEndings(string.Empty).Trim();
|
2024-05-03 15:47:33 +02:00
|
|
|
var name = Path.GetFileName(file);
|
|
|
|
var prototype = new TextMapPrototype(name, map);
|
|
|
|
_maps.Add(name, prototype);
|
2024-04-21 19:34:22 +02:00
|
|
|
}
|
2024-04-06 13:46:34 +02:00
|
|
|
}
|