servicepoint-tanks/tanks-backend/TanksServer/GameLogic/MapService.cs

58 lines
1.8 KiB
C#
Raw Normal View History

using System.Diagnostics.CodeAnalysis;
using System.IO;
using TanksServer.Graphics;
2024-04-10 19:25:45 +02:00
namespace TanksServer.GameLogic;
internal abstract class MapPrototype
{
public abstract Map CreateInstance();
}
2024-04-07 13:02:49 +02:00
internal sealed class MapService
{
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;
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 21:10:21 +02:00
public MapService()
{
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();
Current = _maps[chosenMapName].CreateInstance();
2024-04-14 21:10:21 +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
public void SwitchTo(MapPrototype prototype) => Current = prototype.CreateInstance();
2024-04-14 22:45:51 +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-16 18:55:34 +02:00
private void LoadMapString(string file)
{
2024-04-14 21:10:21 +02:00
var map = File.ReadAllText(file).ReplaceLineEndings(string.Empty).Trim();
var name = Path.GetFileName(file);
var prototype = new TextMapPrototype(name, map);
_maps.Add(name, prototype);
2024-04-21 19:34:22 +02:00
}
}