From 841b241ef28acaf570d4eedd9a5fa12c6762ffab Mon Sep 17 00:00:00 2001 From: dingo Date: Thu, 4 Dec 2025 08:43:10 -0500 Subject: [PATCH] Stats --- Game/GameHandler.cs | 262 +++++-- Game/GameSimulation.cs | 200 ++++-- ...4134242_AddVoidScavengersStats.Designer.cs | 658 ++++++++++++++++++ .../20251204134242_AddVoidScavengersStats.cs | 123 ++++ Migrations/GameDbContextModelSnapshot.cs | 177 +++++ data/GameDbContext.cs | 2 + data/entities/MatchHistory.cs | 76 ++ data/entities/PlayerStats.cs | 67 ++ 8 files changed, 1450 insertions(+), 115 deletions(-) create mode 100644 Migrations/20251204134242_AddVoidScavengersStats.Designer.cs create mode 100644 Migrations/20251204134242_AddVoidScavengersStats.cs create mode 100644 data/entities/MatchHistory.cs create mode 100644 data/entities/PlayerStats.cs diff --git a/Game/GameHandler.cs b/Game/GameHandler.cs index f4d8788..abbf408 100644 --- a/Game/GameHandler.cs +++ b/Game/GameHandler.cs @@ -1,6 +1,8 @@ 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; @@ -66,35 +68,35 @@ public sealed class GameHandler : IClientMessageHandler 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; @@ -110,12 +112,12 @@ public sealed class GameHandler : IClientMessageHandler private async Task HandleLobbyJoinAsync(IConnection conn, ulong accountId, ReadOnlyMemory payload, CancellationToken ct) { var request = _ser.Deserialize(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); } @@ -135,7 +137,7 @@ public sealed class GameHandler : IClientMessageHandler { var input = _ser.Deserialize(payload); if (input == null) return Task.CompletedTask; - + _matchManager.EnqueueInput(accountId, new PlayerInput { PlayerId = accountId, @@ -145,7 +147,7 @@ public sealed class GameHandler : IClientMessageHandler AimAngle = input.AimAngle, Seq = input.Seq }); - + return Task.CompletedTask; } @@ -153,7 +155,7 @@ public sealed class GameHandler : IClientMessageHandler { var input = _ser.Deserialize(payload); if (input == null) return Task.CompletedTask; - + _matchManager.EnqueueInput(accountId, new PlayerInput { PlayerId = accountId, @@ -161,21 +163,21 @@ public sealed class GameHandler : IClientMessageHandler AimAngle = input.AimAngle, Seq = input.Seq }); - + return Task.CompletedTask; } private Task HandleActionInputAsync(IConnection conn, ulong accountId, ReadOnlyMemory payload, CancellationToken ct) { var input = _ser.Deserialize(payload); - + _matchManager.EnqueueInput(accountId, new PlayerInput { PlayerId = accountId, Type = InputType.Action, TargetId = input?.TargetId }); - + return Task.CompletedTask; } @@ -183,14 +185,14 @@ public sealed class GameHandler : IClientMessageHandler { var input = _ser.Deserialize(payload); if (input == null) return Task.CompletedTask; - + _matchManager.EnqueueInput(accountId, new PlayerInput { PlayerId = accountId, Type = InputType.Craft, TargetId = input.RecipeId }); - + return Task.CompletedTask; } @@ -198,14 +200,14 @@ public sealed class GameHandler : IClientMessageHandler { var input = _ser.Deserialize(payload); if (input == null) return Task.CompletedTask; - + _matchManager.EnqueueInput(accountId, new PlayerInput { PlayerId = accountId, Type = InputType.Drop, TargetId = input.SlotIndex }); - + return Task.CompletedTask; } @@ -213,11 +215,11 @@ public sealed class GameHandler : IClientMessageHandler { var msg = _ser.Deserialize(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); } @@ -257,20 +259,20 @@ public static class GameOpCodes 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; @@ -279,7 +281,7 @@ public static class GameOpCodes 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; @@ -292,28 +294,30 @@ public sealed class MatchManager : IDisposable { private readonly ILogger _log; private readonly IMessageSerializer _ser; - + private readonly IServiceScopeFactory _scopeFactory; + private readonly ConcurrentDictionary _lobbies = new(); private readonly ConcurrentDictionary _matches = new(); private readonly ConcurrentDictionary _playerToLobby = new(); private readonly ConcurrentDictionary _playerToMatch = new(); private readonly ConcurrentDictionary _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 log, IMessageSerializer ser) + public MatchManager(ILogger 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); } @@ -322,7 +326,7 @@ public sealed class MatchManager : IDisposable { // Remove from any existing lobby await LeaveLobbyAsync(accountId); - + // Find or create lobby Lobby? lobby = null; foreach (var l in _lobbies.Values) @@ -352,16 +356,16 @@ public sealed class MatchManager : IDisposable 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); } @@ -372,7 +376,7 @@ public sealed class MatchManager : IDisposable if (_lobbies.TryGetValue(lobbyId, out var lobby)) { lobby.Players.Remove(accountId); - + // Clean up empty lobbies if (lobby.Players.Count == 0) { @@ -391,7 +395,7 @@ public sealed class MatchManager : IDisposable } } } - + _playerConnections.TryRemove(accountId, out _); } @@ -400,12 +404,12 @@ public sealed class MatchManager : IDisposable 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 && + if (lobby.Players.Count >= MinPlayersToStart && lobby.Players.Values.All(p => p.Ready) && lobby.Phase == LobbyPhase.Waiting) { @@ -424,7 +428,7 @@ public sealed class MatchManager : IDisposable { if (!_playerToMatch.TryGetValue(accountId, out var matchId)) return; if (!_matches.TryGetValue(matchId, out var match)) return; - + match.Simulation.EnqueueInput(accountId, input); } @@ -435,7 +439,7 @@ public sealed class MatchManager : IDisposable Dictionary? targets = null; string? senderName = null; - if (_playerToMatch.TryGetValue(senderId, out var matchId) && + if (_playerToMatch.TryGetValue(senderId, out var matchId) && _matches.TryGetValue(matchId, out var match)) { targets = match.Connections; @@ -457,10 +461,10 @@ public sealed class MatchManager : IDisposable 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 @@ -478,11 +482,11 @@ public sealed class MatchManager : IDisposable if (lobby.Phase == LobbyPhase.Countdown) { lobby.CountdownSeconds--; - + // Broadcast countdown - await BroadcastToLobbyAsync(lobby, GameOpCodes.LOBBY_COUNTDOWN, + await BroadcastToLobbyAsync(lobby, GameOpCodes.LOBBY_COUNTDOWN, new { seconds = lobby.CountdownSeconds }); - + if (lobby.CountdownSeconds <= 0) { // Start the match! @@ -495,11 +499,11 @@ public sealed class MatchManager : IDisposable 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, @@ -513,27 +517,27 @@ public sealed class MatchManager : IDisposable { 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); @@ -543,7 +547,7 @@ public sealed class MatchManager : IDisposable _log.LogWarning(ex, "Failed to send GAME_START to {AccountId}", accountId); } } - + _log.LogInformation("Match {MatchId} started with {PlayerCount} players", matchId, match.Connections.Count); } @@ -611,18 +615,18 @@ public sealed class MatchManager : IDisposable 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) { @@ -635,7 +639,7 @@ public sealed class MatchManager : IDisposable private async Task BroadcastGameStateAsync(MatchInstance match) { var sim = match.Simulation; - + var state = new { tick = sim.CurrentTick, @@ -676,10 +680,10 @@ public sealed class MatchManager : IDisposable 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 @@ -704,12 +708,12 @@ public sealed class MatchManager : IDisposable 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 @@ -722,14 +726,128 @@ public sealed class MatchManager : IDisposable 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", match.Id); + _log.LogInformation("Match {MatchId} ended with {PlayerCount} players", match.Id, results.Count); + } + + private async Task PersistMatchResultsAsync(string matchId, List results) + { + using var scope = _scopeFactory.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + 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) @@ -746,7 +864,7 @@ public sealed class MatchManager : IDisposable ready = p.Ready }).ToArray() }; - + await BroadcastToLobbyAsync(lobby, GameOpCodes.LOBBY_STATE, state); } @@ -754,7 +872,7 @@ public sealed class MatchManager : IDisposable { var payload = _ser.Serialize(data); var wire = _ser.Serialize(new ServerMessage(opCode, payload)); - + foreach (var player in lobby.Players.Values) { try diff --git a/Game/GameSimulation.cs b/Game/GameSimulation.cs index 07c4161..726634f 100644 --- a/Game/GameSimulation.cs +++ b/Game/GameSimulation.cs @@ -15,7 +15,7 @@ public sealed class GameSimulation public long CurrentTick { get; private set; } public GamePhase Phase { get; private set; } = GamePhase.WaitingForPlayers; public float TimeRemaining { get; private set; } - + private readonly Random _rng; private readonly Dictionary _players = new(); private readonly Dictionary _asteroids = new(); @@ -23,13 +23,13 @@ public sealed class GameSimulation private readonly Dictionary _droppedItems = new(); private readonly Dictionary _projectiles = new(); private readonly Dictionary _extractionZones = new(); - + private readonly ConcurrentQueue _inputQueue = new(); private readonly List _pendingEvents = new(); - + private int _nextEntityId = 1; private int _nextProjectileId = 1; - + // Game constants public const float TickRate = 20f; // 20 ticks per second public const float TickDelta = 1f / TickRate; @@ -48,7 +48,7 @@ public sealed class GameSimulation MapHeight = height; _rng = new Random(seed); TimeRemaining = MatchDuration; - + GenerateMap(); } @@ -75,7 +75,7 @@ public sealed class GameSimulation { var typeRoll = _rng.NextDouble(); int resourceType = typeRoll < 0.6 ? 0 : (typeRoll < 0.9 ? 1 : 2); // 60% scrap, 30% energy, 10% rare - + var resource = new ResourceNode { Id = _nextEntityId++, @@ -103,7 +103,7 @@ public sealed class GameSimulation (MapWidth * 0.5f, MapHeight * 0.1f), (MapWidth * 0.5f, MapHeight * 0.9f) }; - + for (int i = 0; i < zonePositions.Length; i++) { var zone = new ExtractionZone @@ -126,7 +126,7 @@ public sealed class GameSimulation float spawnRadius = Math.Min(MapWidth, MapHeight) * 0.35f; float centerX = MapWidth / 2; float centerY = MapHeight / 2; - + return new Vector2( centerX + (float)Math.Cos(angle) * spawnRadius, centerY + (float)Math.Sin(angle) * spawnRadius @@ -188,7 +188,7 @@ public sealed class GameSimulation public List Tick() { if (Phase != GamePhase.InProgress) return new List(); - + _pendingEvents.Clear(); CurrentTick++; TimeRemaining -= TickDelta; @@ -203,7 +203,7 @@ public sealed class GameSimulation UpdatePlayers(); UpdateProjectiles(); UpdateExtractionZones(); - + // Check win conditions CheckEndConditions(); @@ -250,7 +250,7 @@ public sealed class GameSimulation // Apply movement float dx = player.InputDx * player.Speed * TickDelta; float dy = player.InputDy * player.Speed * TickDelta; - + float newX = player.X + dx; float newY = player.Y + dy; @@ -258,7 +258,7 @@ public sealed class GameSimulation bool blocked = false; foreach (var asteroid in _asteroids.Values) { - float distSq = (newX - asteroid.X) * (newX - asteroid.X) + + float distSq = (newX - asteroid.X) * (newX - asteroid.X) + (newY - asteroid.Y) * (newY - asteroid.Y); float minDist = PlayerRadius + asteroid.Radius; if (distSq < minDist * minDist) @@ -284,13 +284,13 @@ public sealed class GameSimulation // Check resource pickup CheckResourcePickup(player); - + // Check dropped item pickup CheckDroppedItemPickup(player); - + // Update extraction progress UpdateExtraction(player); - + // Clear input for next tick player.InputDx = 0; player.InputDy = 0; @@ -302,28 +302,29 @@ public sealed class GameSimulation foreach (var resource in _resources.Values.ToList()) { if (resource.Amount <= 0) continue; - + float distSq = (player.X - resource.X) * (player.X - resource.X) + (player.Y - resource.Y) * (player.Y - resource.Y); - + if (distSq < PickupRadius * PickupRadius) { int amount = resource.Amount; switch (resource.ResourceType) { - case 0: player.Scrap += amount; break; - case 1: player.Energy += amount; break; - case 2: player.Rare += amount; break; + case 0: player.Scrap += amount; player.TotalScrapCollected += amount; break; + case 1: player.Energy += amount; player.TotalEnergyCollected += amount; break; + case 2: player.Rare += amount; player.TotalRareCollected += amount; break; } - - resource.Amount = 0; - + + // Remove the resource node entirely + _resources.Remove(resource.Id); + _pendingEvents.Add(new GameEvent { Type = EventType.Pickup, PlayerId = player.Id, TargetId = resource.Id, - Data = new { resourceType = resource.ResourceType, amount } + Data = new { resourceType = resource.ResourceType, amount, removed = true } }); } } @@ -335,7 +336,7 @@ public sealed class GameSimulation { float distSq = (player.X - drop.X) * (player.X - drop.X) + (player.Y - drop.Y) * (player.Y - drop.Y); - + if (distSq < PickupRadius * PickupRadius) { // Try to add to inventory @@ -388,15 +389,15 @@ public sealed class GameSimulation foreach (var zone in _extractionZones.Values) { if (!zone.Active) continue; - + float distSq = (player.X - zone.X) * (player.X - zone.X) + (player.Y - zone.Y) * (player.Y - zone.Y); - + if (distSq < zone.Radius * zone.Radius) { inZone = true; player.ExtractionProgress += TickDelta; - + if (player.ExtractionProgress >= ExtractionTime) { // Player extracts! @@ -416,7 +417,8 @@ public sealed class GameSimulation { player.Alive = false; player.Extracted = true; - + player.ExtractedAtTick = CurrentTick; + // Calculate total loot value int totalValue = player.Scrap * 1 + player.Energy * 2 + player.Rare * 5; foreach (var itemId in player.Inventory) @@ -445,7 +447,7 @@ public sealed class GameSimulation // Check fire rate cooldown float cooldown = 1f / weapon.FireRate; if (CurrentTick - player.LastShotTick < cooldown * TickRate) return; - + player.LastShotTick = CurrentTick; // Create projectile(s) @@ -454,7 +456,7 @@ public sealed class GameSimulation { float spread = pellets > 1 ? (float)(_rng.NextDouble() - 0.5) * weapon.Spread : 0; float finalAngle = angle + spread; - + var proj = new Projectile { Id = _nextProjectileId++, @@ -486,7 +488,7 @@ public sealed class GameSimulation float dx = proj.VelX * TickDelta; float dy = proj.VelY * TickDelta; float moveDist = MathF.Sqrt(dx * dx + dy * dy); - + proj.X += dx; proj.Y += dy; proj.DistanceTraveled += moveDist; @@ -528,10 +530,10 @@ public sealed class GameSimulation foreach (var target in _players.Values) { if (target.Id == proj.OwnerId || !target.Alive) continue; - + float distSq = (proj.X - target.X) * (proj.X - target.X) + (proj.Y - target.Y) * (proj.Y - target.Y); - + if (distSq < PlayerRadius * PlayerRadius) { if (proj.ExplosionRadius > 0) @@ -566,7 +568,7 @@ public sealed class GameSimulation foreach (var target in _players.Values) { if (!target.Alive) continue; - + float distSq = (x - target.X) * (x - target.X) + (y - target.Y) * (y - target.Y); if (distSq < radius * radius) { @@ -585,7 +587,14 @@ public sealed class GameSimulation private void DealDamage(PlayerEntity target, int damage, ulong? sourceId) { target.Health -= damage; - + target.DamageTaken += damage; + + // Track damage dealt by source + if (sourceId.HasValue && _players.TryGetValue(sourceId.Value, out var source)) + { + source.DamageDealt += damage; + } + _pendingEvents.Add(new GameEvent { Type = EventType.Damage, @@ -604,9 +613,10 @@ public sealed class GameSimulation { player.Alive = false; player.Health = 0; - + player.DiedAtTick = CurrentTick; + var drops = DropPlayerLoot(player); - + string? killerName = null; if (killerId.HasValue && _players.TryGetValue(killerId.Value, out var killer)) { @@ -695,7 +705,7 @@ public sealed class GameSimulation if (recipe == null) return; var (scrapCost, energyCost, rareCost) = recipe.GetCost(); - + if (player.Scrap < scrapCost || player.Energy < energyCost || player.Rare < rareCost) return; @@ -813,7 +823,7 @@ public sealed class GameSimulation if (Phase != GamePhase.InProgress) return; int alivePlayers = _players.Values.Count(p => p.Alive); - + // Time expired if (TimeRemaining <= 0) { @@ -864,6 +874,98 @@ public sealed class GameSimulation public IReadOnlyDictionary DroppedItems => _droppedItems; public IReadOnlyDictionary Projectiles => _projectiles; public IReadOnlyDictionary ExtractionZones => _extractionZones; + + /// + /// Gets match results for all players, sorted by placement + /// + public List GetMatchResults() + { + var results = new List(); + int totalPlayers = _players.Count; + int matchDurationSeconds = (int)(MatchDuration - TimeRemaining); + + // Calculate placements based on: extracted > alive > death order + var sortedPlayers = _players.Values + .OrderByDescending(p => p.Extracted) + .ThenByDescending(p => p.Alive) + .ThenByDescending(p => p.DiedAtTick == 0 ? long.MaxValue : p.DiedAtTick) + .ThenByDescending(p => p.Kills) + .ToList(); + + for (int i = 0; i < sortedPlayers.Count; i++) + { + var p = sortedPlayers[i]; + int placement = i + 1; + + // Determine result + MatchPlayerResultType resultType; + if (p.Extracted) + resultType = MatchPlayerResultType.Extracted; + else if (p.Alive && placement == 1) + resultType = MatchPlayerResultType.Won; + else + resultType = MatchPlayerResultType.Lost; + + // Calculate survival time + int survivalSeconds; + if (p.Extracted) + survivalSeconds = (int)(p.ExtractedAtTick / TickRate); + else if (!p.Alive && p.DiedAtTick > 0) + survivalSeconds = (int)(p.DiedAtTick / TickRate); + else + survivalSeconds = matchDurationSeconds; + + results.Add(new MatchPlayerResult + { + AccountId = p.Id, + PlayerName = p.Name, + Placement = placement, + TotalPlayers = totalPlayers, + Result = resultType, + Kills = p.Kills, + Deaths = p.Deaths, + DamageDealt = p.DamageDealt, + DamageTaken = p.DamageTaken, + ScrapCollected = p.TotalScrapCollected, + EnergyCollected = p.TotalEnergyCollected, + RareCollected = p.TotalRareCollected, + ItemsCrafted = p.ItemsCrafted, + SurvivalTimeSeconds = survivalSeconds, + MatchDurationSeconds = matchDurationSeconds + }); + } + + return results; + } +} + +/// +/// Result data for a single player in a match +/// +public sealed class MatchPlayerResult +{ + public ulong AccountId { get; set; } + public string PlayerName { get; set; } = ""; + public int Placement { get; set; } + public int TotalPlayers { get; set; } + public MatchPlayerResultType Result { get; set; } + public int Kills { get; set; } + public int Deaths { get; set; } + public int DamageDealt { get; set; } + public int DamageTaken { get; set; } + public int ScrapCollected { get; set; } + public int EnergyCollected { get; set; } + public int RareCollected { get; set; } + public int ItemsCrafted { get; set; } + public int SurvivalTimeSeconds { get; set; } + public int MatchDurationSeconds { get; set; } +} + +public enum MatchPlayerResultType +{ + Lost, + Won, + Extracted } // ===== Entity Classes ===== @@ -879,22 +981,34 @@ public sealed class PlayerEntity public float Speed { get; set; } public bool Alive { get; set; } public bool Extracted { get; set; } - + public int Scrap { get; set; } public int Energy { get; set; } public int Rare { get; set; } public int?[] Inventory { get; set; } = new int?[6]; public int? EquippedWeaponId { get; set; } - + public float InputDx { get; set; } public float InputDy { get; set; } public long LastShotTick { get; set; } public float ExtractionProgress { get; set; } - + + // Match statistics public int Kills { get; set; } public int Deaths { get; set; } public int DamageDealt { get; set; } + public int DamageTaken { get; set; } public int ItemsCrafted { get; set; } + + // Lifetime resource tracking (for this match) + public int TotalScrapCollected { get; set; } + public int TotalEnergyCollected { get; set; } + public int TotalRareCollected { get; set; } + + // Time tracking + public long JoinedAtTick { get; set; } + public long DiedAtTick { get; set; } + public long ExtractedAtTick { get; set; } } public sealed class Asteroid diff --git a/Migrations/20251204134242_AddVoidScavengersStats.Designer.cs b/Migrations/20251204134242_AddVoidScavengersStats.Designer.cs new file mode 100644 index 0000000..08e8397 --- /dev/null +++ b/Migrations/20251204134242_AddVoidScavengersStats.Designer.cs @@ -0,0 +1,658 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Server.Data; + +#nullable disable + +namespace SystemRevivalServer.Migrations +{ + [DbContext(typeof(GameDbContext))] + [Migration("20251204134242_AddVoidScavengersStats")] + partial class AddVoidScavengersStats + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + MySqlModelBuilderExtensions.AutoIncrementColumns(modelBuilder); + + modelBuilder.Entity("Server.Data.Account", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("BannedUntil") + .HasColumnType("datetime(6)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("Email") + .HasMaxLength(255) + .HasColumnType("varchar(255)"); + + b.Property("IsBanned") + .HasColumnType("tinyint(1)"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("varbinary(64)"); + + b.Property("PasswordSalt") + .IsRequired() + .HasColumnType("varbinary(32)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.HasKey("Id"); + + b.HasIndex("Email") + .IsUnique(); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("accounts", (string)null); + }); + + modelBuilder.Entity("Server.Data.Character", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AccountId") + .HasColumnType("bigint unsigned"); + + b.Property("AppearanceJson") + .HasColumnType("json"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("FacingDeg") + .HasColumnType("float"); + + b.Property("HpCurrent") + .HasColumnType("int unsigned"); + + b.Property("HpMax") + .HasColumnType("int unsigned"); + + b.Property("Level") + .HasColumnType("int unsigned"); + + b.Property("MpCurrent") + .HasColumnType("int unsigned"); + + b.Property("MpMax") + .HasColumnType("int unsigned"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("PosX") + .HasColumnType("double"); + + b.Property("PosY") + .HasColumnType("double"); + + b.Property("PosZ") + .HasColumnType("double"); + + b.Property("StaminaCurrent") + .HasColumnType("int unsigned"); + + b.Property("StaminaMax") + .HasColumnType("int unsigned"); + + b.Property("StatDexterity") + .HasColumnType("int unsigned"); + + b.Property("StatEndurance") + .HasColumnType("int unsigned"); + + b.Property("StatIntelligence") + .HasColumnType("int unsigned"); + + b.Property("StatStrength") + .HasColumnType("int unsigned"); + + b.Property("StatWisdom") + .HasColumnType("int unsigned"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.Property("Xp") + .HasColumnType("bigint unsigned"); + + b.Property("ZoneId") + .HasColumnType("bigint unsigned"); + + b.HasKey("Id"); + + b.HasIndex("AccountId") + .IsUnique(); + + b.HasIndex("ZoneId"); + + b.ToTable("characters", (string)null); + }); + + modelBuilder.Entity("Server.Data.EquipmentSlot", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CharacterId") + .HasColumnType("bigint unsigned"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("ItemTemplateId") + .HasColumnType("bigint unsigned"); + + b.Property("SlotCode") + .HasColumnType("tinyint unsigned"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("ItemTemplateId"); + + b.HasIndex("CharacterId", "SlotCode") + .IsUnique(); + + b.ToTable("equipment", (string)null); + }); + + modelBuilder.Entity("Server.Data.InventoryItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CharacterId") + .HasColumnType("bigint unsigned"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("ItemTemplateId") + .HasColumnType("bigint unsigned"); + + b.Property("Quantity") + .HasColumnType("int unsigned"); + + b.Property("SlotIndex") + .HasColumnType("int unsigned"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("CharacterId"); + + b.HasIndex("ItemTemplateId"); + + b.HasIndex("CharacterId", "SlotIndex") + .IsUnique(); + + b.ToTable("inventories", (string)null); + }); + + modelBuilder.Entity("Server.Data.ItemTemplate", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("ItemType") + .HasColumnType("tinyint unsigned"); + + b.Property("MaxStack") + .HasColumnType("int unsigned"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("Rarity") + .HasColumnType("tinyint unsigned"); + + b.Property("StatsJson") + .HasColumnType("json"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.Property("Weight") + .HasColumnType("int unsigned"); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("item_templates", (string)null); + }); + + modelBuilder.Entity("Server.Data.MatchHistory", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AccountId") + .HasColumnType("bigint unsigned"); + + b.Property("DamageDealt") + .HasColumnType("int"); + + b.Property("DamageTaken") + .HasColumnType("int"); + + b.Property("Deaths") + .HasColumnType("int"); + + b.Property("EloAfter") + .HasColumnType("int"); + + b.Property("EloChange") + .HasColumnType("int"); + + b.Property("EnergyCollected") + .HasColumnType("int"); + + b.Property("ItemsCrafted") + .HasColumnType("int"); + + b.Property("Kills") + .HasColumnType("int"); + + b.Property("MatchDurationSeconds") + .HasColumnType("int"); + + b.Property("MatchId") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Placement") + .HasColumnType("int"); + + b.Property("PlayedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("RareCollected") + .HasColumnType("int"); + + b.Property("Result") + .HasColumnType("int"); + + b.Property("ScrapCollected") + .HasColumnType("int"); + + b.Property("SurvivalTimeSeconds") + .HasColumnType("int"); + + b.Property("TotalPlayers") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("AccountId"); + + b.HasIndex("MatchId"); + + b.HasIndex("PlayedAt"); + + b.ToTable("match_history", (string)null); + }); + + modelBuilder.Entity("Server.Data.PlayerStats", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AccountId") + .HasColumnType("bigint unsigned"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("Deaths") + .HasColumnType("int"); + + b.Property("Elo") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1000); + + b.Property("Extractions") + .HasColumnType("int"); + + b.Property("ItemsCrafted") + .HasColumnType("int"); + + b.Property("Kills") + .HasColumnType("int"); + + b.Property("LongestSurvivalSeconds") + .HasColumnType("int"); + + b.Property("Losses") + .HasColumnType("int"); + + b.Property("MatchesPlayed") + .HasColumnType("int"); + + b.Property("TotalDamageDealt") + .HasColumnType("bigint"); + + b.Property("TotalDamageTaken") + .HasColumnType("bigint"); + + b.Property("TotalEnergyCollected") + .HasColumnType("bigint"); + + b.Property("TotalPlayTimeSeconds") + .HasColumnType("bigint"); + + b.Property("TotalRareCollected") + .HasColumnType("bigint"); + + b.Property("TotalScrapCollected") + .HasColumnType("bigint"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.Property("Wins") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("AccountId") + .IsUnique(); + + b.ToTable("player_stats", (string)null); + }); + + modelBuilder.Entity("Server.Data.Session", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AccountId") + .HasColumnType("bigint unsigned"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("CreatedIp") + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("ExpiresAt") + .HasColumnType("datetime(6)"); + + b.Property("RevokedAt") + .HasColumnType("datetime(6)"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("varchar(128)"); + + b.Property("UserAgent") + .HasMaxLength(256) + .HasColumnType("varchar(256)"); + + b.HasKey("Id"); + + b.HasIndex("AccountId"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("sessions", (string)null); + }); + + modelBuilder.Entity("Server.Data.Zone", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("MaxX") + .HasColumnType("double"); + + b.Property("MaxY") + .HasColumnType("double"); + + b.Property("MaxZ") + .HasColumnType("double"); + + b.Property("MinX") + .HasColumnType("double"); + + b.Property("MinY") + .HasColumnType("double"); + + b.Property("MinZ") + .HasColumnType("double"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.HasKey("Id"); + + b.HasIndex("Name") + .IsUnique(); + + b.ToTable("zones", (string)null); + }); + + modelBuilder.Entity("Server.Data.Character", b => + { + b.HasOne("Server.Data.Account", "Account") + .WithMany("Characters") + .HasForeignKey("AccountId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Server.Data.Zone", "Zone") + .WithMany() + .HasForeignKey("ZoneId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Account"); + + b.Navigation("Zone"); + }); + + modelBuilder.Entity("Server.Data.EquipmentSlot", b => + { + b.HasOne("Server.Data.Character", "Character") + .WithMany() + .HasForeignKey("CharacterId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Server.Data.ItemTemplate", "ItemTemplate") + .WithMany() + .HasForeignKey("ItemTemplateId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Character"); + + b.Navigation("ItemTemplate"); + }); + + modelBuilder.Entity("Server.Data.InventoryItem", b => + { + b.HasOne("Server.Data.Character", "Character") + .WithMany() + .HasForeignKey("CharacterId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Server.Data.ItemTemplate", "ItemTemplate") + .WithMany() + .HasForeignKey("ItemTemplateId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Character"); + + b.Navigation("ItemTemplate"); + }); + + modelBuilder.Entity("Server.Data.MatchHistory", b => + { + b.HasOne("Server.Data.Account", "Account") + .WithMany() + .HasForeignKey("AccountId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Account"); + }); + + modelBuilder.Entity("Server.Data.PlayerStats", b => + { + b.HasOne("Server.Data.Account", "Account") + .WithOne() + .HasForeignKey("Server.Data.PlayerStats", "AccountId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Account"); + }); + + modelBuilder.Entity("Server.Data.Session", b => + { + b.HasOne("Server.Data.Account", "Account") + .WithMany("Sessions") + .HasForeignKey("AccountId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Account"); + }); + + modelBuilder.Entity("Server.Data.Account", b => + { + b.Navigation("Characters"); + + b.Navigation("Sessions"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Migrations/20251204134242_AddVoidScavengersStats.cs b/Migrations/20251204134242_AddVoidScavengersStats.cs new file mode 100644 index 0000000..668267e --- /dev/null +++ b/Migrations/20251204134242_AddVoidScavengersStats.cs @@ -0,0 +1,123 @@ +using System; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SystemRevivalServer.Migrations +{ + /// + public partial class AddVoidScavengersStats : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "match_history", + columns: table => new + { + Id = table.Column(type: "bigint unsigned", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + MatchId = table.Column(type: "varchar(32)", maxLength: 32, nullable: false) + .Annotation("MySql:CharSet", "utf8mb4"), + AccountId = table.Column(type: "bigint unsigned", nullable: false), + Result = table.Column(type: "int", nullable: false), + Placement = table.Column(type: "int", nullable: false), + TotalPlayers = table.Column(type: "int", nullable: false), + Kills = table.Column(type: "int", nullable: false), + Deaths = table.Column(type: "int", nullable: false), + DamageDealt = table.Column(type: "int", nullable: false), + DamageTaken = table.Column(type: "int", nullable: false), + ScrapCollected = table.Column(type: "int", nullable: false), + EnergyCollected = table.Column(type: "int", nullable: false), + RareCollected = table.Column(type: "int", nullable: false), + ItemsCrafted = table.Column(type: "int", nullable: false), + SurvivalTimeSeconds = table.Column(type: "int", nullable: false), + MatchDurationSeconds = table.Column(type: "int", nullable: false), + EloChange = table.Column(type: "int", nullable: false), + EloAfter = table.Column(type: "int", nullable: false), + PlayedAt = table.Column(type: "datetime(6)", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP(6)") + }, + constraints: table => + { + table.PrimaryKey("PK_match_history", x => x.Id); + table.ForeignKey( + name: "FK_match_history_accounts_AccountId", + column: x => x.AccountId, + principalTable: "accounts", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateTable( + name: "player_stats", + columns: table => new + { + Id = table.Column(type: "bigint unsigned", nullable: false) + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn), + AccountId = table.Column(type: "bigint unsigned", nullable: false), + MatchesPlayed = table.Column(type: "int", nullable: false), + Wins = table.Column(type: "int", nullable: false), + Losses = table.Column(type: "int", nullable: false), + Extractions = table.Column(type: "int", nullable: false), + Kills = table.Column(type: "int", nullable: false), + Deaths = table.Column(type: "int", nullable: false), + TotalDamageDealt = table.Column(type: "bigint", nullable: false), + TotalDamageTaken = table.Column(type: "bigint", nullable: false), + TotalScrapCollected = table.Column(type: "bigint", nullable: false), + TotalEnergyCollected = table.Column(type: "bigint", nullable: false), + TotalRareCollected = table.Column(type: "bigint", nullable: false), + ItemsCrafted = table.Column(type: "int", nullable: false), + TotalPlayTimeSeconds = table.Column(type: "bigint", nullable: false), + LongestSurvivalSeconds = table.Column(type: "int", nullable: false), + Elo = table.Column(type: "int", nullable: false, defaultValue: 1000), + CreatedAt = table.Column(type: "datetime(6)", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP(6)"), + UpdatedAt = table.Column(type: "datetime(6)", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP(6)") + .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.ComputedColumn) + }, + constraints: table => + { + table.PrimaryKey("PK_player_stats", x => x.Id); + table.ForeignKey( + name: "FK_player_stats_accounts_AccountId", + column: x => x.AccountId, + principalTable: "accounts", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }) + .Annotation("MySql:CharSet", "utf8mb4"); + + migrationBuilder.CreateIndex( + name: "IX_match_history_AccountId", + table: "match_history", + column: "AccountId"); + + migrationBuilder.CreateIndex( + name: "IX_match_history_MatchId", + table: "match_history", + column: "MatchId"); + + migrationBuilder.CreateIndex( + name: "IX_match_history_PlayedAt", + table: "match_history", + column: "PlayedAt"); + + migrationBuilder.CreateIndex( + name: "IX_player_stats_AccountId", + table: "player_stats", + column: "AccountId", + unique: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "match_history"); + + migrationBuilder.DropTable( + name: "player_stats"); + } + } +} diff --git a/Migrations/GameDbContextModelSnapshot.cs b/Migrations/GameDbContextModelSnapshot.cs index e20f297..100842e 100644 --- a/Migrations/GameDbContextModelSnapshot.cs +++ b/Migrations/GameDbContextModelSnapshot.cs @@ -302,6 +302,161 @@ namespace SystemRevivalServer.Migrations b.ToTable("item_templates", (string)null); }); + modelBuilder.Entity("Server.Data.MatchHistory", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AccountId") + .HasColumnType("bigint unsigned"); + + b.Property("DamageDealt") + .HasColumnType("int"); + + b.Property("DamageTaken") + .HasColumnType("int"); + + b.Property("Deaths") + .HasColumnType("int"); + + b.Property("EloAfter") + .HasColumnType("int"); + + b.Property("EloChange") + .HasColumnType("int"); + + b.Property("EnergyCollected") + .HasColumnType("int"); + + b.Property("ItemsCrafted") + .HasColumnType("int"); + + b.Property("Kills") + .HasColumnType("int"); + + b.Property("MatchDurationSeconds") + .HasColumnType("int"); + + b.Property("MatchId") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("varchar(32)"); + + b.Property("Placement") + .HasColumnType("int"); + + b.Property("PlayedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("RareCollected") + .HasColumnType("int"); + + b.Property("Result") + .HasColumnType("int"); + + b.Property("ScrapCollected") + .HasColumnType("int"); + + b.Property("SurvivalTimeSeconds") + .HasColumnType("int"); + + b.Property("TotalPlayers") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("AccountId"); + + b.HasIndex("MatchId"); + + b.HasIndex("PlayedAt"); + + b.ToTable("match_history", (string)null); + }); + + modelBuilder.Entity("Server.Data.PlayerStats", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("bigint unsigned"); + + MySqlPropertyBuilderExtensions.UseMySqlIdentityColumn(b.Property("Id")); + + b.Property("AccountId") + .HasColumnType("bigint unsigned"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + b.Property("Deaths") + .HasColumnType("int"); + + b.Property("Elo") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(1000); + + b.Property("Extractions") + .HasColumnType("int"); + + b.Property("ItemsCrafted") + .HasColumnType("int"); + + b.Property("Kills") + .HasColumnType("int"); + + b.Property("LongestSurvivalSeconds") + .HasColumnType("int"); + + b.Property("Losses") + .HasColumnType("int"); + + b.Property("MatchesPlayed") + .HasColumnType("int"); + + b.Property("TotalDamageDealt") + .HasColumnType("bigint"); + + b.Property("TotalDamageTaken") + .HasColumnType("bigint"); + + b.Property("TotalEnergyCollected") + .HasColumnType("bigint"); + + b.Property("TotalPlayTimeSeconds") + .HasColumnType("bigint"); + + b.Property("TotalRareCollected") + .HasColumnType("bigint"); + + b.Property("TotalScrapCollected") + .HasColumnType("bigint"); + + b.Property("UpdatedAt") + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("datetime(6)") + .HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + + MySqlPropertyBuilderExtensions.UseMySqlComputedColumn(b.Property("UpdatedAt")); + + b.Property("Wins") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("AccountId") + .IsUnique(); + + b.ToTable("player_stats", (string)null); + }); + modelBuilder.Entity("Server.Data.Session", b => { b.Property("Id") @@ -455,6 +610,28 @@ namespace SystemRevivalServer.Migrations b.Navigation("ItemTemplate"); }); + modelBuilder.Entity("Server.Data.MatchHistory", b => + { + b.HasOne("Server.Data.Account", "Account") + .WithMany() + .HasForeignKey("AccountId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Account"); + }); + + modelBuilder.Entity("Server.Data.PlayerStats", b => + { + b.HasOne("Server.Data.Account", "Account") + .WithOne() + .HasForeignKey("Server.Data.PlayerStats", "AccountId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Account"); + }); + modelBuilder.Entity("Server.Data.Session", b => { b.HasOne("Server.Data.Account", "Account") diff --git a/data/GameDbContext.cs b/data/GameDbContext.cs index b44abab..697b492 100644 --- a/data/GameDbContext.cs +++ b/data/GameDbContext.cs @@ -14,6 +14,8 @@ public sealed class GameDbContext : DbContext public DbSet ItemTemplates => Set(); public DbSet Inventory => Set(); public DbSet Equipment => Set(); + public DbSet PlayerStats => Set(); + public DbSet MatchHistory => Set(); protected override void OnModelCreating(ModelBuilder b) { diff --git a/data/entities/MatchHistory.cs b/data/entities/MatchHistory.cs new file mode 100644 index 0000000..6f15634 --- /dev/null +++ b/data/entities/MatchHistory.cs @@ -0,0 +1,76 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Server.Data; + +/// +/// Records individual match results for Void Scavengers +/// +public sealed class MatchHistory +{ + public ulong Id { get; set; } + public string MatchId { get; set; } = ""; // The game's match ID + public ulong AccountId { get; set; } + + // Result + public MatchResult Result { get; set; } + public int Placement { get; set; } // 1st, 2nd, etc. + public int TotalPlayers { get; set; } + + // Match performance + public int Kills { get; set; } + public int Deaths { get; set; } + public int DamageDealt { get; set; } + public int DamageTaken { get; set; } + + // Resources + public int ScrapCollected { get; set; } + public int EnergyCollected { get; set; } + public int RareCollected { get; set; } + public int ItemsCrafted { get; set; } + + // Time + public int SurvivalTimeSeconds { get; set; } + public int MatchDurationSeconds { get; set; } + + // Elo change + public int EloChange { get; set; } + public int EloAfter { get; set; } + + // Timestamp + public DateTime PlayedAt { get; set; } + + // Navigation + public Account Account { get; set; } = null!; +} + +public enum MatchResult +{ + Loss = 0, + Win = 1, + Extracted = 2, // Special win type + Disconnected = 3 +} + +public sealed class MatchHistoryConfig : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder e) + { + e.ToTable("match_history"); + e.HasKey(x => x.Id); + e.Property(x => x.Id).ValueGeneratedOnAdd(); + + e.HasIndex(x => x.AccountId); + e.HasIndex(x => x.MatchId); + e.HasIndex(x => x.PlayedAt); + + e.Property(x => x.MatchId).HasMaxLength(32).IsRequired(); + + e.HasOne(x => x.Account) + .WithMany() + .HasForeignKey(x => x.AccountId) + .OnDelete(DeleteBehavior.Cascade); + + e.Property(x => x.PlayedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + } +} diff --git a/data/entities/PlayerStats.cs b/data/entities/PlayerStats.cs new file mode 100644 index 0000000..5ff4173 --- /dev/null +++ b/data/entities/PlayerStats.cs @@ -0,0 +1,67 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Server.Data; + +/// +/// Tracks player statistics for Void Scavengers +/// +public sealed class PlayerStats +{ + public ulong Id { get; set; } + public ulong AccountId { get; set; } + + // Match stats + public int MatchesPlayed { get; set; } + public int Wins { get; set; } + public int Losses { get; set; } + public int Extractions { get; set; } // Successful extractions (counts as win) + + // Combat stats + public int Kills { get; set; } + public int Deaths { get; set; } + public long TotalDamageDealt { get; set; } + public long TotalDamageTaken { get; set; } + + // Resource stats + public long TotalScrapCollected { get; set; } + public long TotalEnergyCollected { get; set; } + public long TotalRareCollected { get; set; } + public int ItemsCrafted { get; set; } + + // Time stats + public long TotalPlayTimeSeconds { get; set; } + public int LongestSurvivalSeconds { get; set; } + + // Ratings + public int Elo { get; set; } = 1000; // Starting Elo rating + + // Timestamps + public DateTime CreatedAt { get; set; } + public DateTime UpdatedAt { get; set; } + + // Navigation + public Account Account { get; set; } = null!; +} + +public sealed class PlayerStatsConfig : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder e) + { + e.ToTable("player_stats"); + e.HasKey(x => x.Id); + e.Property(x => x.Id).ValueGeneratedOnAdd(); + + e.HasIndex(x => x.AccountId).IsUnique(); + + e.HasOne(x => x.Account) + .WithOne() + .HasForeignKey(x => x.AccountId) + .OnDelete(DeleteBehavior.Cascade); + + e.Property(x => x.Elo).HasDefaultValue(1000); + e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)"); + e.Property(x => x.UpdatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)") + .ValueGeneratedOnAddOrUpdate(); + } +}