925 lines
30 KiB
C#
925 lines
30 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Numerics;
|
|
using System.Text.Json;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging;
|
|
using Server.Networking;
|
|
using Server.Networking.Handling;
|
|
using Server.Networking.Messages;
|
|
using Server.Services.Auth;
|
|
|
|
namespace VoidScavengers.Game;
|
|
|
|
/// <summary>
|
|
/// Handles all game-related messages and manages match instances.
|
|
/// Integrates with the existing SystemRevival server architecture.
|
|
/// </summary>
|
|
public sealed class GameHandler : IClientMessageHandler
|
|
{
|
|
private readonly ILogger<GameHandler> _log;
|
|
private readonly ISessionRegistry _sessions;
|
|
private readonly IMessageSerializer _ser;
|
|
private readonly MatchManager _matchManager;
|
|
|
|
public GameHandler(
|
|
ILogger<GameHandler> log,
|
|
ISessionRegistry sessions,
|
|
IMessageSerializer ser,
|
|
MatchManager matchManager)
|
|
{
|
|
_log = log;
|
|
_sessions = sessions;
|
|
_ser = ser;
|
|
_matchManager = matchManager;
|
|
}
|
|
|
|
public IReadOnlyCollection<int> SupportedOpCodes => new[]
|
|
{
|
|
// Lobby
|
|
GameOpCodes.LOBBY_JOIN,
|
|
GameOpCodes.LOBBY_READY,
|
|
GameOpCodes.LOBBY_LEAVE,
|
|
|
|
// Game Input
|
|
GameOpCodes.INPUT_MOVE,
|
|
GameOpCodes.INPUT_ACTION,
|
|
GameOpCodes.INPUT_SHOOT,
|
|
GameOpCodes.INPUT_DROP,
|
|
GameOpCodes.INPUT_CRAFT,
|
|
|
|
// Chat
|
|
GameOpCodes.CHAT_SEND
|
|
};
|
|
|
|
public async Task HandleAsync(int opCode, IConnection connection, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
|
{
|
|
// All game operations require authentication
|
|
if (!_sessions.TryGet(connection.Id, out var accountId, out _))
|
|
{
|
|
await SendErrorAsync(connection, "auth_required", ct);
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
switch (opCode)
|
|
{
|
|
case GameOpCodes.LOBBY_JOIN:
|
|
await HandleLobbyJoinAsync(connection, accountId, payload, ct);
|
|
break;
|
|
|
|
case GameOpCodes.LOBBY_READY:
|
|
await HandleLobbyReadyAsync(connection, accountId, payload, ct);
|
|
break;
|
|
|
|
case GameOpCodes.LOBBY_LEAVE:
|
|
await HandleLobbyLeaveAsync(connection, accountId, ct);
|
|
break;
|
|
|
|
case GameOpCodes.INPUT_MOVE:
|
|
await HandleMoveInputAsync(connection, accountId, payload, ct);
|
|
break;
|
|
|
|
case GameOpCodes.INPUT_SHOOT:
|
|
await HandleShootInputAsync(connection, accountId, payload, ct);
|
|
break;
|
|
|
|
case GameOpCodes.INPUT_ACTION:
|
|
await HandleActionInputAsync(connection, accountId, payload, ct);
|
|
break;
|
|
|
|
case GameOpCodes.INPUT_CRAFT:
|
|
await HandleCraftInputAsync(connection, accountId, payload, ct);
|
|
break;
|
|
|
|
case GameOpCodes.INPUT_DROP:
|
|
await HandleDropInputAsync(connection, accountId, payload, ct);
|
|
break;
|
|
|
|
case GameOpCodes.CHAT_SEND:
|
|
await HandleChatAsync(connection, accountId, payload, ct);
|
|
break;
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_log.LogError(ex, "Error handling opcode {OpCode} from account {AccountId}", opCode, accountId);
|
|
await SendErrorAsync(connection, "internal_error", ct);
|
|
}
|
|
}
|
|
|
|
private async Task HandleLobbyJoinAsync(IConnection conn, ulong accountId, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
|
{
|
|
var request = _ser.Deserialize<LobbyJoinRequest>(payload);
|
|
|
|
// Get or create player name (in production, fetch from database)
|
|
string playerName = request?.PlayerName ?? $"Player{accountId % 10000}";
|
|
|
|
var (ok, lobbyId, error) = await _matchManager.JoinLobbyAsync(accountId, conn, playerName);
|
|
|
|
var result = new LobbyJoinResult(ok, error, lobbyId, ok ? _matchManager.GetLobbyPlayerCount(lobbyId!) : 0);
|
|
await SendAsync(conn, GameOpCodes.LOBBY_JOIN_RESULT, result, ct);
|
|
}
|
|
|
|
private async Task HandleLobbyReadyAsync(IConnection conn, ulong accountId, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
|
{
|
|
var request = _ser.Deserialize<LobbyReadyRequest>(payload);
|
|
await _matchManager.SetPlayerReadyAsync(accountId, request?.Ready ?? true);
|
|
}
|
|
|
|
private async Task HandleLobbyLeaveAsync(IConnection conn, ulong accountId, CancellationToken ct)
|
|
{
|
|
await _matchManager.LeaveLobbyAsync(accountId);
|
|
}
|
|
|
|
private Task HandleMoveInputAsync(IConnection conn, ulong accountId, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
|
{
|
|
var input = _ser.Deserialize<MoveInputMsg>(payload);
|
|
if (input == null) return Task.CompletedTask;
|
|
|
|
_matchManager.EnqueueInput(accountId, new PlayerInput
|
|
{
|
|
PlayerId = accountId,
|
|
Type = InputType.Move,
|
|
Dx = input.Dx,
|
|
Dy = input.Dy,
|
|
AimAngle = input.AimAngle,
|
|
Seq = input.Seq
|
|
});
|
|
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
private Task HandleShootInputAsync(IConnection conn, ulong accountId, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
|
{
|
|
var input = _ser.Deserialize<ShootInputMsg>(payload);
|
|
if (input == null) return Task.CompletedTask;
|
|
|
|
_matchManager.EnqueueInput(accountId, new PlayerInput
|
|
{
|
|
PlayerId = accountId,
|
|
Type = InputType.Shoot,
|
|
AimAngle = input.AimAngle,
|
|
Seq = input.Seq
|
|
});
|
|
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
private Task HandleActionInputAsync(IConnection conn, ulong accountId, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
|
{
|
|
var input = _ser.Deserialize<ActionInputMsg>(payload);
|
|
|
|
_matchManager.EnqueueInput(accountId, new PlayerInput
|
|
{
|
|
PlayerId = accountId,
|
|
Type = InputType.Action,
|
|
TargetId = input?.TargetId
|
|
});
|
|
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
private Task HandleCraftInputAsync(IConnection conn, ulong accountId, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
|
{
|
|
var input = _ser.Deserialize<CraftInputMsg>(payload);
|
|
if (input == null) return Task.CompletedTask;
|
|
|
|
_matchManager.EnqueueInput(accountId, new PlayerInput
|
|
{
|
|
PlayerId = accountId,
|
|
Type = InputType.Craft,
|
|
TargetId = input.RecipeId
|
|
});
|
|
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
private Task HandleDropInputAsync(IConnection conn, ulong accountId, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
|
{
|
|
var input = _ser.Deserialize<DropInputMsg>(payload);
|
|
if (input == null) return Task.CompletedTask;
|
|
|
|
_matchManager.EnqueueInput(accountId, new PlayerInput
|
|
{
|
|
PlayerId = accountId,
|
|
Type = InputType.Drop,
|
|
TargetId = input.SlotIndex
|
|
});
|
|
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
private async Task HandleChatAsync(IConnection conn, ulong accountId, ReadOnlyMemory<byte> payload, CancellationToken ct)
|
|
{
|
|
var msg = _ser.Deserialize<ChatMsg>(payload);
|
|
if (string.IsNullOrWhiteSpace(msg?.Text)) return;
|
|
|
|
// Sanitize and limit message
|
|
string text = msg.Text.Trim();
|
|
if (text.Length > 200) text = text[..200];
|
|
|
|
await _matchManager.BroadcastChatAsync(accountId, text);
|
|
}
|
|
|
|
private async Task SendAsync<T>(IConnection conn, int opCode, T data, CancellationToken ct)
|
|
{
|
|
var payload = _ser.Serialize(data);
|
|
var wire = _ser.Serialize(new ServerMessage(opCode, payload));
|
|
await conn.SendAsync(wire, ct);
|
|
}
|
|
|
|
private async Task SendErrorAsync(IConnection conn, string error, CancellationToken ct)
|
|
{
|
|
await SendAsync(conn, OpCodes.ERROR, new { error }, ct);
|
|
}
|
|
}
|
|
|
|
// ===== Input message types for deserialization =====
|
|
public sealed record LobbyJoinRequest(string? PlayerName);
|
|
public sealed record LobbyReadyRequest(bool Ready);
|
|
public sealed record LobbyJoinResult(bool Ok, string? Error, string? LobbyId, int PlayerCount);
|
|
public sealed record MoveInputMsg(float Dx, float Dy, float AimAngle, uint Seq);
|
|
public sealed record ShootInputMsg(float AimAngle, uint Seq);
|
|
public sealed record ActionInputMsg(int? TargetId);
|
|
public sealed record CraftInputMsg(int RecipeId);
|
|
public sealed record DropInputMsg(int SlotIndex);
|
|
public sealed record ChatMsg(string Text);
|
|
|
|
/// <summary>
|
|
/// Static OpCodes class for game-specific operations
|
|
/// </summary>
|
|
public static class GameOpCodes
|
|
{
|
|
// Lobby
|
|
public const int LOBBY_JOIN = 400;
|
|
public const int LOBBY_JOIN_RESULT = 401;
|
|
public const int LOBBY_STATE = 402;
|
|
public const int LOBBY_READY = 403;
|
|
public const int LOBBY_COUNTDOWN = 404;
|
|
public const int LOBBY_LEAVE = 405;
|
|
|
|
// Game State
|
|
public const int GAME_START = 420;
|
|
public const int GAME_STATE = 421;
|
|
public const int GAME_TICK = 422;
|
|
public const int GAME_END = 423;
|
|
|
|
// Input
|
|
public const int INPUT_MOVE = 450;
|
|
public const int INPUT_ACTION = 451;
|
|
public const int INPUT_SHOOT = 452;
|
|
public const int INPUT_DROP = 453;
|
|
public const int INPUT_CRAFT = 454;
|
|
|
|
// Events
|
|
public const int EVENT_SPAWN = 470;
|
|
public const int EVENT_DESPAWN = 471;
|
|
public const int EVENT_DAMAGE = 472;
|
|
public const int EVENT_DEATH = 473;
|
|
public const int EVENT_PICKUP = 474;
|
|
public const int EVENT_PROJECTILE = 475;
|
|
public const int EVENT_EXPLOSION = 476;
|
|
|
|
// Chat
|
|
public const int CHAT_SEND = 500;
|
|
public const int CHAT_RECEIVE = 501;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Manages lobbies, matchmaking, and active game instances
|
|
/// </summary>
|
|
public sealed class MatchManager : IDisposable
|
|
{
|
|
private readonly ILogger<MatchManager> _log;
|
|
private readonly IMessageSerializer _ser;
|
|
private readonly IServiceScopeFactory _scopeFactory;
|
|
|
|
private readonly ConcurrentDictionary<string, Lobby> _lobbies = new();
|
|
private readonly ConcurrentDictionary<string, MatchInstance> _matches = new();
|
|
private readonly ConcurrentDictionary<ulong, string> _playerToLobby = new();
|
|
private readonly ConcurrentDictionary<ulong, string> _playerToMatch = new();
|
|
private readonly ConcurrentDictionary<ulong, IConnection> _playerConnections = new();
|
|
|
|
private readonly Timer _tickTimer;
|
|
private readonly Timer _lobbyTimer;
|
|
|
|
private const int MinPlayersToStart = 2;
|
|
private const int MaxPlayersPerLobby = 8;
|
|
private const int LobbyCountdownSeconds = 10;
|
|
|
|
public MatchManager(ILogger<MatchManager> log, IMessageSerializer ser, IServiceScopeFactory scopeFactory)
|
|
{
|
|
_log = log;
|
|
_ser = ser;
|
|
_scopeFactory = scopeFactory;
|
|
|
|
// Game tick timer (20 Hz)
|
|
_tickTimer = new Timer(OnGameTick, null, 50, 50);
|
|
|
|
// Lobby update timer (1 Hz)
|
|
_lobbyTimer = new Timer(OnLobbyTick, null, 1000, 1000);
|
|
}
|
|
|
|
public async Task<(bool ok, string? lobbyId, string? error)> JoinLobbyAsync(ulong accountId, IConnection conn, string playerName)
|
|
{
|
|
// Remove from any existing lobby
|
|
await LeaveLobbyAsync(accountId);
|
|
|
|
// Find or create lobby
|
|
Lobby? lobby = null;
|
|
foreach (var l in _lobbies.Values)
|
|
{
|
|
if (l.Phase == LobbyPhase.Waiting && l.Players.Count < MaxPlayersPerLobby)
|
|
{
|
|
lobby = l;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (lobby == null)
|
|
{
|
|
lobby = new Lobby
|
|
{
|
|
Id = Guid.NewGuid().ToString("N")[..8],
|
|
CreatedAt = DateTime.UtcNow
|
|
};
|
|
_lobbies[lobby.Id] = lobby;
|
|
_log.LogInformation("Created new lobby {LobbyId}", lobby.Id);
|
|
}
|
|
|
|
var player = new LobbyPlayer
|
|
{
|
|
AccountId = accountId,
|
|
Name = playerName,
|
|
Ready = false,
|
|
Connection = conn
|
|
};
|
|
|
|
lobby.Players[accountId] = player;
|
|
_playerToLobby[accountId] = lobby.Id;
|
|
_playerConnections[accountId] = conn;
|
|
|
|
_log.LogInformation("Player {AccountId} ({Name}) joined lobby {LobbyId}", accountId, playerName, lobby.Id);
|
|
|
|
// Broadcast updated lobby state
|
|
await BroadcastLobbyStateAsync(lobby);
|
|
|
|
return (true, lobby.Id, null);
|
|
}
|
|
|
|
public async Task LeaveLobbyAsync(ulong accountId)
|
|
{
|
|
if (_playerToLobby.TryRemove(accountId, out var lobbyId))
|
|
{
|
|
if (_lobbies.TryGetValue(lobbyId, out var lobby))
|
|
{
|
|
lobby.Players.Remove(accountId);
|
|
|
|
// Clean up empty lobbies
|
|
if (lobby.Players.Count == 0)
|
|
{
|
|
_lobbies.TryRemove(lobbyId, out _);
|
|
_log.LogInformation("Removed empty lobby {LobbyId}", lobbyId);
|
|
}
|
|
else
|
|
{
|
|
// Reset countdown if in progress
|
|
if (lobby.Phase == LobbyPhase.Countdown)
|
|
{
|
|
lobby.Phase = LobbyPhase.Waiting;
|
|
lobby.CountdownSeconds = 0;
|
|
}
|
|
await BroadcastLobbyStateAsync(lobby);
|
|
}
|
|
}
|
|
}
|
|
|
|
_playerConnections.TryRemove(accountId, out _);
|
|
}
|
|
|
|
public async Task SetPlayerReadyAsync(ulong accountId, bool ready)
|
|
{
|
|
if (!_playerToLobby.TryGetValue(accountId, out var lobbyId)) return;
|
|
if (!_lobbies.TryGetValue(lobbyId, out var lobby)) return;
|
|
if (!lobby.Players.TryGetValue(accountId, out var player)) return;
|
|
|
|
player.Ready = ready;
|
|
await BroadcastLobbyStateAsync(lobby);
|
|
|
|
// Check if all players ready
|
|
if (lobby.Players.Count >= MinPlayersToStart &&
|
|
lobby.Players.Values.All(p => p.Ready) &&
|
|
lobby.Phase == LobbyPhase.Waiting)
|
|
{
|
|
lobby.Phase = LobbyPhase.Countdown;
|
|
lobby.CountdownSeconds = LobbyCountdownSeconds;
|
|
_log.LogInformation("Lobby {LobbyId} starting countdown", lobbyId);
|
|
}
|
|
}
|
|
|
|
public int GetLobbyPlayerCount(string lobbyId)
|
|
{
|
|
return _lobbies.TryGetValue(lobbyId, out var lobby) ? lobby.Players.Count : 0;
|
|
}
|
|
|
|
public void EnqueueInput(ulong accountId, PlayerInput input)
|
|
{
|
|
if (!_playerToMatch.TryGetValue(accountId, out var matchId)) return;
|
|
if (!_matches.TryGetValue(matchId, out var match)) return;
|
|
|
|
match.Simulation.EnqueueInput(accountId, input);
|
|
}
|
|
|
|
public async Task BroadcastChatAsync(ulong senderId, string text)
|
|
{
|
|
// Find which match/lobby the sender is in
|
|
string? targetId = null;
|
|
Dictionary<ulong, IConnection>? targets = null;
|
|
string? senderName = null;
|
|
|
|
if (_playerToMatch.TryGetValue(senderId, out var matchId) &&
|
|
_matches.TryGetValue(matchId, out var match))
|
|
{
|
|
targets = match.Connections;
|
|
senderName = match.Simulation.Players.TryGetValue(senderId, out var p) ? p.Name : "Unknown";
|
|
}
|
|
else if (_playerToLobby.TryGetValue(senderId, out var lobbyId) &&
|
|
_lobbies.TryGetValue(lobbyId, out var lobby))
|
|
{
|
|
targets = lobby.Players.ToDictionary(kv => kv.Key, kv => kv.Value.Connection);
|
|
senderName = lobby.Players.TryGetValue(senderId, out var p) ? p.Name : "Unknown";
|
|
}
|
|
|
|
if (targets == null) return;
|
|
|
|
var chatMsg = new
|
|
{
|
|
senderId,
|
|
senderName,
|
|
text,
|
|
timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
|
|
};
|
|
|
|
var payload = _ser.Serialize(chatMsg);
|
|
var wire = _ser.Serialize(new ServerMessage(GameOpCodes.CHAT_RECEIVE, payload));
|
|
|
|
foreach (var (_, conn) in targets)
|
|
{
|
|
try
|
|
{
|
|
await conn.SendAsync(wire);
|
|
}
|
|
catch { /* ignore failed sends */ }
|
|
}
|
|
}
|
|
|
|
private async void OnLobbyTick(object? state)
|
|
{
|
|
foreach (var lobby in _lobbies.Values.ToList())
|
|
{
|
|
if (lobby.Phase == LobbyPhase.Countdown)
|
|
{
|
|
lobby.CountdownSeconds--;
|
|
|
|
// Broadcast countdown
|
|
await BroadcastToLobbyAsync(lobby, GameOpCodes.LOBBY_COUNTDOWN,
|
|
new { seconds = lobby.CountdownSeconds });
|
|
|
|
if (lobby.CountdownSeconds <= 0)
|
|
{
|
|
// Start the match!
|
|
await StartMatchAsync(lobby);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private async Task StartMatchAsync(Lobby lobby)
|
|
{
|
|
lobby.Phase = LobbyPhase.Starting;
|
|
|
|
var matchId = Guid.NewGuid().ToString("N")[..12];
|
|
var seed = (int)(DateTime.UtcNow.Ticks % int.MaxValue);
|
|
var simulation = new GameSimulation(matchId, seed);
|
|
|
|
var match = new MatchInstance
|
|
{
|
|
Id = matchId,
|
|
Simulation = simulation,
|
|
StartedAt = DateTime.UtcNow
|
|
};
|
|
|
|
// Add players to match
|
|
int playerIndex = 0;
|
|
foreach (var (accountId, lobbyPlayer) in lobby.Players)
|
|
{
|
|
var spawnPos = simulation.GetSpawnPosition(playerIndex, lobby.Players.Count);
|
|
simulation.AddPlayer(accountId, lobbyPlayer.Name, spawnPos);
|
|
|
|
match.Connections[accountId] = lobbyPlayer.Connection;
|
|
_playerToMatch[accountId] = matchId;
|
|
_playerToLobby.TryRemove(accountId, out _);
|
|
|
|
playerIndex++;
|
|
}
|
|
|
|
_matches[matchId] = match;
|
|
_lobbies.TryRemove(lobby.Id, out _);
|
|
|
|
// Start simulation
|
|
simulation.StartGame();
|
|
|
|
// Send GAME_START to all players
|
|
foreach (var (accountId, conn) in match.Connections)
|
|
{
|
|
var startInfo = BuildGameStartInfo(simulation, accountId);
|
|
var payload = _ser.Serialize(startInfo);
|
|
var wire = _ser.Serialize(new ServerMessage(GameOpCodes.GAME_START, payload));
|
|
|
|
try
|
|
{
|
|
await conn.SendAsync(wire);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_log.LogWarning(ex, "Failed to send GAME_START to {AccountId}", accountId);
|
|
}
|
|
}
|
|
|
|
_log.LogInformation("Match {MatchId} started with {PlayerCount} players", matchId, match.Connections.Count);
|
|
}
|
|
|
|
private object BuildGameStartInfo(GameSimulation sim, ulong forPlayerId)
|
|
{
|
|
var self = sim.Players[forPlayerId];
|
|
var others = sim.Players.Values.Where(p => p.Id != forPlayerId).ToArray();
|
|
|
|
return new
|
|
{
|
|
matchId = sim.MatchId,
|
|
mapSeed = sim.MapSeed,
|
|
mapWidth = sim.MapWidth,
|
|
mapHeight = sim.MapHeight,
|
|
self = new
|
|
{
|
|
playerId = self.Id,
|
|
name = self.Name,
|
|
x = self.X,
|
|
y = self.Y,
|
|
rotation = self.Rotation,
|
|
health = self.Health,
|
|
maxHealth = self.MaxHealth
|
|
},
|
|
otherPlayers = others.Select(p => new
|
|
{
|
|
playerId = p.Id,
|
|
name = p.Name,
|
|
x = p.X,
|
|
y = p.Y,
|
|
rotation = p.Rotation,
|
|
health = p.Health,
|
|
maxHealth = p.MaxHealth
|
|
}).ToArray(),
|
|
asteroids = sim.Asteroids.Values.Select(a => new
|
|
{
|
|
id = a.Id,
|
|
x = a.X,
|
|
y = a.Y,
|
|
radius = a.Radius,
|
|
type = a.Type
|
|
}).ToArray(),
|
|
resources = sim.Resources.Values.Select(r => new
|
|
{
|
|
id = r.Id,
|
|
x = r.X,
|
|
y = r.Y,
|
|
resourceType = r.ResourceType,
|
|
amount = r.Amount
|
|
}).ToArray(),
|
|
extractionZones = sim.ExtractionZones.Values.Select(z => new
|
|
{
|
|
id = z.Id,
|
|
x = z.X,
|
|
y = z.Y,
|
|
radius = z.Radius,
|
|
active = z.Active,
|
|
activatesAtTick = z.ActivatesAtTick
|
|
}).ToArray()
|
|
};
|
|
}
|
|
|
|
private async void OnGameTick(object? state)
|
|
{
|
|
foreach (var match in _matches.Values.ToList())
|
|
{
|
|
if (match.Simulation.Phase != GamePhase.InProgress) continue;
|
|
|
|
// Advance simulation
|
|
var events = match.Simulation.Tick();
|
|
|
|
// Broadcast state snapshot every tick
|
|
await BroadcastGameStateAsync(match);
|
|
|
|
// Broadcast events
|
|
foreach (var evt in events)
|
|
{
|
|
await BroadcastEventAsync(match, evt);
|
|
|
|
// Handle game end
|
|
if (evt.Type == EventType.GameEnd)
|
|
{
|
|
await EndMatchAsync(match);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private async Task BroadcastGameStateAsync(MatchInstance match)
|
|
{
|
|
var sim = match.Simulation;
|
|
|
|
var state = new
|
|
{
|
|
tick = sim.CurrentTick,
|
|
timeRemaining = sim.TimeRemaining,
|
|
playersAlive = sim.Players.Values.Count(p => p.Alive),
|
|
entities = sim.Players.Values.Where(p => p.Alive).Select(p => new
|
|
{
|
|
id = p.Id,
|
|
type = 0, // player
|
|
x = p.X,
|
|
y = p.Y,
|
|
rotation = p.Rotation,
|
|
health = p.Health,
|
|
scrap = p.Scrap,
|
|
energy = p.Energy,
|
|
rare = p.Rare
|
|
}).ToArray(),
|
|
projectiles = sim.Projectiles.Values.Select(p => new
|
|
{
|
|
id = p.Id,
|
|
x = p.X,
|
|
y = p.Y,
|
|
velX = p.VelX,
|
|
velY = p.VelY,
|
|
ownerId = p.OwnerId
|
|
}).ToArray(),
|
|
droppedItems = sim.DroppedItems.Values.Select(d => new
|
|
{
|
|
id = d.Id,
|
|
x = d.X,
|
|
y = d.Y,
|
|
itemId = d.ItemId,
|
|
quantity = d.Quantity
|
|
}).ToArray(),
|
|
resources = sim.Resources.Values.Where(r => r.Amount > 0).Select(r => new
|
|
{
|
|
id = r.Id,
|
|
amount = r.Amount
|
|
}).ToArray()
|
|
};
|
|
|
|
var payload = _ser.Serialize(state);
|
|
var wire = _ser.Serialize(new ServerMessage(GameOpCodes.GAME_STATE, payload));
|
|
|
|
foreach (var (_, conn) in match.Connections)
|
|
{
|
|
try
|
|
{
|
|
await conn.SendAsync(wire);
|
|
}
|
|
catch { /* ignore */ }
|
|
}
|
|
}
|
|
|
|
private async Task BroadcastEventAsync(MatchInstance match, GameEvent evt)
|
|
{
|
|
int opCode = evt.Type switch
|
|
{
|
|
EventType.Spawn => GameOpCodes.EVENT_SPAWN,
|
|
EventType.Despawn => GameOpCodes.EVENT_DESPAWN,
|
|
EventType.Damage => GameOpCodes.EVENT_DAMAGE,
|
|
EventType.Death => GameOpCodes.EVENT_DEATH,
|
|
EventType.Pickup => GameOpCodes.EVENT_PICKUP,
|
|
EventType.Projectile => GameOpCodes.EVENT_PROJECTILE,
|
|
EventType.Explosion => GameOpCodes.EVENT_EXPLOSION,
|
|
EventType.GameEnd => GameOpCodes.GAME_END,
|
|
_ => 0
|
|
};
|
|
|
|
if (opCode == 0) return;
|
|
|
|
var payload = _ser.Serialize(evt.Data);
|
|
var wire = _ser.Serialize(new ServerMessage(opCode, payload));
|
|
|
|
foreach (var (_, conn) in match.Connections)
|
|
{
|
|
try
|
|
{
|
|
await conn.SendAsync(wire);
|
|
}
|
|
catch { /* ignore */ }
|
|
}
|
|
}
|
|
|
|
private async Task EndMatchAsync(MatchInstance match)
|
|
{
|
|
// Get match results before cleanup
|
|
var results = match.Simulation.GetMatchResults();
|
|
|
|
// Persist stats to database
|
|
try
|
|
{
|
|
await PersistMatchResultsAsync(match.Id, results);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_log.LogError(ex, "Failed to persist match results for {MatchId}", match.Id);
|
|
}
|
|
|
|
// Remove players from match tracking
|
|
foreach (var accountId in match.Connections.Keys)
|
|
{
|
|
_playerToMatch.TryRemove(accountId, out _);
|
|
}
|
|
|
|
_matches.TryRemove(match.Id, out _);
|
|
_log.LogInformation("Match {MatchId} ended with {PlayerCount} players", match.Id, results.Count);
|
|
}
|
|
|
|
private async Task PersistMatchResultsAsync(string matchId, List<MatchPlayerResult> results)
|
|
{
|
|
using var scope = _scopeFactory.CreateScope();
|
|
var db = scope.ServiceProvider.GetRequiredService<Server.Data.GameDbContext>();
|
|
|
|
foreach (var result in results)
|
|
{
|
|
// Get or create player stats
|
|
var stats = await db.PlayerStats.FirstOrDefaultAsync(s => s.AccountId == result.AccountId);
|
|
if (stats == null)
|
|
{
|
|
stats = new Server.Data.PlayerStats
|
|
{
|
|
AccountId = result.AccountId,
|
|
CreatedAt = DateTime.UtcNow
|
|
};
|
|
db.PlayerStats.Add(stats);
|
|
}
|
|
|
|
// Update lifetime stats
|
|
stats.MatchesPlayed++;
|
|
stats.Kills += result.Kills;
|
|
stats.Deaths += result.Deaths;
|
|
stats.TotalDamageDealt += result.DamageDealt;
|
|
stats.TotalDamageTaken += result.DamageTaken;
|
|
stats.TotalScrapCollected += result.ScrapCollected;
|
|
stats.TotalEnergyCollected += result.EnergyCollected;
|
|
stats.TotalRareCollected += result.RareCollected;
|
|
stats.ItemsCrafted += result.ItemsCrafted;
|
|
stats.TotalPlayTimeSeconds += result.SurvivalTimeSeconds;
|
|
|
|
if (result.SurvivalTimeSeconds > stats.LongestSurvivalSeconds)
|
|
stats.LongestSurvivalSeconds = result.SurvivalTimeSeconds;
|
|
|
|
// Win/loss tracking
|
|
bool isWin = result.Result == MatchPlayerResultType.Won || result.Result == MatchPlayerResultType.Extracted;
|
|
if (isWin)
|
|
stats.Wins++;
|
|
else
|
|
stats.Losses++;
|
|
|
|
if (result.Result == MatchPlayerResultType.Extracted)
|
|
stats.Extractions++;
|
|
|
|
// Simple Elo calculation (can be made more sophisticated)
|
|
int eloChange = CalculateEloChange(stats.Elo, result.Placement, result.TotalPlayers, isWin);
|
|
stats.Elo = Math.Max(0, stats.Elo + eloChange);
|
|
|
|
// Record match history
|
|
var history = new Server.Data.MatchHistory
|
|
{
|
|
MatchId = matchId,
|
|
AccountId = result.AccountId,
|
|
Result = isWin
|
|
? (result.Result == MatchPlayerResultType.Extracted
|
|
? Server.Data.MatchResult.Extracted
|
|
: Server.Data.MatchResult.Win)
|
|
: Server.Data.MatchResult.Loss,
|
|
Placement = result.Placement,
|
|
TotalPlayers = result.TotalPlayers,
|
|
Kills = result.Kills,
|
|
Deaths = result.Deaths,
|
|
DamageDealt = result.DamageDealt,
|
|
DamageTaken = result.DamageTaken,
|
|
ScrapCollected = result.ScrapCollected,
|
|
EnergyCollected = result.EnergyCollected,
|
|
RareCollected = result.RareCollected,
|
|
ItemsCrafted = result.ItemsCrafted,
|
|
SurvivalTimeSeconds = result.SurvivalTimeSeconds,
|
|
MatchDurationSeconds = result.MatchDurationSeconds,
|
|
EloChange = eloChange,
|
|
EloAfter = stats.Elo,
|
|
PlayedAt = DateTime.UtcNow
|
|
};
|
|
db.MatchHistory.Add(history);
|
|
}
|
|
|
|
await db.SaveChangesAsync();
|
|
_log.LogInformation("Persisted stats for match {MatchId}", matchId);
|
|
}
|
|
|
|
private int CalculateEloChange(int currentElo, int placement, int totalPlayers, bool isWin)
|
|
{
|
|
// Simple Elo-like system based on placement
|
|
// K-factor varies by Elo (higher K for lower Elo = faster adjustment)
|
|
int kFactor = currentElo < 1200 ? 32 : (currentElo < 1600 ? 24 : 16);
|
|
|
|
// Expected score based on placement (1st = 1.0, last = 0.0)
|
|
float expectedPlacement = totalPlayers / 2f;
|
|
float actualScore = (totalPlayers - placement) / (float)(totalPlayers - 1);
|
|
float expectedScore = 0.5f; // Assume average performance expected
|
|
|
|
// Bonus for winning
|
|
if (isWin) actualScore = Math.Max(actualScore, 0.75f);
|
|
|
|
int change = (int)(kFactor * (actualScore - expectedScore));
|
|
|
|
// Clamp to reasonable range
|
|
return Math.Clamp(change, -50, 50);
|
|
}
|
|
|
|
private async Task BroadcastLobbyStateAsync(Lobby lobby)
|
|
{
|
|
var state = new
|
|
{
|
|
lobbyId = lobby.Id,
|
|
phase = lobby.Phase.ToString(),
|
|
countdownSeconds = lobby.CountdownSeconds,
|
|
players = lobby.Players.Values.Select(p => new
|
|
{
|
|
accountId = p.AccountId,
|
|
name = p.Name,
|
|
ready = p.Ready
|
|
}).ToArray()
|
|
};
|
|
|
|
await BroadcastToLobbyAsync(lobby, GameOpCodes.LOBBY_STATE, state);
|
|
}
|
|
|
|
private async Task BroadcastToLobbyAsync<T>(Lobby lobby, int opCode, T data)
|
|
{
|
|
var payload = _ser.Serialize(data);
|
|
var wire = _ser.Serialize(new ServerMessage(opCode, payload));
|
|
|
|
foreach (var player in lobby.Players.Values)
|
|
{
|
|
try
|
|
{
|
|
await player.Connection.SendAsync(wire);
|
|
}
|
|
catch { /* ignore */ }
|
|
}
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
_tickTimer.Dispose();
|
|
_lobbyTimer.Dispose();
|
|
}
|
|
}
|
|
|
|
// ===== Lobby & Match Data Structures =====
|
|
public sealed class Lobby
|
|
{
|
|
public string Id { get; set; } = "";
|
|
public LobbyPhase Phase { get; set; } = LobbyPhase.Waiting;
|
|
public int CountdownSeconds { get; set; }
|
|
public DateTime CreatedAt { get; set; }
|
|
public Dictionary<ulong, LobbyPlayer> Players { get; } = new();
|
|
}
|
|
|
|
public sealed class LobbyPlayer
|
|
{
|
|
public ulong AccountId { get; set; }
|
|
public string Name { get; set; } = "";
|
|
public bool Ready { get; set; }
|
|
public IConnection Connection { get; set; } = null!;
|
|
}
|
|
|
|
public enum LobbyPhase
|
|
{
|
|
Waiting,
|
|
Countdown,
|
|
Starting
|
|
}
|
|
|
|
public sealed class MatchInstance
|
|
{
|
|
public string Id { get; set; } = "";
|
|
public GameSimulation Simulation { get; set; } = null!;
|
|
public DateTime StartedAt { get; set; }
|
|
public Dictionary<ulong, IConnection> Connections { get; } = new();
|
|
}
|