///<summary>Ensures at least 1 game is available to join. If not, creates one to fill capacity</summary> public virtual void CheckCapacity() { List<GameLevel> availableGames = new List<GameLevel>(); List<GameLevel> closingGames = new List<GameLevel>(); lock (GameLevels) { foreach (GameLevel gameLevel in GameLevels.Values) { if (gameLevel.CurrentState.CanAddPlayer(gameLevel)) { availableGames.Add(gameLevel); } else if (gameLevel.CurrentState.GetEnumState(gameLevel) == StateType.Closing) { closingGames.Add(gameLevel); } } } lock (GameLevels) { foreach (GameLevel gameLevel in closingGames) { //SkyUtil.log($"Closing game {gameLevel.GameId}..."); gameLevel.Close(); GameLevels.TryRemove(gameLevel.GameId, out _); } } int j = 0; while (j++ + availableGames.Count < 2) { InitializeNewGame(); //Cannot add the new games to the available games list this tick. } //Clean up unnecessary games if (availableGames.Count >= 5) { lock (GameLevels) { //Start at the most recently created game for (int i = availableGames.Count - 1; i >= 0; i--) { GameLevel gameLevel = availableGames[i]; gameLevel.Close(); if (!GameLevels.TryRemove(gameLevel.GameId, out _)) { SkyUtil.log($"Failed to remove game id:{gameLevel.GameId} from GameLevels"); } } } } }