Repository navigation
game shutdown lifecycle
The MakaMek game currently lacks a proper shutdown mechanism. When players navigate back to the menu from an active game:
-
Server continues running -
ServerGame.Start()loop keeps running in background - No client disconnect notification - Server is unaware when clients leave
- No cleanup before new game - Starting a new game doesn't properly clean up the previous one
- Resource leaks - Subscriptions, network connections, and background tasks are not disposed
1. GameManager (src/MakaMek.Core/Models/Game/GameManager.cs)
- Singleton service managing server game instance
- Owns
ServerGame,INetworkHostService, andICommandLogger -
InitializeLobby()creates server game and starts network host -
Dispose()cleans up server game and network host - Issue: Only disposed when application exits, not between games
2. ServerGame (src/MakaMek.Core/Models/Game/ServerGame.cs)
- Implements
IDisposable -
Start()method runs infinite loop:while (!_isDisposed && !_isGameOver) -
Dispose()sets flags to exit loop - Publishes server commands via
CommandPublisher - Issue: No mechanism to signal game end to clients
3. ClientGame (src/MakaMek.Core/Models/Game/ClientGame.cs)
- Receives and handles server commands
- Maintains
LocalPlayerslist - Subscribes to
CommandPublisherinBaseGameconstructor - Issue: No cleanup when leaving game, subscriptions remain active
4. ViewModels
-
StartNewGameViewModel: Creates lobby, initializes server -
BattleMapViewModel: Displays active game, hasBackToMenuCommand -
Issue:
BackToMenu()just navigates, doesn't clean up game state
Server → Client Commands:
-
ChangePhaseCommand- Phase transitions -
ChangeActivePlayerCommand- Active player changes -
TurnIncrementedCommand- Turn increments -
SetBattleMapCommand- Map initialization -
HeatUpdatedCommand,MechFallCommand, etc. - Game state updates
Client → Server Commands:
- All implement
IClientCommandinterface -
JoinGameCommand,DeployUnitCommand,MoveUnitCommand, etc.
Command Publisher/Subscriber Pattern:
-
CommandPublisher.Subscribe(Action<IGameCommand>)- Adds subscriber -
CommandPublisher.PublishCommand(IGameCommand)- Broadcasts to all -
Issue: No
Unsubscribe()method exists
Maintain Client-Server Separation: Clients communicate with server ONLY through commands, never direct method calls.
Create two new commands for the shutdown flow:
A. Client Command - PlayerLeftCommand
File: src/MakaMek.Core/Data/Game/Commands/Client/PlayerLeftCommand.cs
public record struct PlayerLeftCommand : IClientCommand
{
public required Guid GameOriginId { get; set; }
public DateTime Timestamp { get; set; }
public required Guid PlayerId { get; init; }
public string Render(ILocalizationService localizationService, IGame game)
{
var player = game.Players.FirstOrDefault(p => p.Id == PlayerId);
var playerName = player?.Name ?? "Unknown";
var localizedTemplate = localizationService.GetString("Command_PlayerLeft");
return string.Format(localizedTemplate, playerName);
}
}B. Server Command - GameEndedCommand
File: src/MakaMek.Core/Data/Game/Commands/Server/GameEndedCommand.cs
public record struct GameEndedCommand : IGameCommand
{
public required Guid GameOriginId { get; set; }
public DateTime Timestamp { get; set; }
public required GameEndReason Reason { get; init; }
public string Render(ILocalizationService localizationService, IGame game)
{
var key = $"Command_GameEnded_{Reason}";
return localizationService.GetString(key);
}
}
public enum GameEndReason
{
HostDisconnected,
GameAborted,
Victory,
AllPlayersLeft
}Add shutdown method to ServerGame that handles game termination:
File: src/MakaMek.Core/Models/Game/ServerGame.cs
public class ServerGame : BaseGame, IDisposable
{
// Existing fields...
/// <summary>
/// Stops the game and notifies all clients
/// </summary>
public void StopGame(GameEndReason reason)
{
if (_isDisposed || _isGameOver) return;
// 1. Publish GameEndedCommand to all clients
var endCommand = new GameEndedCommand
{
GameOriginId = Id,
Reason = reason,
Timestamp = DateTime.UtcNow
};
CommandPublisher.PublishCommand(endCommand);
// 2. Mark game as over (will exit Start() loop)
_isGameOver = true;
}
public override void HandleCommand(IGameCommand command)
{
if (!ShouldHandleCommand(command)) return;
switch (command)
{
// Existing cases...
case PlayerLeftCommand playerLeftCommand:
HandlePlayerLeft(playerLeftCommand);
break;
}
// Existing logic...
}
private void HandlePlayerLeft(PlayerLeftCommand command)
{
// Remove player from game
var player = Players.FirstOrDefault(p => p.Id == command.PlayerId);
if (player != null)
{
Players.Remove(player);
// Check if all players have left
if (Players.Count == 0)
{
StopGame(GameEndReason.AllPlayersLeft);
}
}
}
}Add unsubscribe capability:
File: src/MakaMek.Core/Services/Transport/ICommandPublisher.cs
public interface ICommandPublisher
{
void PublishCommand(IGameCommand command);
void Subscribe(Action<IGameCommand> onCommandReceived, ITransportPublisher? transportPublisher = null);
void Unsubscribe(Action<IGameCommand> onCommandReceived); // NEW
CommandTransportAdapter Adapter { get; }
}Implementation in CommandPublisher.cs:
public void Unsubscribe(Action<IGameCommand> onCommandReceived)
{
_subscribers.Remove(onCommandReceived);
_subscriberTransports.Remove(onCommandReceived);
}Update GameManager to handle cleanup between games (NO direct StopGame call):
File: src/MakaMek.Core/Models/Game/GameManager.cs
public class GameManager : IGameManager
{
private ServerGame? _serverGame;
private bool _isGameActive;
public bool IsGameActive => _isGameActive && _serverGame != null;
public async Task ResetForNewGame()
{
// Dispose current server game if exists
if (_serverGame != null)
{
_serverGame.Dispose();
_serverGame = null;
_isGameActive = false;
}
// Unsubscribe logging handler
if (_logHandler != null)
{
_commandPublisher.Unsubscribe(_logHandler);
_loggingSubscribed = false;
}
// Dispose command logger
_commandLogger?.Dispose();
_commandLogger = null;
// Clear transport publishers (but keep network host running)
var transportAdapter = _commandPublisher.Adapter;
var networkPublisher = _networkHostService?.Publisher;
transportAdapter.ClearPublishers();
if (networkPublisher != null)
{
transportAdapter.AddPublisher(networkPublisher);
}
}
public async Task InitializeLobby()
{
// Reset before initializing new lobby
await ResetForNewGame();
// Existing initialization logic...
var transportAdapter = _commandPublisher.Adapter;
if (CanStartLanServer && !IsLanServerRunning && _networkHostService != null)
{
await _networkHostService.Start();
if (_networkHostService.Publisher != null)
{
transportAdapter.AddPublisher(_networkHostService.Publisher);
}
}
// Create new server game
_serverGame = _gameFactory.CreateServerGame(/*...*/);
_ = Task.Run(() => _serverGame?.Start());
_isGameActive = true;
// Setup logging...
}
}Add cleanup method to ClientGame:
public sealed class ClientGame : BaseGame, IDisposable
{
private bool _isDisposed;
public void Dispose()
{
if (_isDisposed) return;
_isDisposed = true;
// Complete and dispose subjects
_commandSubject.OnCompleted();
_commandSubject.Dispose();
GC.SuppressFinalize(this);
}
public override void HandleCommand(IGameCommand command)
{
if (!ShouldHandleCommand(command)) return;
switch (command)
{
// Existing cases...
case GameEndedCommand gameEndedCommand:
OnGameEnded(gameEndedCommand);
break;
}
// Existing logic...
}
private void OnGameEnded(GameEndedCommand command)
{
// Log and publish to subscribers
_commandLog.Add(command);
_commandSubject.OnNext(command);
}
}NO IGameManager dependency - Use commands only:
public class BattleMapViewModel : BaseViewModel, IDisposable
{
private readonly ICommandPublisher _commandPublisher;
private bool _isDisposed;
public BattleMapViewModel(
ICommandPublisher commandPublisher, // NOT IGameManager
ILocalizationService localizationService,
IRulesProvider rulesProvider,
IDispatcherService dispatcherService)
{
_commandPublisher = commandPublisher;
BackToMenuCommand = new AsyncCommand(BackToMenu);
}
private async Task BackToMenu()
{
// Send PlayerLeftCommand for each local player
foreach (var player in Game.LocalPlayers)
{
var playerLeftCommand = new PlayerLeftCommand
{
GameOriginId = Game.Id,
PlayerId = player.Id,
Timestamp = DateTime.UtcNow
};
_commandPublisher.PublishCommand(playerLeftCommand);
}
// Cleanup local game
Dispose();
// Navigate to menu
await NavigationService.NavigateToRootAsync();
}
public void Dispose()
{
if (_isDisposed) return;
_isDisposed = true;
_gameSubscription?.Dispose();
_commandSubscription?.Dispose();
(_game as IDisposable)?.Dispose();
GC.SuppressFinalize(this);
}
private void OnCommandReceived(IGameCommand command)
{
if (command is GameEndedCommand)
{
// Server ended the game - navigate back
_dispatcherService.RunOnUIThread(async () => await BackToMenu());
}
}
}- Create
PlayerLeftCommand(client command) - Create
GameEndedCommandandGameEndReasonenum (server command) - Add
Unsubscribe()method toICommandPublisherandCommandPublisher - Update
GameManager.ResetForNewGame()to use Unsubscribe
- Add
StopGame(GameEndReason)method toServerGame - Add
HandlePlayerLeft()toServerGame.HandleCommand() - Add validation for
PlayerLeftCommandinBaseGame.ValidateCommand()
- Add
IDisposabletoClientGamewith proper cleanup - Implement
OnGameEnded()inClientGame - Add
GameEndedCommandtoBaseGame.ValidateCommand()
- Remove
IGameManagerdependency fromBattleMapViewModel - Implement
IDisposableinBattleMapViewModel - Update
BackToMenu()to sendPlayerLeftCommand - Handle
GameEndedCommandinBattleMapViewModel
- Unit tests for
ServerGame.StopGame() - Unit tests for
ServerGame.HandlePlayerLeft() - Unit tests for
CommandPublisher.Unsubscribe() - Integration tests for shutdown flow
- Test multiple game start/stop cycles
- Proper Client-Server Separation: Commands-only communication
- Clean Shutdown: Proper cleanup of all resources
- Client Notification: All clients informed when game ends
- Resource Management: No memory leaks or zombie processes
- Multiple Games: Can start new games without restarting app
- Testability: Clear lifecycle makes testing easier