Compare commits

...

5 Commits

50 changed files with 1243 additions and 465 deletions

View File

@@ -1,23 +1,22 @@
using Godot; using Godot;
using Godot.Collections;
using Mr.BrickAdventures.scripts.Resources; using Mr.BrickAdventures.scripts.Resources;
using Mr.BrickAdventures.scripts.State;
namespace Mr.BrickAdventures.Autoloads; namespace Mr.BrickAdventures.Autoloads;
/// <summary>
/// Manages achievements using GameStateStore.
/// </summary>
public partial class AchievementManager : Node public partial class AchievementManager : Node
{ {
[Export] private string AchievementsFolderPath = "res://achievements/"; [Export] private string AchievementsFolderPath = "res://achievements/";
[Export] private PackedScene AchievementPopupScene { get; set; } [Export] private PackedScene AchievementPopupScene { get; set; }
private System.Collections.Generic.Dictionary<string, AchievementResource> _achievements = new(); private System.Collections.Generic.Dictionary<string, AchievementResource> _achievements = new();
private Array<string> _unlockedAchievementIds = [];
private GameManager _gameManager;
public override void _Ready() public override void _Ready()
{ {
_gameManager = GetNode<GameManager>("/root/GameManager");
LoadAchievementsFromFolder(); LoadAchievementsFromFolder();
LoadUnlockedAchievements();
} }
private void LoadAchievementsFromFolder() private void LoadAchievementsFromFolder()
@@ -44,7 +43,15 @@ public partial class AchievementManager : Node
fileName = dir.GetNext(); fileName = dir.GetNext();
} }
} }
/// <summary>
/// Gets the list of unlocked achievement IDs from the store.
/// </summary>
private System.Collections.Generic.List<string> GetUnlockedIds()
{
return GameStateStore.Instance?.Player.UnlockedAchievements ?? new System.Collections.Generic.List<string>();
}
public void UnlockAchievement(string achievementId) public void UnlockAchievement(string achievementId)
{ {
if (!_achievements.TryGetValue(achievementId, out var achievement)) if (!_achievements.TryGetValue(achievementId, out var achievement))
@@ -53,13 +60,14 @@ public partial class AchievementManager : Node
return; return;
} }
if (_unlockedAchievementIds.Contains(achievementId)) var unlockedIds = GetUnlockedIds();
if (unlockedIds.Contains(achievementId))
{ {
return; // Already unlocked return; // Already unlocked
} }
// 1. Mark as unlocked internally // 1. Mark as unlocked
_unlockedAchievementIds.Add(achievementId); unlockedIds.Add(achievementId);
GD.Print($"Achievement Unlocked: {achievement.DisplayName}"); GD.Print($"Achievement Unlocked: {achievement.DisplayName}");
// 2. Show the UI popup // 2. Show the UI popup
@@ -75,31 +83,19 @@ public partial class AchievementManager : Node
{ {
SteamManager.UnlockAchievement(achievement.Id); SteamManager.UnlockAchievement(achievement.Id);
} }
// 4. Save progress
SaveUnlockedAchievements();
}
public void LockAchievement(string achievementId)
{
if (_unlockedAchievementIds.Contains(achievementId))
{
_unlockedAchievementIds.Remove(achievementId);
SaveUnlockedAchievements();
}
}
private void SaveUnlockedAchievements()
{
_gameManager.PlayerState["unlocked_achievements"] = _unlockedAchievementIds;
// You might want to trigger a save game here, depending on your SaveSystem
} }
private void LoadUnlockedAchievements() public void LockAchievement(string achievementId)
{ {
if (_gameManager.PlayerState.TryGetValue("unlocked_achievements", out var unlocked)) var unlockedIds = GetUnlockedIds();
if (unlockedIds.Contains(achievementId))
{ {
_unlockedAchievementIds = (Array<string>)unlocked; unlockedIds.Remove(achievementId);
} }
} }
public bool IsAchievementUnlocked(string achievementId)
{
return GetUnlockedIds().Contains(achievementId);
}
} }

View File

@@ -1,4 +1,5 @@
using Godot; using Godot;
using Mr.BrickAdventures;
using Mr.BrickAdventures.scripts.components; using Mr.BrickAdventures.scripts.components;
namespace Mr.BrickAdventures.Autoloads; namespace Mr.BrickAdventures.Autoloads;
@@ -12,9 +13,9 @@ public partial class ConsoleManager : Node
public override void _Ready() public override void _Ready()
{ {
_gameManager = GetNode<GameManager>("/root/GameManager"); _gameManager = GetNode<GameManager>(Constants.GameManagerPath);
_achievementManager = GetNode<AchievementManager>("/root/AchievementManager"); _achievementManager = GetNode<AchievementManager>(Constants.AchievementManagerPath);
_skillManager = GetNode<SkillManager>("/root/SkillManager"); _skillManager = GetNode<SkillManager>(Constants.SkillManagerPath);
} }
private void AddCoinsCommand(int amount) private void AddCoinsCommand(int amount)
@@ -88,7 +89,7 @@ public partial class ConsoleManager : Node
_skillUnlockerComponent.UnlockAllSkills(); _skillUnlockerComponent.UnlockAllSkills();
} }
private void RemoveSkillCommand(string skillName) private void RemoveSkillCommand(string skillName)
{ {
if (!GetSkillManagement()) return; if (!GetSkillManagement()) return;
@@ -102,28 +103,28 @@ public partial class ConsoleManager : Node
_gameManager.RemoveSkill(skill.Name); _gameManager.RemoveSkill(skill.Name);
_skillManager.DeactivateSkill(skill); _skillManager.DeactivateSkill(skill);
} }
private void RemoveAllSkillsCommand() private void RemoveAllSkillsCommand()
{ {
if (!GetSkillManagement()) return; if (!GetSkillManagement()) return;
foreach (var skill in _skillManager.AvailableSkills) foreach (var skill in _skillManager.AvailableSkills)
{ {
_gameManager.RemoveSkill(skill.Name); _gameManager.RemoveSkill(skill.Name);
_skillManager.DeactivateSkill(skill); _skillManager.DeactivateSkill(skill);
} }
} }
private void GoToNextLevelCommand() private void GoToNextLevelCommand()
{ {
_gameManager.OnLevelComplete(); _gameManager.OnLevelComplete();
} }
private void UnlockAchievementCommand(string achievementId) private void UnlockAchievementCommand(string achievementId)
{ {
_achievementManager.UnlockAchievement(achievementId); _achievementManager.UnlockAchievement(achievementId);
} }
private void ResetAchievementCommand(string achievementId) private void ResetAchievementCommand(string achievementId)
{ {
_achievementManager.LockAchievement(achievementId); _achievementManager.LockAchievement(achievementId);

View File

@@ -1,9 +1,151 @@
using Godot; using Godot;
using Mr.BrickAdventures.scripts.components;
using Mr.BrickAdventures.scripts.Resources;
namespace Mr.BrickAdventures.Autoloads; namespace Mr.BrickAdventures.Autoloads;
/// <summary>
/// Global event bus for decoupled communication between game systems.
/// Use the static Instance property for easy access from anywhere.
/// </summary>
public partial class EventBus : Node public partial class EventBus : Node
{ {
/// <summary>
/// Singleton instance. Available after the autoload is initialized.
/// </summary>
public static EventBus Instance { get; private set; }
public override void _Ready()
{
Instance = this;
}
public override void _ExitTree()
{
if (Instance == this)
Instance = null;
}
#region Level Events
[Signal] public delegate void LevelStartedEventHandler(int levelIndex, Node currentScene); [Signal] public delegate void LevelStartedEventHandler(int levelIndex, Node currentScene);
[Signal] public delegate void LevelCompletedEventHandler(int levelIndex, Node currentScene, double completionTime); [Signal] public delegate void LevelCompletedEventHandler(int levelIndex, Node currentScene, double completionTime);
[Signal] public delegate void LevelRestartedEventHandler(int levelIndex);
public static void EmitLevelStarted(int levelIndex, Node currentScene)
=> Instance?.EmitSignal(SignalName.LevelStarted, levelIndex, currentScene);
public static void EmitLevelCompleted(int levelIndex, Node currentScene, double completionTime)
=> Instance?.EmitSignal(SignalName.LevelCompleted, levelIndex, currentScene, completionTime);
public static void EmitLevelRestarted(int levelIndex)
=> Instance?.EmitSignal(SignalName.LevelRestarted, levelIndex);
#endregion
#region Player Events
[Signal] public delegate void PlayerSpawnedEventHandler(PlayerController player);
[Signal] public delegate void PlayerDiedEventHandler(Vector2 position);
[Signal] public delegate void PlayerDamagedEventHandler(float damage, float remainingHealth, Vector2 position);
[Signal] public delegate void PlayerHealedEventHandler(float amount, float newHealth, Vector2 position);
public static void EmitPlayerSpawned(PlayerController player)
=> Instance?.EmitSignal(SignalName.PlayerSpawned, player);
public static void EmitPlayerDied(Vector2 position)
=> Instance?.EmitSignal(SignalName.PlayerDied, position);
public static void EmitPlayerDamaged(float damage, float remainingHealth, Vector2 position)
=> Instance?.EmitSignal(SignalName.PlayerDamaged, damage, remainingHealth, position);
public static void EmitPlayerHealed(float amount, float newHealth, Vector2 position)
=> Instance?.EmitSignal(SignalName.PlayerHealed, amount, newHealth, position);
#endregion
#region Combat Events
[Signal] public delegate void EnemyDefeatedEventHandler(Node enemy, Vector2 position);
[Signal] public delegate void EnemyDamagedEventHandler(Node enemy, float damage, Vector2 position);
public static void EmitEnemyDefeated(Node enemy, Vector2 position)
=> Instance?.EmitSignal(SignalName.EnemyDefeated, enemy, position);
public static void EmitEnemyDamaged(Node enemy, float damage, Vector2 position)
=> Instance?.EmitSignal(SignalName.EnemyDamaged, enemy, damage, position);
#endregion
#region Collection Events
[Signal] public delegate void CoinCollectedEventHandler(int amount, Vector2 position);
[Signal] public delegate void ItemCollectedEventHandler(CollectableType itemType, float amount, Vector2 position);
[Signal] public delegate void ChildRescuedEventHandler(Vector2 position);
public static void EmitCoinCollected(int amount, Vector2 position)
=> Instance?.EmitSignal(SignalName.CoinCollected, amount, position);
public static void EmitItemCollected(CollectableType itemType, float amount, Vector2 position)
=> Instance?.EmitSignal(SignalName.ItemCollected, (int)itemType, amount, position);
public static void EmitChildRescued(Vector2 position)
=> Instance?.EmitSignal(SignalName.ChildRescued, position);
#endregion
#region Skill Events
[Signal] public delegate void SkillUnlockedEventHandler(string skillName, int level);
[Signal] public delegate void SkillActivatedEventHandler(string skillName);
[Signal] public delegate void SkillDeactivatedEventHandler(string skillName);
public static void EmitSkillUnlocked(string skillName, int level = 1)
=> Instance?.EmitSignal(SignalName.SkillUnlocked, skillName, level);
public static void EmitSkillActivated(string skillName)
=> Instance?.EmitSignal(SignalName.SkillActivated, skillName);
public static void EmitSkillDeactivated(string skillName)
=> Instance?.EmitSignal(SignalName.SkillDeactivated, skillName);
#endregion
#region Game State Events
[Signal] public delegate void GamePausedEventHandler();
[Signal] public delegate void GameResumedEventHandler();
[Signal] public delegate void GameSavedEventHandler();
[Signal] public delegate void GameStartedEventHandler();
[Signal] public delegate void GameContinuedEventHandler();
public static void EmitGamePaused()
=> Instance?.EmitSignal(SignalName.GamePaused);
public static void EmitGameResumed()
=> Instance?.EmitSignal(SignalName.GameResumed);
public static void EmitGameSaved()
=> Instance?.EmitSignal(SignalName.GameSaved);
public static void EmitGameStarted()
=> Instance?.EmitSignal(SignalName.GameStarted);
public static void EmitGameContinued()
=> Instance?.EmitSignal(SignalName.GameContinued);
#endregion
#region State Change Events
[Signal] public delegate void CoinsChangedEventHandler(int totalCoins);
[Signal] public delegate void LivesChangedEventHandler(int lives);
public static void EmitCoinsChanged(int totalCoins)
=> Instance?.EmitSignal(SignalName.CoinsChanged, totalCoins);
public static void EmitLivesChanged(int lives)
=> Instance?.EmitSignal(SignalName.LivesChanged, lives);
#endregion
} }

View File

@@ -3,41 +3,32 @@ using Godot;
using Godot.Collections; using Godot.Collections;
using Mr.BrickAdventures.scripts.components; using Mr.BrickAdventures.scripts.components;
using Mr.BrickAdventures.scripts.Resources; using Mr.BrickAdventures.scripts.Resources;
using Double = System.Double; using Mr.BrickAdventures.scripts.State;
namespace Mr.BrickAdventures.Autoloads; namespace Mr.BrickAdventures.Autoloads;
/// <summary>
/// Game orchestrator - handles scene management and game flow.
/// State is delegated to GameStateStore for better separation of concerns.
/// </summary>
public partial class GameManager : Node public partial class GameManager : Node
{ {
[Export] public Array<PackedScene> LevelScenes { get; set; } = []; [Export] public Array<PackedScene> LevelScenes { get; set; } = [];
public PlayerController Player { public PlayerController Player
{
get => GetPlayer(); get => GetPlayer();
private set => _player = value; private set => _player = value;
} }
private List<Node> _sceneNodes = []; private List<Node> _sceneNodes = [];
private PlayerController _player; private PlayerController _player;
private SpeedRunManager _speedRunManager; private SpeedRunManager _speedRunManager;
private EventBus _eventBus;
/// <summary>
[Export] /// Lazy accessor for GameStateStore - avoids initialization order issues.
public Dictionary PlayerState { get; set; } = new() /// </summary>
{ private GameStateStore Store => GameStateStore.Instance;
{ "coins", 0 },
{ "lives", 3 },
{ "current_level", 0 },
{ "completed_levels", new Array<int>() },
{ "unlocked_levels", new Array<int>() {0}},
{ "unlocked_skills", new Array<SkillData>() }
};
[Export]
public Dictionary CurrentSessionState { get; private set; } = new()
{
{ "coins_collected", 0 },
{ "skills_unlocked", new Array<SkillData>() }
};
public override void _EnterTree() public override void _EnterTree()
{ {
@@ -54,15 +45,14 @@ public partial class GameManager : Node
public override void _Ready() public override void _Ready()
{ {
_speedRunManager = GetNode<SpeedRunManager>("/root/SpeedRunManager"); _speedRunManager = GetNode<SpeedRunManager>(Constants.SpeedRunManagerPath);
_eventBus = GetNode<EventBus>("/root/EventBus");
} }
private void OnNodeAdded(Node node) private void OnNodeAdded(Node node)
{ {
_sceneNodes.Add(node); _sceneNodes.Add(node);
} }
private void OnNodeRemoved(Node node) private void OnNodeRemoved(Node node)
{ {
_sceneNodes.Remove(node); _sceneNodes.Remove(node);
@@ -72,57 +62,71 @@ public partial class GameManager : Node
} }
} }
#region Coin Operations
public void AddCoins(int amount) public void AddCoins(int amount)
{ {
PlayerState["coins"] = Mathf.Max(0, (int)PlayerState["coins"] + amount); if (Store != null)
}
public void SetCoins(int amount) => PlayerState["coins"] = Mathf.Max(0, amount);
public int GetCoins() => (int)PlayerState["coins"] + (int)CurrentSessionState["coins_collected"];
public void RemoveCoins(int amount)
{
var sessionCoins = (int)CurrentSessionState["coins_collected"];
if (amount <= sessionCoins)
{ {
CurrentSessionState["coins_collected"] = sessionCoins - amount; Store.Player.Coins += amount;
EventBus.EmitCoinsChanged(Store.GetTotalCoins());
} }
else
{
var remaining = amount - sessionCoins;
CurrentSessionState["coins_collected"] = 0;
PlayerState["coins"] = Mathf.Max(0, (int)PlayerState["coins"] - remaining);
}
PlayerState["coins"] = Mathf.Max(0, (int)PlayerState["coins"]);
} }
public void AddLives(int amount) => PlayerState["lives"] = (int)PlayerState["lives"] + amount; public void SetCoins(int amount)
public void RemoveLives(int amount) => PlayerState["lives"] = (int)PlayerState["lives"] - amount;
public void SetLives(int amount) => PlayerState["lives"] = amount;
public int GetLives() => (int)PlayerState["lives"];
public bool IsSkillUnlocked(SkillData skill)
{ {
return ((Array)PlayerState["unlocked_skills"]).Contains(skill) if (Store != null)
|| ((Array)CurrentSessionState["skills_unlocked"]).Contains(skill); {
Store.Player.Coins = Mathf.Max(0, amount);
EventBus.EmitCoinsChanged(Store.GetTotalCoins());
}
} }
public int GetCoins() => Store?.GetTotalCoins() ?? 0;
public void RemoveCoins(int amount) => Store?.RemoveCoins(amount);
#endregion
#region Lives Operations
public void AddLives(int amount) => Store?.AddLives(amount);
public void RemoveLives(int amount) => Store?.RemoveLife();
public void SetLives(int amount)
{
if (Store != null)
{
Store.Player.Lives = amount;
EventBus.EmitLivesChanged(amount);
}
}
public int GetLives() => Store?.Player.Lives ?? 0;
#endregion
#region Skill Operations
public bool IsSkillUnlocked(SkillData skill) => Store?.IsSkillUnlocked(skill) ?? false;
public void UnlockSkill(SkillData skill) public void UnlockSkill(SkillData skill)
{ {
if (!IsSkillUnlocked(skill)) if (Store != null && !Store.IsSkillUnlocked(skill))
((Array)PlayerState["unlocked_skills"]).Add(skill); {
Store.Player.UnlockedSkills.Add(skill);
}
} }
public void RemoveSkill(string skillName) public void RemoveSkill(string skillName)
{ {
var arr = (Array)PlayerState["unlocked_skills"]; if (Store == null) return;
foreach (SkillData s in arr) var skills = Store.Player.UnlockedSkills;
for (int i = 0; i < skills.Count; i++)
{ {
if (s.Name != skillName) continue; if (skills[i].Name == skillName)
{
arr.Remove(s); skills.RemoveAt(i);
break; break;
}
} }
} }
@@ -132,81 +136,84 @@ public partial class GameManager : Node
UnlockSkill(s); UnlockSkill(s);
} }
public void ResetPlayerState() public Array<SkillData> GetUnlockedSkills()
{ {
PlayerState = new Dictionary if (Store == null) return new Array<SkillData>();
{
{ "coins", 0 }, var result = new Array<SkillData>();
{ "lives", 3 }, foreach (var s in Store.Player.UnlockedSkills)
{ "current_level", 0 }, result.Add(s);
{ "completed_levels", new Array<int>() }, foreach (var s in Store.Session.SkillsUnlocked)
{ "unlocked_levels", new Array<int>() {0}}, if (!result.Contains(s)) result.Add(s);
{ "unlocked_skills", new Array<SkillData>() }, return result;
{ "statistics", new Godot.Collections.Dictionary<string, Variant>()}
};
}
public void UnlockLevel(int levelIndex)
{
var unlocked = (Array)PlayerState["unlocked_levels"];
if (!unlocked.Contains(levelIndex)) unlocked.Add(levelIndex);
} }
#endregion
#region Level Operations
public void UnlockLevel(int levelIndex) => Store?.UnlockLevel(levelIndex);
public void MarkLevelComplete(int levelIndex) => Store?.MarkLevelComplete(levelIndex);
public void TryToGoToNextLevel() public void TryToGoToNextLevel()
{ {
var next = (int)PlayerState["current_level"] + 1; if (Store == null) return;
var unlocked = (Array)PlayerState["unlocked_levels"];
if (next < LevelScenes.Count && unlocked.Contains(next)) var next = Store.Session.CurrentLevel + 1;
if (next < LevelScenes.Count && Store.IsLevelUnlocked(next))
{ {
PlayerState["current_level"] = next; Store.Session.CurrentLevel = next;
GetTree().ChangeSceneToPacked(LevelScenes[next]); GetTree().ChangeSceneToPacked(LevelScenes[next]);
_eventBus.EmitSignal(EventBus.SignalName.LevelStarted, next, GetTree().CurrentScene); EventBus.EmitLevelStarted(next, GetTree().CurrentScene);
} }
} }
public void MarkLevelComplete(int levelIndex)
{
UnlockLevel(levelIndex + 1);
var completed = (Array)PlayerState["completed_levels"];
if (!completed.Contains(levelIndex)) completed.Add(levelIndex);
}
public void ResetCurrentSessionState() #endregion
{
CurrentSessionState = new Dictionary #region State Reset
{
{ "coins_collected", 0 }, public void ResetPlayerState() => Store?.ResetAll();
{ "skills_unlocked", new Array<SkillData>() }
}; public void ResetCurrentSessionState() => Store?.ResetSession();
}
#endregion
#region Game Flow
public void RestartGame() public void RestartGame()
{ {
ResetPlayerState(); Store?.ResetAll();
ResetCurrentSessionState();
GetTree().ChangeSceneToPacked(LevelScenes[0]); GetTree().ChangeSceneToPacked(LevelScenes[0]);
GetNode<SaveSystem>("/root/SaveSystem").SaveGame(); GetNode<SaveSystem>(Constants.SaveSystemPath).SaveGame();
} }
public void QuitGame() => GetTree().Quit(); public void QuitGame() => GetTree().Quit();
public void PauseGame() => Engine.TimeScale = 0; public void PauseGame()
public void ResumeGame() => Engine.TimeScale = 1; {
Engine.TimeScale = 0;
EventBus.EmitGamePaused();
}
public void ResumeGame()
{
Engine.TimeScale = 1;
EventBus.EmitGameResumed();
}
public void StartNewGame() public void StartNewGame()
{ {
ResetPlayerState(); Store?.ResetAll();
ResetCurrentSessionState();
_speedRunManager?.StartTimer(); _speedRunManager?.StartTimer();
GetTree().ChangeSceneToPacked(LevelScenes[0]); GetTree().ChangeSceneToPacked(LevelScenes[0]);
GetNode<SaveSystem>("/root/SaveSystem").SaveGame(); GetNode<SaveSystem>(Constants.SaveSystemPath).SaveGame();
EventBus.EmitGameStarted();
} }
public void ContinueGame() public void ContinueGame()
{ {
var save = GetNode<SaveSystem>("/root/SaveSystem"); var save = GetNode<SaveSystem>(Constants.SaveSystemPath);
if (!save.LoadGame()) if (!save.LoadGame())
{ {
GD.PrintErr("Failed to load game. Starting a new game instead."); GD.PrintErr("Failed to load game. Starting a new game instead.");
@@ -214,57 +221,56 @@ public partial class GameManager : Node
return; return;
} }
var idx = (int)PlayerState["current_level"]; var idx = Store?.Session.CurrentLevel ?? 0;
if (idx < LevelScenes.Count) if (idx < LevelScenes.Count)
{
GetTree().ChangeSceneToPacked(LevelScenes[idx]); GetTree().ChangeSceneToPacked(LevelScenes[idx]);
EventBus.EmitGameContinued();
}
else else
{
GD.PrintErr("No levels unlocked to continue."); GD.PrintErr("No levels unlocked to continue.");
}
} }
public void OnLevelComplete() public void OnLevelComplete()
{ {
var levelIndex = (int)PlayerState["current_level"]; if (Store == null) return;
MarkLevelComplete(levelIndex);
var levelIndex = Store.Session.CurrentLevel;
AddCoins((int)CurrentSessionState["coins_collected"]); Store.MarkLevelComplete(levelIndex);
foreach (var s in (Array)CurrentSessionState["skills_unlocked"]) Store.CommitSessionCoins();
UnlockSkill((SkillData)s); Store.CommitSessionSkills();
var completionTime = _speedRunManager?.GetCurrentLevelTime() ?? 0.0; var completionTime = _speedRunManager?.GetCurrentLevelTime() ?? 0.0;
_eventBus.EmitSignal(EventBus.SignalName.LevelCompleted, levelIndex, GetTree().CurrentScene, completionTime); EventBus.EmitLevelCompleted(levelIndex, GetTree().CurrentScene, completionTime);
ResetCurrentSessionState(); Store.ResetSession();
TryToGoToNextLevel(); TryToGoToNextLevel();
GetNode<SaveSystem>("/root/SaveSystem").SaveGame(); GetNode<SaveSystem>(Constants.SaveSystemPath).SaveGame();
} }
public Array<SkillData> GetUnlockedSkills() #endregion
{
var unlocked = (Array<SkillData>)PlayerState["unlocked_skills"]; #region Player Lookup
var session = (Array<SkillData>)CurrentSessionState["skills_unlocked"];
if (session!.Count == 0) return unlocked;
if (unlocked!.Count == 0) return session;
var joined = new Array<SkillData>();
joined.AddRange(unlocked);
joined.AddRange(session);
return joined;
}
public PlayerController GetPlayer() public PlayerController GetPlayer()
{ {
if (_player != null && IsInstanceValid(_player)) return _player; if (_player != null && IsInstanceValid(_player)) return _player;
_player = null; _player = null;
foreach (var node in _sceneNodes) foreach (var node in _sceneNodes)
{ {
if (node is not PlayerController player) continue; if (node is not PlayerController player) continue;
_player = player; _player = player;
return _player; return _player;
} }
GD.PrintErr("PlayerController not found in the scene tree."); GD.PrintErr("PlayerController not found in the scene tree.");
return null; return null;
} }
#endregion
} }

185
Autoloads/GameStateStore.cs Normal file
View File

@@ -0,0 +1,185 @@
using Godot;
using Mr.BrickAdventures.scripts.Resources;
using Mr.BrickAdventures.scripts.State;
namespace Mr.BrickAdventures.Autoloads;
/// <summary>
/// Central store for game state - single source of truth.
/// Use the static Instance property for easy access.
/// </summary>
public partial class GameStateStore : Node
{
/// <summary>
/// Singleton instance.
/// </summary>
public static GameStateStore Instance { get; private set; }
/// <summary>
/// Persistent player state (saved to disk).
/// </summary>
public PlayerState Player { get; set; } = new();
/// <summary>
/// Current session state (transient, reset on death/level complete).
/// </summary>
public SessionState Session { get; set; } = new();
public override void _Ready()
{
Instance = this;
}
public override void _ExitTree()
{
if (Instance == this)
Instance = null;
}
#region Coin Operations
/// <summary>
/// Gets total coins (saved + session).
/// </summary>
public int GetTotalCoins() => Player.Coins + Session.CoinsCollected;
/// <summary>
/// Adds coins to the session (not saved until level complete).
/// </summary>
public void AddSessionCoins(int amount)
{
Session.CoinsCollected += amount;
EventBus.EmitCoinsChanged(GetTotalCoins());
}
/// <summary>
/// Commits session coins to player state.
/// </summary>
public void CommitSessionCoins()
{
Player.Coins += Session.CoinsCollected;
Session.CoinsCollected = 0;
}
/// <summary>
/// Removes coins, first from session then from saved.
/// </summary>
public void RemoveCoins(int amount)
{
if (amount <= Session.CoinsCollected)
{
Session.CoinsCollected -= amount;
}
else
{
var remaining = amount - Session.CoinsCollected;
Session.CoinsCollected = 0;
Player.Coins = Mathf.Max(0, Player.Coins - remaining);
}
EventBus.EmitCoinsChanged(GetTotalCoins());
}
#endregion
#region Lives Operations
/// <summary>
/// Decrements lives by 1.
/// </summary>
public void RemoveLife()
{
Player.Lives = Mathf.Max(0, Player.Lives - 1);
EventBus.EmitLivesChanged(Player.Lives);
}
/// <summary>
/// Adds lives.
/// </summary>
public void AddLives(int amount)
{
Player.Lives += amount;
EventBus.EmitLivesChanged(Player.Lives);
}
#endregion
#region Level Operations
/// <summary>
/// Unlocks a level for access.
/// </summary>
public void UnlockLevel(int levelIndex)
{
if (!Player.UnlockedLevels.Contains(levelIndex))
Player.UnlockedLevels.Add(levelIndex);
}
/// <summary>
/// Marks a level as completed and unlocks the next.
/// </summary>
public void MarkLevelComplete(int levelIndex)
{
if (!Player.CompletedLevels.Contains(levelIndex))
Player.CompletedLevels.Add(levelIndex);
UnlockLevel(levelIndex + 1);
}
/// <summary>
/// Checks if a level is unlocked.
/// </summary>
public bool IsLevelUnlocked(int levelIndex) => Player.UnlockedLevels.Contains(levelIndex);
#endregion
#region Skill Operations
/// <summary>
/// Checks if a skill is unlocked (saved or session).
/// </summary>
public bool IsSkillUnlocked(SkillData skill)
{
return Player.UnlockedSkills.Contains(skill) || Session.SkillsUnlocked.Contains(skill);
}
/// <summary>
/// Unlocks a skill in the session.
/// </summary>
public void UnlockSkillInSession(SkillData skill)
{
if (!IsSkillUnlocked(skill))
Session.SkillsUnlocked.Add(skill);
}
/// <summary>
/// Commits session skills to player state.
/// </summary>
public void CommitSessionSkills()
{
foreach (var skill in Session.SkillsUnlocked)
{
if (!Player.UnlockedSkills.Contains(skill))
Player.UnlockedSkills.Add(skill);
}
Session.SkillsUnlocked.Clear();
}
#endregion
#region Reset Operations
/// <summary>
/// Resets only the session state.
/// </summary>
public void ResetSession() => Session.Reset();
/// <summary>
/// Resets everything to defaults.
/// </summary>
public void ResetAll()
{
Player.Reset();
Session.ResetAll();
}
#endregion
}

View File

@@ -0,0 +1 @@
uid://bwrhkipwecytk

View File

@@ -1,61 +1,180 @@
using System.Collections.Generic;
using System.Text.Json;
using Godot; using Godot;
using Godot.Collections;
using Mr.BrickAdventures.scripts.Resources; using Mr.BrickAdventures.scripts.Resources;
using Mr.BrickAdventures.scripts.State;
namespace Mr.BrickAdventures.Autoloads; namespace Mr.BrickAdventures.Autoloads;
/// <summary>
/// Save system that serializes state to JSON using DTOs.
/// </summary>
public partial class SaveSystem : Node public partial class SaveSystem : Node
{ {
[Export] public string SavePath { get; set; } = "user://savegame.save"; [Export] public string SavePath { get; set; } = "user://savegame.json";
[Export] public int Version { get; set; } = 1; [Export] public int Version { get; set; } = 2;
private GameManager _gameManager; private static readonly JsonSerializerOptions JsonOptions = new()
public override void _Ready()
{ {
_gameManager = GetNode<GameManager>("/root/GameManager"); WriteIndented = true,
} PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
public void SaveGame() public void SaveGame()
{ {
var saveData = new Dictionary var store = GameStateStore.Instance;
if (store == null)
{ {
{ "player_state", _gameManager.PlayerState}, GD.PrintErr("SaveSystem: GameStateStore not available.");
{ "version", Version} return;
}
// Convert to DTO (only serializable data)
var saveData = new SaveDataDto
{
Version = Version,
Coins = store.Player.Coins,
Lives = store.Player.Lives,
CurrentLevel = store.Session.CurrentLevel,
CompletedLevels = [.. store.Player.CompletedLevels],
UnlockedLevels = new List<int>(store.Player.UnlockedLevels),
UnlockedSkillNames = GetSkillNames(store.Player.UnlockedSkills),
UnlockedAchievements = new List<string>(store.Player.UnlockedAchievements),
Statistics = new Dictionary<string, int>(store.Player.Statistics)
}; };
using var file = FileAccess.Open(SavePath, FileAccess.ModeFlags.Write); try
file.StoreVar(saveData); {
GD.Print("Game state saved to: ", SavePath); var json = JsonSerializer.Serialize(saveData, JsonOptions);
using var file = FileAccess.Open(SavePath, FileAccess.ModeFlags.Write);
file.StoreString(json);
GD.Print("Game saved to: ", SavePath);
EventBus.EmitGameSaved();
}
catch (System.Exception e)
{
GD.PrintErr($"SaveSystem: Failed to save game: {e.Message}");
}
} }
public bool LoadGame() public bool LoadGame()
{ {
if (!FileAccess.FileExists(SavePath)) if (!FileAccess.FileExists(SavePath))
return false;
using var file = FileAccess.Open(SavePath, FileAccess.ModeFlags.Read);
var saveDataObj = (Dictionary)file.GetVar();
if (saveDataObj.ContainsKey("version") && (int)saveDataObj["version"] != Version)
{ {
GD.Print($"Save file version mismatch. Expected: {Version}, Found: {saveDataObj["version"]}"); GD.Print("SaveSystem: No save file found.");
return false; return false;
} }
GD.Print("Game state loaded from: ", SavePath); try
GD.Print("Player state: ", saveDataObj["player_state"]);
_gameManager.PlayerState = (Dictionary)saveDataObj["player_state"];
var skills = new Array<SkillData>();
foreach (var skill in (Array<SkillData>)_gameManager.PlayerState["unlocked_skills"])
{ {
skills.Add(skill); using var file = FileAccess.Open(SavePath, FileAccess.ModeFlags.Read);
var json = file.GetAsText();
var saveData = JsonSerializer.Deserialize<SaveDataDto>(json, JsonOptions);
if (saveData == null)
{
GD.PrintErr("SaveSystem: Failed to deserialize save data.");
return false;
}
if (saveData.Version != Version)
{
GD.PrintErr($"SaveSystem: Version mismatch. Expected {Version}, found {saveData.Version}");
return false;
}
var store = GameStateStore.Instance;
if (store == null)
{
GD.PrintErr("SaveSystem: GameStateStore not available.");
return false;
}
// Apply loaded state
store.Player.Coins = saveData.Coins;
store.Player.Lives = saveData.Lives;
store.Session.CurrentLevel = saveData.CurrentLevel;
store.Player.CompletedLevels = saveData.CompletedLevels ?? new List<int>();
store.Player.UnlockedLevels = saveData.UnlockedLevels ?? new List<int> { 0 };
store.Player.UnlockedAchievements = saveData.UnlockedAchievements ?? new List<string>();
store.Player.Statistics = saveData.Statistics ?? new Dictionary<string, int>();
// Reload skills by name from SkillManager
store.Player.UnlockedSkills = LoadSkillsByName(saveData.UnlockedSkillNames);
GD.Print("Game loaded from: ", SavePath);
return true;
}
catch (System.Exception e)
{
GD.PrintErr($"SaveSystem: Failed to load game: {e.Message}");
return false;
} }
_gameManager.UnlockSkills(skills);
return true;
} }
private static List<string> GetSkillNames(List<SkillData> skills)
{
var names = new List<string>();
foreach (var skill in skills)
{
if (skill != null)
names.Add(skill.Name);
}
return names;
}
private List<SkillData> LoadSkillsByName(List<string> skillNames)
{
var skills = new List<SkillData>();
if (skillNames == null) return skills;
var skillManager = GetNodeOrNull<SkillManager>(Constants.SkillManagerPath);
if (skillManager == null)
{
GD.PrintErr("SaveSystem: SkillManager not available to resolve skill names.");
return skills;
}
foreach (var name in skillNames)
{
var skill = skillManager.GetSkillByName(name);
if (skill != null)
{
skills.Add(skill);
}
else
{
GD.PrintErr($"SaveSystem: Skill '{name}' not found in SkillManager.");
}
}
return skills;
}
public bool CheckSaveExists() => FileAccess.FileExists(SavePath); public bool CheckSaveExists() => FileAccess.FileExists(SavePath);
public void DeleteSave()
{
if (FileAccess.FileExists(SavePath))
{
DirAccess.RemoveAbsolute(ProjectSettings.GlobalizePath(SavePath));
GD.Print("Save file deleted.");
}
}
}
/// <summary>
/// Serializable DTO for save data - no Godot types.
/// </summary>
public class SaveDataDto
{
public int Version { get; set; }
public int Coins { get; set; }
public int Lives { get; set; }
public int CurrentLevel { get; set; }
public List<int> CompletedLevels { get; set; }
public List<int> UnlockedLevels { get; set; }
public List<string> UnlockedSkillNames { get; set; }
public List<string> UnlockedAchievements { get; set; }
public Dictionary<string, int> Statistics { get; set; }
} }

View File

@@ -2,6 +2,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using Godot; using Godot;
using Godot.Collections; using Godot.Collections;
using Mr.BrickAdventures;
using Mr.BrickAdventures.scripts.components; using Mr.BrickAdventures.scripts.components;
using Mr.BrickAdventures.scripts.interfaces; using Mr.BrickAdventures.scripts.interfaces;
using Mr.BrickAdventures.scripts.Resources; using Mr.BrickAdventures.scripts.Resources;
@@ -14,19 +15,19 @@ public partial class SkillManager : Node
private PlayerController _player; private PlayerController _player;
[Export] public Array<SkillData> AvailableSkills { get; set; } = []; [Export] public Array<SkillData> AvailableSkills { get; set; } = [];
public Dictionary ActiveComponents { get; private set; } = new(); public Dictionary ActiveComponents { get; private set; } = new();
[Signal] [Signal]
public delegate void ActiveThrowSkillChangedEventHandler(BrickThrowComponent throwComponent); public delegate void ActiveThrowSkillChangedEventHandler(BrickThrowComponent throwComponent);
[Signal] [Signal]
public delegate void SkillRemovedEventHandler(SkillData skillData); public delegate void SkillRemovedEventHandler(SkillData skillData);
public override void _Ready() public override void _Ready()
{ {
_gameManager = GetNode<GameManager>("/root/GameManager"); _gameManager = GetNode<GameManager>(Constants.GameManagerPath);
} }
/// <summary> /// <summary>
/// Called by the PlayerController from its _Ready method to register itself with the manager. /// Called by the PlayerController from its _Ready method to register itself with the manager.
/// </summary> /// </summary>
@@ -39,7 +40,7 @@ public partial class SkillManager : Node
{ {
UnregisterPlayer(); UnregisterPlayer();
} }
_player = player; _player = player;
if (_player != null) if (_player != null)
{ {
@@ -61,7 +62,7 @@ public partial class SkillManager : Node
} }
_player = null; _player = null;
} }
public void AddSkill(SkillData skillData) public void AddSkill(SkillData skillData)
{ {
// Ensure a valid player is registered before adding a skill. // Ensure a valid player is registered before adding a skill.
@@ -70,7 +71,7 @@ public partial class SkillManager : Node
GD.Print("SkillManager: Player not available to add skill."); GD.Print("SkillManager: Player not available to add skill.");
return; return;
} }
if (ActiveComponents.ContainsKey(skillData.Name)) if (ActiveComponents.ContainsKey(skillData.Name))
return; return;
@@ -98,9 +99,9 @@ public partial class SkillManager : Node
if (instance is ISkill skill) if (instance is ISkill skill)
{ {
// Initialize the skill with the registered player instance. // Initialize the skill with the registered player instance.
skill.Initialize(_player, skillData); skill.Initialize(_player, skillData);
skill.Activate(); skill.Activate();
} }
else else
{ {
GD.PrintErr($"Skill scene for '{skillData.Name}' does not implement ISkill!"); GD.PrintErr($"Skill scene for '{skillData.Name}' does not implement ISkill!");
@@ -111,18 +112,18 @@ public partial class SkillManager : Node
// Add the skill node as a child of the player. // Add the skill node as a child of the player.
_player.AddChild(instance); _player.AddChild(instance);
ActiveComponents[skillData.Name] = instance; ActiveComponents[skillData.Name] = instance;
if (instance is BrickThrowComponent btc) if (instance is BrickThrowComponent btc)
{ {
EmitSignalActiveThrowSkillChanged(btc); EmitSignalActiveThrowSkillChanged(btc);
} }
} }
public void RemoveSkill(string skillName) public void RemoveSkill(string skillName)
{ {
if (!ActiveComponents.TryGetValue(skillName, out var component)) if (!ActiveComponents.TryGetValue(skillName, out var component))
return; return;
if (component.AsGodotObject() is BrickThrowComponent) if (component.AsGodotObject() is BrickThrowComponent)
{ {
EmitSignalActiveThrowSkillChanged(null); EmitSignalActiveThrowSkillChanged(null);
@@ -133,7 +134,7 @@ public partial class SkillManager : Node
{ {
skill.Deactivate(); skill.Deactivate();
} }
if (IsInstanceValid(inst)) if (IsInstanceValid(inst))
inst.QueueFree(); inst.QueueFree();
@@ -150,7 +151,7 @@ public partial class SkillManager : Node
var sd = GetSkillByName(skillName); var sd = GetSkillByName(skillName);
if (sd != null) EmitSignalSkillRemoved(sd); if (sd != null) EmitSignalSkillRemoved(sd);
} }
private void RemoveAllActiveSkills() private void RemoveAllActiveSkills()
{ {
// Create a copy of keys to avoid modification during iteration // Create a copy of keys to avoid modification during iteration

View File

@@ -1,78 +1,62 @@
using System.Collections.Generic;
using Godot; using Godot;
using Godot.Collections; using Mr.BrickAdventures.scripts.State;
namespace Mr.BrickAdventures.Autoloads; namespace Mr.BrickAdventures.Autoloads;
/// <summary>
/// Manages game statistics using GameStateStore.
/// </summary>
public partial class StatisticsManager : Node public partial class StatisticsManager : Node
{ {
private GameManager _gameManager;
private AchievementManager _achievementManager;
private Dictionary<string, Variant> _stats = new();
public override void _Ready() /// <summary>
/// Gets the statistics dictionary from the store.
/// </summary>
private Dictionary<string, int> GetStats()
{ {
_gameManager = GetNode<GameManager>("/root/GameManager"); return GameStateStore.Instance?.Player.Statistics ?? new Dictionary<string, int>();
_achievementManager = GetNode<AchievementManager>("/root/AchievementManager");
LoadStatistics();
} }
private void LoadStatistics()
{
if (_gameManager.PlayerState.TryGetValue("statistics", out var statsObj))
{
_stats = (Dictionary<string, Variant>)statsObj;
}
else
{
_stats = new Dictionary<string, Variant>();
_gameManager.PlayerState["statistics"] = _stats;
}
}
/// <summary> /// <summary>
/// Increases a numerical statistic by a given amount. /// Increases a numerical statistic by a given amount.
/// </summary> /// </summary>
public void IncrementStat(string statName, int amount = 1) public void IncrementStat(string statName, int amount = 1)
{ {
if (_stats.TryGetValue(statName, out var currentValue)) var stats = GetStats();
if (stats.TryGetValue(statName, out var currentValue))
{ {
_stats[statName] = (int)currentValue + amount; stats[statName] = currentValue + amount;
} }
else else
{ {
_stats[statName] = amount; stats[statName] = amount;
} }
GD.Print($"Stat '{statName}' updated to: {_stats[statName]}"); }
CheckAchievementsForStat(statName);
/// <summary>
/// Sets a statistic to a specific value.
/// </summary>
public void SetStat(string statName, int value)
{
var stats = GetStats();
stats[statName] = value;
} }
/// <summary> /// <summary>
/// Gets the value of a statistic. /// Gets the value of a statistic.
/// </summary> /// </summary>
public Variant GetStat(string statName, Variant defaultValue = default) public int GetStat(string statName)
{ {
return _stats.TryGetValue(statName, out var value) ? value : defaultValue; var stats = GetStats();
return stats.TryGetValue(statName, out var value) ? value : 0;
} }
/// <summary> /// <summary>
/// Checks if the updated stat meets the criteria for any achievements. /// Gets a copy of all statistics.
/// </summary> /// </summary>
private void CheckAchievementsForStat(string statName) public Dictionary<string, int> GetAllStats()
{ {
switch (statName) return new Dictionary<string, int>(GetStats());
{
case "enemies_defeated":
if ((int)GetStat(statName, 0) >= 100)
{
_achievementManager.UnlockAchievement("slayer_100_enemies");
}
break;
case "jumps_made":
if ((int)GetStat(statName, 0) >= 1000)
{
_achievementManager.UnlockAchievement("super_jumper");
}
break;
}
} }
} }

View File

@@ -1,4 +1,4 @@
[gd_scene load_steps=58 format=3 uid="uid://bqi5s710xb1ju"] [gd_scene load_steps=57 format=3 uid="uid://bqi5s710xb1ju"]
[ext_resource type="Script" uid="uid://csel4s0e4g5uf" path="res://scripts/components/PlayerController.cs" id="1_yysbb"] [ext_resource type="Script" uid="uid://csel4s0e4g5uf" path="res://scripts/components/PlayerController.cs" id="1_yysbb"]
[ext_resource type="Shader" uid="uid://bs4xvm4qkurpr" path="res://shaders/hit_flash.tres" id="2_lgb3u"] [ext_resource type="Shader" uid="uid://bs4xvm4qkurpr" path="res://shaders/hit_flash.tres" id="2_lgb3u"]
@@ -19,7 +19,6 @@
[ext_resource type="PackedScene" uid="uid://dre1vit1m4d2n" path="res://objects/movement_abilities/grid_movement_ability.tscn" id="8_xuhvf"] [ext_resource type="PackedScene" uid="uid://dre1vit1m4d2n" path="res://objects/movement_abilities/grid_movement_ability.tscn" id="8_xuhvf"]
[ext_resource type="Script" uid="uid://dy78ak8eykw6e" path="res://scripts/components/FlipComponent.cs" id="9_yysbb"] [ext_resource type="Script" uid="uid://dy78ak8eykw6e" path="res://scripts/components/FlipComponent.cs" id="9_yysbb"]
[ext_resource type="Script" uid="uid://mnjg3p0aw1ow" path="res://scripts/components/CanPickUpComponent.cs" id="10_yysbb"] [ext_resource type="Script" uid="uid://mnjg3p0aw1ow" path="res://scripts/components/CanPickUpComponent.cs" id="10_yysbb"]
[ext_resource type="Script" uid="uid://ccqb8kd5m0eh7" path="res://scripts/components/ScoreComponent.cs" id="11_o1ihh"]
[ext_resource type="Script" uid="uid://dgb8bqcri7nsj" path="res://scripts/components/HealthComponent.cs" id="12_ur2y5"] [ext_resource type="Script" uid="uid://dgb8bqcri7nsj" path="res://scripts/components/HealthComponent.cs" id="12_ur2y5"]
[ext_resource type="Script" uid="uid://byw1legrv1ep2" path="res://scripts/components/PlayerDeathComponent.cs" id="13_7til7"] [ext_resource type="Script" uid="uid://byw1legrv1ep2" path="res://scripts/components/PlayerDeathComponent.cs" id="13_7til7"]
[ext_resource type="Script" uid="uid://cecelixl41t3j" path="res://scripts/components/InvulnerabilityComponent.cs" id="15_xuhvf"] [ext_resource type="Script" uid="uid://cecelixl41t3j" path="res://scripts/components/InvulnerabilityComponent.cs" id="15_xuhvf"]
@@ -175,9 +174,6 @@ shape = SubResource("RectangleShape2D_vad0t")
[node name="CanPickUpComponent" type="Node" parent="."] [node name="CanPickUpComponent" type="Node" parent="."]
script = ExtResource("10_yysbb") script = ExtResource("10_yysbb")
[node name="ScoreComponent" type="Node" parent="."]
script = ExtResource("11_o1ihh")
[node name="HealthComponent" type="Node2D" parent="." node_paths=PackedStringArray("HurtSfx", "HealSfx")] [node name="HealthComponent" type="Node2D" parent="." node_paths=PackedStringArray("HurtSfx", "HealSfx")]
script = ExtResource("12_ur2y5") script = ExtResource("12_ur2y5")
HurtSfx = NodePath("../sfx_hurt") HurtSfx = NodePath("../sfx_hurt")

View File

@@ -29,7 +29,6 @@ config/icon="uid://jix7wdn0isr3"
[autoload] [autoload]
GameManager="*res://objects/game_manager.tscn"
PhantomCameraManager="*res://addons/phantom_camera/scripts/managers/phantom_camera_manager.gd" PhantomCameraManager="*res://addons/phantom_camera/scripts/managers/phantom_camera_manager.gd"
AudioController="*res://objects/audio_controller.tscn" AudioController="*res://objects/audio_controller.tscn"
UIManager="*res://Autoloads/UIManager.cs" UIManager="*res://Autoloads/UIManager.cs"
@@ -46,6 +45,12 @@ EventBus="*res://Autoloads/EventBus.cs"
StatisticsManager="*res://Autoloads/StatisticsManager.cs" StatisticsManager="*res://Autoloads/StatisticsManager.cs"
SpeedRunManager="res://Autoloads/SpeedRunManager.cs" SpeedRunManager="res://Autoloads/SpeedRunManager.cs"
GhostManager="res://objects/ghost_manager.tscn" GhostManager="res://objects/ghost_manager.tscn"
StatisticsEventHandler="*res://scripts/Events/StatisticsEventHandler.cs"
CoinStateHandler="*res://scripts/Events/CoinStateHandler.cs"
LevelStateHandler="*res://scripts/Events/LevelStateHandler.cs"
LivesStateHandler="*res://scripts/Events/LivesStateHandler.cs"
GameStateStore="*res://Autoloads/GameStateStore.cs"
GameManager="*res://objects/game_manager.tscn"
[debug] [debug]

25
scripts/Constants.cs Normal file
View File

@@ -0,0 +1,25 @@
namespace Mr.BrickAdventures;
/// <summary>
/// Constants for autoload paths and other commonly used values.
/// </summary>
public static class Constants
{
// Autoload paths
public const string EventBusPath = "/root/EventBus";
public const string GameManagerPath = "/root/GameManager";
public const string GameStateStorePath = "/root/GameStateStore";
public const string SaveSystemPath = "/root/SaveSystem";
public const string SpeedRunManagerPath = "/root/SpeedRunManager";
public const string GhostManagerPath = "/root/GhostManager";
public const string AchievementManagerPath = "/root/AchievementManager";
public const string StatisticsManagerPath = "/root/StatisticsManager";
public const string SkillManagerPath = "/root/SkillManager";
public const string FloatingTextManagerPath = "/root/FloatingTextManager";
public const string UIManagerPath = "/root/UIManager";
public const string ConsoleManagerPath = "/root/ConsoleManager";
public const string ConfigFileHandlerPath = "/root/ConfigFileHandler";
// Group names
public const string CoinsGroup = "coins";
}

1
scripts/Constants.cs.uid Normal file
View File

@@ -0,0 +1 @@
uid://bn7o3n3bomvrd

View File

@@ -0,0 +1,29 @@
using Godot;
using Mr.BrickAdventures.Autoloads;
namespace Mr.BrickAdventures.scripts.Events;
/// <summary>
/// Handles coin collection events and updates the GameStateStore.
/// Replaces the manual coin logic in GameManager.
/// </summary>
public partial class CoinStateHandler : Node
{
public override void _Ready()
{
EventBus.Instance.CoinCollected += OnCoinCollected;
}
public override void _ExitTree()
{
if (EventBus.Instance != null)
{
EventBus.Instance.CoinCollected -= OnCoinCollected;
}
}
private void OnCoinCollected(int amount, Vector2 position)
{
GameStateStore.Instance?.AddSessionCoins(amount);
}
}

View File

@@ -0,0 +1 @@
uid://1qg3q53kkh0k

View File

@@ -1,4 +1,5 @@
using Godot; using Godot;
using Mr.BrickAdventures;
using Mr.BrickAdventures.Autoloads; using Mr.BrickAdventures.Autoloads;
namespace Mr.BrickAdventures.scripts.Events; namespace Mr.BrickAdventures.scripts.Events;
@@ -10,11 +11,10 @@ public partial class GhostEventHandler : Node
public override void _Ready() public override void _Ready()
{ {
_ghostManager = GetNode<GhostManager>("/root/GhostManager"); _ghostManager = GetNode<GhostManager>(Constants.GhostManagerPath);
var eventBus = GetNode<EventBus>("/root/EventBus");
EventBus.Instance.LevelStarted += OnLevelStarted;
eventBus.LevelStarted += OnLevelStarted; EventBus.Instance.LevelCompleted += OnLevelCompleted;
eventBus.LevelCompleted += OnLevelCompleted;
} }
private void OnLevelStarted(int levelIndex, Node currentScene) private void OnLevelStarted(int levelIndex, Node currentScene)
@@ -23,7 +23,7 @@ public partial class GhostEventHandler : Node
_ghostManager.StartRecording(levelIndex); _ghostManager.StartRecording(levelIndex);
_ghostManager.SpawnGhostPlayer(levelIndex, currentScene); _ghostManager.SpawnGhostPlayer(levelIndex, currentScene);
} }
private void OnLevelCompleted(int levelIndex, Node currentScene, double completionTime) private void OnLevelCompleted(int levelIndex, Node currentScene, double completionTime)
{ {
_ghostManager.StopRecording(true, completionTime); _ghostManager.StopRecording(true, completionTime);

View File

@@ -0,0 +1,39 @@
using Godot;
using Mr.BrickAdventures.Autoloads;
namespace Mr.BrickAdventures.scripts.Events;
/// <summary>
/// Handles level completion events and updates GameStateStore.
/// </summary>
public partial class LevelStateHandler : Node
{
public override void _Ready()
{
EventBus.Instance.LevelCompleted += OnLevelCompleted;
}
public override void _ExitTree()
{
if (EventBus.Instance != null)
{
EventBus.Instance.LevelCompleted -= OnLevelCompleted;
}
}
private void OnLevelCompleted(int levelIndex, Node currentScene, double completionTime)
{
var store = GameStateStore.Instance;
if (store == null) return;
// Mark level complete and unlock next
store.MarkLevelComplete(levelIndex);
// Commit session data to persistent state
store.CommitSessionCoins();
store.CommitSessionSkills();
// Reset session for next level
store.ResetSession();
}
}

View File

@@ -0,0 +1 @@
uid://gx5vn7viphv

View File

@@ -0,0 +1,29 @@
using Godot;
using Mr.BrickAdventures.Autoloads;
namespace Mr.BrickAdventures.scripts.Events;
/// <summary>
/// Handles player death events and updates lives in GameStateStore.
/// </summary>
public partial class LivesStateHandler : Node
{
public override void _Ready()
{
EventBus.Instance.PlayerDied += OnPlayerDied;
}
public override void _ExitTree()
{
if (EventBus.Instance != null)
{
EventBus.Instance.PlayerDied -= OnPlayerDied;
}
}
private void OnPlayerDied(Vector2 position)
{
GameStateStore.Instance?.RemoveLife();
GameStateStore.Instance?.ResetSession();
}
}

View File

@@ -0,0 +1 @@
uid://b4ocg7g8vmtvp

View File

@@ -1,4 +1,5 @@
using Godot; using Godot;
using Mr.BrickAdventures;
using Mr.BrickAdventures.Autoloads; using Mr.BrickAdventures.Autoloads;
namespace Mr.BrickAdventures.scripts.Events; namespace Mr.BrickAdventures.scripts.Events;
@@ -10,10 +11,9 @@ public partial class SpeedRunEventHandler : Node
public override void _Ready() public override void _Ready()
{ {
_speedRunManager = GetNode<SpeedRunManager>("/root/SpeedRunManager"); _speedRunManager = GetNode<SpeedRunManager>(Constants.SpeedRunManagerPath);
var eventBus = GetNode<EventBus>("/root/EventBus");
EventBus.Instance.LevelCompleted += OnLevelCompleted;
eventBus.LevelCompleted += OnLevelCompleted;
} }
private void OnLevelCompleted(int levelIndex, Node currentScene, double completionTime) private void OnLevelCompleted(int levelIndex, Node currentScene, double completionTime)

View File

@@ -0,0 +1,62 @@
using Godot;
using Mr.BrickAdventures;
using Mr.BrickAdventures.Autoloads;
namespace Mr.BrickAdventures.scripts.Events;
/// <summary>
/// Handles game events and updates statistics accordingly.
/// Listens to EventBus signals and increments relevant stats.
/// </summary>
public partial class StatisticsEventHandler : Node
{
private StatisticsManager _statisticsManager;
public override void _Ready()
{
_statisticsManager = GetNode<StatisticsManager>(Constants.StatisticsManagerPath);
// Subscribe to events
EventBus.Instance.CoinCollected += OnCoinCollected;
EventBus.Instance.EnemyDefeated += OnEnemyDefeated;
EventBus.Instance.PlayerDied += OnPlayerDied;
EventBus.Instance.LevelCompleted += OnLevelCompleted;
EventBus.Instance.ChildRescued += OnChildRescued;
}
public override void _ExitTree()
{
if (EventBus.Instance == null) return;
EventBus.Instance.CoinCollected -= OnCoinCollected;
EventBus.Instance.EnemyDefeated -= OnEnemyDefeated;
EventBus.Instance.PlayerDied -= OnPlayerDied;
EventBus.Instance.LevelCompleted -= OnLevelCompleted;
EventBus.Instance.ChildRescued -= OnChildRescued;
}
private void OnCoinCollected(int amount, Vector2 position)
{
_statisticsManager.IncrementStat("coins_collected", amount);
}
private void OnEnemyDefeated(Node enemy, Vector2 position)
{
_statisticsManager.IncrementStat("enemies_defeated");
}
private void OnPlayerDied(Vector2 position)
{
_statisticsManager.IncrementStat("deaths");
}
private void OnLevelCompleted(int levelIndex, Node currentScene, double completionTime)
{
_statisticsManager.IncrementStat("levels_completed");
}
private void OnChildRescued(Vector2 position)
{
_statisticsManager.IncrementStat("children_rescued");
}
}

View File

@@ -0,0 +1 @@
uid://l68tjau3k6bw

View File

@@ -0,0 +1,73 @@
using System.Collections.Generic;
using Mr.BrickAdventures.scripts.Resources;
namespace Mr.BrickAdventures.scripts.State;
/// <summary>
/// Persistent player data that survives across sessions.
/// This is a POCO (Plain Old C# Object) for predictable state management.
/// </summary>
public class PlayerState
{
/// <summary>
/// Saved coins (not including current session).
/// </summary>
public int Coins { get; set; }
/// <summary>
/// Remaining lives.
/// </summary>
public int Lives { get; set; } = 3;
/// <summary>
/// Indices of completed levels.
/// </summary>
public List<int> CompletedLevels { get; set; } = new();
/// <summary>
/// Indices of levels the player can access.
/// </summary>
public List<int> UnlockedLevels { get; set; } = new() { 0 };
/// <summary>
/// Skills the player has permanently unlocked.
/// </summary>
public List<SkillData> UnlockedSkills { get; set; } = new();
/// <summary>
/// Statistics dictionary for tracking game stats.
/// </summary>
public Dictionary<string, int> Statistics { get; set; } = new();
/// <summary>
/// IDs of unlocked achievements.
/// </summary>
public List<string> UnlockedAchievements { get; set; } = new();
/// <summary>
/// Creates a fresh default player state.
/// </summary>
public static PlayerState CreateDefault() => new()
{
Coins = 0,
Lives = 3,
CompletedLevels = new List<int>(),
UnlockedLevels = new List<int> { 0 },
UnlockedSkills = new List<SkillData>(),
Statistics = new Dictionary<string, int>()
};
/// <summary>
/// Resets this state to default values.
/// </summary>
public void Reset()
{
Coins = 0;
Lives = 3;
CompletedLevels.Clear();
UnlockedLevels.Clear();
UnlockedLevels.Add(0);
UnlockedSkills.Clear();
Statistics.Clear();
}
}

View File

@@ -0,0 +1 @@
uid://gtr1e60jq7iv

View File

@@ -0,0 +1,55 @@
using System.Collections.Generic;
using Mr.BrickAdventures.scripts.Resources;
namespace Mr.BrickAdventures.scripts.State;
/// <summary>
/// Data for the current gameplay session.
/// Reset when player dies or completes a level.
/// </summary>
public class SessionState
{
/// <summary>
/// Current level index being played.
/// </summary>
public int CurrentLevel { get; set; }
/// <summary>
/// Coins collected during this session (not yet saved).
/// </summary>
public int CoinsCollected { get; set; }
/// <summary>
/// Skills unlocked during this session (not yet saved).
/// </summary>
public List<SkillData> SkillsUnlocked { get; set; } = new();
/// <summary>
/// Creates a fresh session state.
/// </summary>
public static SessionState CreateDefault() => new()
{
CurrentLevel = 0,
CoinsCollected = 0,
SkillsUnlocked = new List<SkillData>()
};
/// <summary>
/// Resets session state to defaults.
/// </summary>
public void Reset()
{
CoinsCollected = 0;
SkillsUnlocked.Clear();
}
/// <summary>
/// Resets completely including level.
/// </summary>
public void ResetAll()
{
CurrentLevel = 0;
CoinsCollected = 0;
SkillsUnlocked.Clear();
}
}

View File

@@ -0,0 +1 @@
uid://chqsdleqrnl7b

View File

@@ -1,4 +1,5 @@
using Godot; using Godot;
using Mr.BrickAdventures;
using Mr.BrickAdventures.Autoloads; using Mr.BrickAdventures.Autoloads;
namespace Mr.BrickAdventures.scripts.UI; namespace Mr.BrickAdventures.scripts.UI;
@@ -10,19 +11,19 @@ public partial class AudioSettings : Control
[Export] public Slider SfxVolumeSlider { get; set; } [Export] public Slider SfxVolumeSlider { get; set; }
[Export] public Control AudioSettingsControl { get; set; } [Export] public Control AudioSettingsControl { get; set; }
[Export] public float MuteThreshold { get; set; } = -20f; [Export] public float MuteThreshold { get; set; } = -20f;
private UIManager _uiManager; private UIManager _uiManager;
private ConfigFileHandler _configFileHandler; private ConfigFileHandler _configFileHandler;
public override void _Ready() public override void _Ready()
{ {
_uiManager = GetNode<UIManager>("/root/UIManager"); _uiManager = GetNode<UIManager>(Constants.UIManagerPath);
_configFileHandler = GetNode<ConfigFileHandler>("/root/ConfigFileHandler"); _configFileHandler = GetNode<ConfigFileHandler>(Constants.ConfigFileHandlerPath);
Initialize(); Initialize();
MasterVolumeSlider.ValueChanged += OnMasterVolumeChanged; MasterVolumeSlider.ValueChanged += OnMasterVolumeChanged;
MusicVolumeSlider.ValueChanged += OnMusicVolumeChanged; MusicVolumeSlider.ValueChanged += OnMusicVolumeChanged;
SfxVolumeSlider.ValueChanged += OnSfxVolumeChanged; SfxVolumeSlider.ValueChanged += OnSfxVolumeChanged;
LoadSettings(); LoadSettings();
} }
@@ -35,7 +36,7 @@ public partial class AudioSettings : Control
{ {
if (!@event.IsActionReleased("ui_cancel")) return; if (!@event.IsActionReleased("ui_cancel")) return;
if (!_uiManager.IsScreenOnTop(AudioSettingsControl)) return; if (!_uiManager.IsScreenOnTop(AudioSettingsControl)) return;
SaveSettings(); SaveSettings();
_uiManager.PopScreen(); _uiManager.PopScreen();
} }
@@ -64,12 +65,12 @@ public partial class AudioSettings : Control
MasterVolumeSlider.Value = volumeDb; MasterVolumeSlider.Value = volumeDb;
MasterVolumeSlider.MinValue = MuteThreshold; MasterVolumeSlider.MinValue = MuteThreshold;
MasterVolumeSlider.MaxValue = 0f; MasterVolumeSlider.MaxValue = 0f;
var musicVolumeDb = AudioServer.GetBusVolumeDb(AudioServer.GetBusIndex("music")); var musicVolumeDb = AudioServer.GetBusVolumeDb(AudioServer.GetBusIndex("music"));
MusicVolumeSlider.Value = musicVolumeDb; MusicVolumeSlider.Value = musicVolumeDb;
MusicVolumeSlider.MinValue = MuteThreshold; MusicVolumeSlider.MinValue = MuteThreshold;
MusicVolumeSlider.MaxValue = 0f; MusicVolumeSlider.MaxValue = 0f;
var sfxVolumeDb = AudioServer.GetBusVolumeDb(AudioServer.GetBusIndex("sfx")); var sfxVolumeDb = AudioServer.GetBusVolumeDb(AudioServer.GetBusIndex("sfx"));
SfxVolumeSlider.Value = sfxVolumeDb; SfxVolumeSlider.Value = sfxVolumeDb;
SfxVolumeSlider.MinValue = MuteThreshold; SfxVolumeSlider.MinValue = MuteThreshold;
@@ -95,12 +96,12 @@ public partial class AudioSettings : Control
{ {
var settingsConfig = _configFileHandler.SettingsConfig; var settingsConfig = _configFileHandler.SettingsConfig;
if (!settingsConfig.HasSection("audio_settings")) return; if (!settingsConfig.HasSection("audio_settings")) return;
var masterVolume = (float)settingsConfig.GetValue("audio_settings", "master_volume", MasterVolumeSlider.Value); var masterVolume = (float)settingsConfig.GetValue("audio_settings", "master_volume", MasterVolumeSlider.Value);
var musicVolume = (float)settingsConfig.GetValue("audio_settings", "music_volume", MusicVolumeSlider.Value); var musicVolume = (float)settingsConfig.GetValue("audio_settings", "music_volume", MusicVolumeSlider.Value);
var sfxVolume = (float)settingsConfig.GetValue("audio_settings", "sfx_volume", SfxVolumeSlider.Value); var sfxVolume = (float)settingsConfig.GetValue("audio_settings", "sfx_volume", SfxVolumeSlider.Value);
var muteThreshold = (float)settingsConfig.GetValue("audio_settings", "mute_threshold", MuteThreshold); var muteThreshold = (float)settingsConfig.GetValue("audio_settings", "mute_threshold", MuteThreshold);
MasterVolumeSlider.Value = masterVolume; MasterVolumeSlider.Value = masterVolume;
MusicVolumeSlider.Value = musicVolume; MusicVolumeSlider.Value = musicVolume;
SfxVolumeSlider.Value = sfxVolume; SfxVolumeSlider.Value = sfxVolume;

View File

@@ -1,4 +1,5 @@
using Godot; using Godot;
using Mr.BrickAdventures;
using Mr.BrickAdventures.Autoloads; using Mr.BrickAdventures.Autoloads;
using Mr.BrickAdventures.scripts.components; using Mr.BrickAdventures.scripts.components;
using Mr.BrickAdventures.scripts.Resources; using Mr.BrickAdventures.scripts.Resources;
@@ -17,15 +18,15 @@ public partial class ChargeProgressBar : ProgressBar
{ {
ProgressBar.Hide(); ProgressBar.Hide();
_skillManager = GetNodeOrNull<SkillManager>("/root/SkillManager"); _skillManager = GetNodeOrNull<SkillManager>(Constants.SkillManagerPath);
if (_skillManager == null) if (_skillManager == null)
{ {
GD.PrintErr("ChargeProgressBar: SkillManager autoload not found."); GD.PrintErr("ChargeProgressBar: SkillManager autoload not found.");
return; return;
} }
_skillManager.ActiveThrowSkillChanged += OnActiveThrowSkillChanged; _skillManager.ActiveThrowSkillChanged += OnActiveThrowSkillChanged;
SetupDependencies(); SetupDependencies();
} }
@@ -43,7 +44,7 @@ public partial class ChargeProgressBar : ProgressBar
OnOwnerExiting(); OnOwnerExiting();
if (throwComponent == null || !IsInstanceValid(throwComponent)) return; if (throwComponent == null || !IsInstanceValid(throwComponent)) return;
_throwComponent = throwComponent; _throwComponent = throwComponent;
_throwComponent.TreeExiting += OnOwnerExiting; _throwComponent.TreeExiting += OnOwnerExiting;
SetupDependencies(); SetupDependencies();
@@ -60,7 +61,7 @@ public partial class ChargeProgressBar : ProgressBar
} }
_throwComponent = null; _throwComponent = null;
} }
private void SetupDependencies() private void SetupDependencies()
{ {
@@ -68,7 +69,7 @@ public partial class ChargeProgressBar : ProgressBar
{ {
return; return;
} }
if (_throwComponent.ThrowInputBehavior is ChargeThrowInputResource throwInput) if (_throwComponent.ThrowInputBehavior is ChargeThrowInputResource throwInput)
{ {
_throwInput = throwInput; _throwInput = throwInput;
@@ -77,7 +78,7 @@ public partial class ChargeProgressBar : ProgressBar
{ {
_throwInput = null; _throwInput = null;
} }
if (_throwInput == null) if (_throwInput == null)
{ {
return; return;
@@ -88,9 +89,9 @@ public partial class ChargeProgressBar : ProgressBar
ProgressBar.Hide(); ProgressBar.Hide();
return; return;
} }
SetupProgressBar(); SetupProgressBar();
_throwInput.ChargeStarted += OnChargeStarted; _throwInput.ChargeStarted += OnChargeStarted;
_throwInput.ChargeStopped += OnChargeStopped; _throwInput.ChargeStopped += OnChargeStopped;
_throwInput.ChargeUpdated += OnChargeUpdated; _throwInput.ChargeUpdated += OnChargeUpdated;

View File

@@ -1,4 +1,5 @@
using Godot; using Godot;
using Mr.BrickAdventures;
using Mr.BrickAdventures.Autoloads; using Mr.BrickAdventures.Autoloads;
namespace Mr.BrickAdventures.scripts.UI; namespace Mr.BrickAdventures.scripts.UI;
@@ -9,7 +10,7 @@ public partial class Credits : Control
public override void _Ready() public override void _Ready()
{ {
_uiManager = GetNode<UIManager>("/root/UIManager"); _uiManager = GetNode<UIManager>(Constants.UIManagerPath);
} }
public override void _UnhandledInput(InputEvent @event) public override void _UnhandledInput(InputEvent @event)

View File

@@ -1,6 +1,8 @@
using Godot; using Godot;
using Mr.BrickAdventures;
using Mr.BrickAdventures.Autoloads; using Mr.BrickAdventures.Autoloads;
using Mr.BrickAdventures.scripts.Resources; using Mr.BrickAdventures.scripts.Resources;
using Mr.BrickAdventures.scripts.State;
namespace Mr.BrickAdventures.scripts.UI; namespace Mr.BrickAdventures.scripts.UI;
@@ -12,27 +14,44 @@ public partial class DeathScreen : Control
[Export] public Label LivesLeftLabel { get; set; } [Export] public Label LivesLeftLabel { get; set; }
[Export] public float TimeoutTime { get; set; } = 2.0f; [Export] public float TimeoutTime { get; set; } = 2.0f;
[Export] public Godot.Collections.Array<Node> NodesToDisable { get; set; } = new(); [Export] public Godot.Collections.Array<Node> NodesToDisable { get; set; } = new();
private GameManager _gameManager; private GameManager _gameManager;
private Timer _timer; private Timer _timer;
public override void _Ready() public override void _Ready()
{ {
_gameManager = GetNode<GameManager>("/root/GameManager"); _gameManager = GetNode<GameManager>(Constants.GameManagerPath);
SetLabels();
// Subscribe to lives changed event for reactive updates
EventBus.Instance.LivesChanged += OnLivesChanged;
} }
public override void _ExitTree()
{
if (EventBus.Instance != null)
{
EventBus.Instance.LivesChanged -= OnLivesChanged;
}
}
private void OnLivesChanged(int lives)
{
// Update the label when lives change
LivesLeftLabel.Text = $" x {lives}";
}
private void SetLabels() private void SetLabels()
{ {
if (_gameManager == null) return;
if (CurrentLevel != null) if (CurrentLevel != null)
{ {
CurrentLevelLabel.Text = CurrentLevel.LevelName; CurrentLevelLabel.Text = CurrentLevel.LevelName;
} }
LivesLeftLabel.Text = $" x {_gameManager.GetLives()}";
// Read current lives from store
var lives = GameStateStore.Instance?.Player.Lives ?? 0;
LivesLeftLabel.Text = $" x {lives}";
} }
private void SetupTimer() private void SetupTimer()
{ {
_timer = new Timer(); _timer = new Timer();
@@ -42,31 +61,32 @@ public partial class DeathScreen : Control
AddChild(_timer); AddChild(_timer);
_timer.Start(); _timer.Start();
} }
private void ToggleNodes() private void ToggleNodes()
{ {
foreach (var node in NodesToDisable) foreach (var node in NodesToDisable)
{ {
node.ProcessMode = node.ProcessMode == ProcessModeEnum.Disabled node.ProcessMode = node.ProcessMode == ProcessModeEnum.Disabled
? ProcessModeEnum.Inherit ? ProcessModeEnum.Inherit
: ProcessModeEnum.Disabled; : ProcessModeEnum.Disabled;
} }
} }
public void OnPlayerDeath() public void OnPlayerDeath()
{ {
if (_gameManager == null) return; if (_gameManager == null) return;
ToggleNodes(); ToggleNodes();
SetLabels(); SetLabels();
Show(); Show();
SetupTimer(); SetupTimer();
} }
private void OnTimeout() private void OnTimeout()
{ {
if (_gameManager == null || _gameManager.GetLives() == 0) return; var lives = GameStateStore.Instance?.Player.Lives ?? 0;
if (lives == 0) return;
GetTree().ReloadCurrentScene(); GetTree().ReloadCurrentScene();
} }
} }

View File

@@ -1,4 +1,5 @@
using Godot; using Godot;
using Mr.BrickAdventures;
using Mr.BrickAdventures.Autoloads; using Mr.BrickAdventures.Autoloads;
namespace Mr.BrickAdventures.scripts.UI; namespace Mr.BrickAdventures.scripts.UI;
@@ -9,14 +10,14 @@ public partial class GameOverScreen : Control
[Export] public Button RestartButton { get; set; } [Export] public Button RestartButton { get; set; }
[Export] public Button MainMenuButton { get; set; } [Export] public Button MainMenuButton { get; set; }
[Export] public PackedScene MainMenuScene { get; set; } [Export] public PackedScene MainMenuScene { get; set; }
private GameManager _gameManager; private GameManager _gameManager;
public override void _Ready() public override void _Ready()
{ {
_gameManager = GetNode<GameManager>("/root/GameManager"); _gameManager = GetNode<GameManager>(Constants.GameManagerPath);
RestartButton.Pressed += OnRestartClicked; RestartButton.Pressed += OnRestartClicked;
MainMenuButton.Pressed += OnMainMenuClicked; MainMenuButton.Pressed += OnMainMenuClicked;
} }
private void OnMainMenuClicked() private void OnMainMenuClicked()
@@ -33,7 +34,7 @@ public partial class GameOverScreen : Control
public void OnPlayerDeath() public void OnPlayerDeath()
{ {
if (_gameManager == null || _gameManager.GetLives() != 0) return; if (_gameManager == null || _gameManager.GetLives() != 0) return;
GameOverPanel.Show(); GameOverPanel.Show();
} }
} }

View File

@@ -1,4 +1,5 @@
using Godot; using Godot;
using Mr.BrickAdventures;
using Mr.BrickAdventures.Autoloads; using Mr.BrickAdventures.Autoloads;
using Mr.BrickAdventures.scripts.components; using Mr.BrickAdventures.scripts.components;
@@ -15,7 +16,7 @@ public partial class Hud : Control
public override void _Ready() public override void _Ready()
{ {
_gameManager = GetNode<GameManager>("/root/GameManager"); _gameManager = GetNode<GameManager>(Constants.GameManagerPath);
} }
public override void _Process(double delta) public override void _Process(double delta)

View File

@@ -1,4 +1,5 @@
using Godot; using Godot;
using Mr.BrickAdventures;
using Mr.BrickAdventures.Autoloads; using Mr.BrickAdventures.Autoloads;
namespace Mr.BrickAdventures.scripts.UI; namespace Mr.BrickAdventures.scripts.UI;
@@ -14,16 +15,16 @@ public partial class MainMenu : Control
[Export] public Label VersionLabel { get; set; } [Export] public Label VersionLabel { get; set; }
[Export] public Control SettingsControl { get; set; } [Export] public Control SettingsControl { get; set; }
[Export] public Control CreditsControl { get; set; } [Export] public Control CreditsControl { get; set; }
private SaveSystem _saveSystem; private SaveSystem _saveSystem;
private GameManager _gameManager; private GameManager _gameManager;
private UIManager _uiManager; private UIManager _uiManager;
public override void _Ready() public override void _Ready()
{ {
_saveSystem = GetNode<SaveSystem>("/root/SaveSystem"); _saveSystem = GetNode<SaveSystem>(Constants.SaveSystemPath);
_gameManager = GetNode<GameManager>("/root/GameManager"); _gameManager = GetNode<GameManager>(Constants.GameManagerPath);
_uiManager = GetNode<UIManager>("/root/UIManager"); _uiManager = GetNode<UIManager>(Constants.UIManagerPath);
NewGameButton.Pressed += OnNewGamePressed; NewGameButton.Pressed += OnNewGamePressed;
ContinueButton.Pressed += OnContinuePressed; ContinueButton.Pressed += OnContinuePressed;

View File

@@ -1,6 +1,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using Godot; using Godot;
using Godot.Collections; using Godot.Collections;
using Mr.BrickAdventures;
using Mr.BrickAdventures.Autoloads; using Mr.BrickAdventures.Autoloads;
using Mr.BrickAdventures.scripts.components; using Mr.BrickAdventures.scripts.components;
using Mr.BrickAdventures.scripts.Resources; using Mr.BrickAdventures.scripts.Resources;
@@ -17,7 +18,7 @@ public partial class Marketplace : Control
[Export] public Array<Node> ComponentsToDisable { get; set; } = []; [Export] public Array<Node> ComponentsToDisable { get; set; } = [];
[Export] public PackedScene MarketplaceButtonScene { get; set; } [Export] public PackedScene MarketplaceButtonScene { get; set; }
[Export] public PackedScene SkillButtonScene { get; set; } [Export] public PackedScene SkillButtonScene { get; set; }
private GameManager _gameManager; private GameManager _gameManager;
private SkillManager _skillManager; private SkillManager _skillManager;
private readonly List<Button> _unlockButtons = []; private readonly List<Button> _unlockButtons = [];
@@ -25,21 +26,21 @@ public partial class Marketplace : Control
public override void _Ready() public override void _Ready()
{ {
_gameManager = GetNode<GameManager>("/root/GameManager"); _gameManager = GetNode<GameManager>(Constants.GameManagerPath);
_skillManager = GetNode<SkillManager>("/root/SkillManager"); _skillManager = GetNode<SkillManager>(Constants.SkillManagerPath);
_skillManager.SkillRemoved += OnSkillRemoved; _skillManager.SkillRemoved += OnSkillRemoved;
Skills = _skillManager.AvailableSkills; Skills = _skillManager.AvailableSkills;
var skillsToUnlock = new List<SkillData>(); var skillsToUnlock = new List<SkillData>();
foreach (var skill in Skills) skillsToUnlock.Add(skill); foreach (var skill in Skills) skillsToUnlock.Add(skill);
foreach (var skill in skillsToUnlock) CreateUpgradeButton(skill); foreach (var skill in skillsToUnlock) CreateUpgradeButton(skill);
var unlockedSkills = _gameManager.GetUnlockedSkills(); var unlockedSkills = _gameManager.GetUnlockedSkills();
foreach (var skill in unlockedSkills) CreateSkillButton(skill); foreach (var skill in unlockedSkills) CreateSkillButton(skill);
SkillUnlockerComponent.SkillUnlocked += OnSkillUnlocked; SkillUnlockerComponent.SkillUnlocked += OnSkillUnlocked;
} }
@@ -51,7 +52,7 @@ public partial class Marketplace : Control
public override void _Input(InputEvent @event) public override void _Input(InputEvent @event)
{ {
if (!@event.IsActionPressed("show_marketplace")) return; if (!@event.IsActionPressed("show_marketplace")) return;
if (IsVisible()) if (IsVisible())
{ {
Hide(); Hide();
@@ -75,7 +76,7 @@ public partial class Marketplace : Control
break; break;
} }
} }
if (!buttonExists) CreateSkillButton(skill); if (!buttonExists) CreateSkillButton(skill);
foreach (var btn in _skillButtons) foreach (var btn in _skillButtons)
@@ -92,7 +93,7 @@ public partial class Marketplace : Control
button.Setup(); button.Setup();
button.Pressed += () => OnSkillButtonPressed(button); button.Pressed += () => OnSkillButtonPressed(button);
button.Activate(); button.Activate();
_skillButtons.Add(button); _skillButtons.Add(button);
UnlockedGrid.AddChild(button); UnlockedGrid.AddChild(button);
UnlockedGrid.QueueSort(); UnlockedGrid.QueueSort();
@@ -104,7 +105,7 @@ public partial class Marketplace : Control
button.Data = skill; button.Data = skill;
button.Icon = skill.Icon; button.Icon = skill.Icon;
button.Pressed += () => OnUpgradeButtonPressed(skill); button.Pressed += () => OnUpgradeButtonPressed(skill);
_unlockButtons.Add(button); _unlockButtons.Add(button);
ToUnlockGrid.AddChild(button); ToUnlockGrid.AddChild(button);
ToUnlockGrid.QueueSort(); ToUnlockGrid.QueueSort();
@@ -133,7 +134,7 @@ public partial class Marketplace : Control
private void OnSkillButtonPressed(SkillButton button) private void OnSkillButtonPressed(SkillButton button)
{ {
SkillUnlockerComponent.SkillManager.ToggleSkillActivation(button.Data); SkillUnlockerComponent.SkillManager.ToggleSkillActivation(button.Data);
foreach (var btn in _skillButtons) foreach (var btn in _skillButtons)
{ {
if (btn.Data.IsActive) if (btn.Data.IsActive)
@@ -142,7 +143,7 @@ public partial class Marketplace : Control
btn.Deactivate(); btn.Deactivate();
} }
} }
private void OnSkillRemoved(SkillData skill) private void OnSkillRemoved(SkillData skill)
{ {
SkillButton buttonToRemove = null; SkillButton buttonToRemove = null;

View File

@@ -1,4 +1,5 @@
using Godot; using Godot;
using Mr.BrickAdventures;
using Mr.BrickAdventures.Autoloads; using Mr.BrickAdventures.Autoloads;
using Mr.BrickAdventures.scripts.components; using Mr.BrickAdventures.scripts.components;
using Mr.BrickAdventures.scripts.Resources; using Mr.BrickAdventures.scripts.Resources;
@@ -11,26 +12,26 @@ public partial class MarketplaceButton : Button
[Export] public Texture2D UnlockedSkillIcon { get; set; } [Export] public Texture2D UnlockedSkillIcon { get; set; }
[Export] public Texture2D LockedSkillIcon { get; set; } [Export] public Texture2D LockedSkillIcon { get; set; }
[Export] public Container SkillLevelContainer { get; set; } [Export] public Container SkillLevelContainer { get; set; }
private GameManager _gameManager; private GameManager _gameManager;
private SkillUnlockerComponent _skillUnlockerComponent; private SkillUnlockerComponent _skillUnlockerComponent;
private SkillManager _skillManager; private SkillManager _skillManager;
public override void _Ready() public override void _Ready()
{ {
_gameManager = GetNode<GameManager>("/root/GameManager"); _gameManager = GetNode<GameManager>(Constants.GameManagerPath);
var player = _gameManager.Player; var player = _gameManager.Player;
if (player == null) return; if (player == null) return;
_skillUnlockerComponent = player.GetNodeOrNull<SkillUnlockerComponent>("SkillUnlockerComponent"); _skillUnlockerComponent = player.GetNodeOrNull<SkillUnlockerComponent>("SkillUnlockerComponent");
if (_skillUnlockerComponent != null) if (_skillUnlockerComponent != null)
{ {
_skillUnlockerComponent.SkillUnlocked += OnSkillStateChanged; _skillUnlockerComponent.SkillUnlocked += OnSkillStateChanged;
} }
_skillManager = GetNode<SkillManager>("/root/SkillManager"); _skillManager = GetNode<SkillManager>(Constants.SkillManagerPath);
_skillManager.SkillRemoved += OnSkillStateChanged; _skillManager.SkillRemoved += OnSkillStateChanged;
UpdateButtonState(); UpdateButtonState();
} }
@@ -41,7 +42,7 @@ public partial class MarketplaceButton : Button
_skillUnlockerComponent.SkillUnlocked -= OnSkillStateChanged; _skillUnlockerComponent.SkillUnlocked -= OnSkillStateChanged;
} }
} }
private void OnSkillStateChanged(SkillData skill) private void OnSkillStateChanged(SkillData skill)
{ {
if (skill.Name == Data.Name) if (skill.Name == Data.Name)
@@ -59,7 +60,7 @@ public partial class MarketplaceButton : Button
} }
var isUnlocked = _gameManager.IsSkillUnlocked(Data); var isUnlocked = _gameManager.IsSkillUnlocked(Data);
for (var i = 0; i < SkillLevelContainer.GetChildCount(); i++) for (var i = 0; i < SkillLevelContainer.GetChildCount(); i++)
{ {
SkillLevelContainer.GetChild(i).QueueFree(); SkillLevelContainer.GetChild(i).QueueFree();

View File

@@ -1,4 +1,5 @@
using Godot; using Godot;
using Mr.BrickAdventures;
using Mr.BrickAdventures.Autoloads; using Mr.BrickAdventures.Autoloads;
namespace Mr.BrickAdventures.scripts.UI; namespace Mr.BrickAdventures.scripts.UI;
@@ -18,8 +19,8 @@ public partial class PauseMenu : Control
public override void _Ready() public override void _Ready()
{ {
_gameManager = GetNode<GameManager>("/root/GameManager"); _gameManager = GetNode<GameManager>(Constants.GameManagerPath);
_uiManager = GetNode<UIManager>("/root/UIManager"); _uiManager = GetNode<UIManager>(Constants.UIManagerPath);
ResumeButton.Pressed += OnResumePressed; ResumeButton.Pressed += OnResumePressed;
MainMenuButton.Pressed += OnMainMenuPressed; MainMenuButton.Pressed += OnMainMenuPressed;

View File

@@ -1,4 +1,5 @@
using Godot; using Godot;
using Mr.BrickAdventures;
using Mr.BrickAdventures.Autoloads; using Mr.BrickAdventures.Autoloads;
namespace Mr.BrickAdventures.scripts.UI; namespace Mr.BrickAdventures.scripts.UI;
@@ -14,18 +15,18 @@ public partial class SettingsMenu : Control
[Export] public Button AudioSettingsButton { get; set; } [Export] public Button AudioSettingsButton { get; set; }
[Export] public Button DisplaySettingsButton { get; set; } [Export] public Button DisplaySettingsButton { get; set; }
[Export] public Button GameplaySettingsButton { get; set; } [Export] public Button GameplaySettingsButton { get; set; }
private UIManager _uiManager; private UIManager _uiManager;
public override void _Ready() public override void _Ready()
{ {
_uiManager = GetNode<UIManager>("/root/UIManager"); _uiManager = GetNode<UIManager>(Constants.UIManagerPath);
InputSettingsButton.Pressed += OnInputSettingsPressed; InputSettingsButton.Pressed += OnInputSettingsPressed;
AudioSettingsButton.Pressed += OnAudioSettingsPressed; AudioSettingsButton.Pressed += OnAudioSettingsPressed;
DisplaySettingsButton.Pressed += OnDisplaySettingsPressed; DisplaySettingsButton.Pressed += OnDisplaySettingsPressed;
GameplaySettingsButton.Pressed += OnGameplaySettingsPressed; GameplaySettingsButton.Pressed += OnGameplaySettingsPressed;
InputSettingsControl?.Hide(); InputSettingsControl?.Hide();
AudioSettingsControl?.Hide(); AudioSettingsControl?.Hide();
DisplaySettingsControl?.Hide(); DisplaySettingsControl?.Hide();

View File

@@ -1,4 +1,5 @@
using Godot; using Godot;
using Mr.BrickAdventures;
using Mr.BrickAdventures.Autoloads; using Mr.BrickAdventures.Autoloads;
namespace Mr.BrickAdventures.scripts.UI; namespace Mr.BrickAdventures.scripts.UI;
@@ -7,15 +8,15 @@ namespace Mr.BrickAdventures.scripts.UI;
public partial class SpeedRunHud : Control public partial class SpeedRunHud : Control
{ {
[Export] private Label _timerLabel; [Export] private Label _timerLabel;
private SpeedRunManager _speedRunManager; private SpeedRunManager _speedRunManager;
public override void _Ready() public override void _Ready()
{ {
_speedRunManager = GetNode<SpeedRunManager>("/root/SpeedRunManager"); _speedRunManager = GetNode<SpeedRunManager>(Constants.SpeedRunManagerPath);
_speedRunManager.TimeUpdated += OnTimerUpdated; _speedRunManager.TimeUpdated += OnTimerUpdated;
Visible = _speedRunManager.IsVisible; Visible = _speedRunManager.IsVisible;
} }

View File

@@ -1,4 +1,5 @@
using Godot; using Godot;
using Mr.BrickAdventures;
using Mr.BrickAdventures.Autoloads; using Mr.BrickAdventures.Autoloads;
using Mr.BrickAdventures.scripts.interfaces; using Mr.BrickAdventures.scripts.interfaces;
using Mr.BrickAdventures.scripts.Resources; using Mr.BrickAdventures.scripts.Resources;
@@ -9,7 +10,7 @@ namespace Mr.BrickAdventures.scripts.components;
public partial class BrickShieldSkillComponent : Node, ISkill public partial class BrickShieldSkillComponent : Node, ISkill
{ {
[Export] public PackedScene ShieldScene { get; set; } [Export] public PackedScene ShieldScene { get; set; }
private PlayerController _player; private PlayerController _player;
private Node2D _shieldInstance; private Node2D _shieldInstance;
private SkillData _skillData; private SkillData _skillData;
@@ -19,8 +20,8 @@ public partial class BrickShieldSkillComponent : Node, ISkill
public override void _Ready() public override void _Ready()
{ {
_gameManager = GetNode<GameManager>("/root/GameManager"); _gameManager = GetNode<GameManager>(Constants.GameManagerPath);
_skillManager = GetNode<SkillManager>("/root/SkillManager"); _skillManager = GetNode<SkillManager>(Constants.SkillManagerPath);
} }
public void Initialize(Node owner, SkillData data) public void Initialize(Node owner, SkillData data)
@@ -59,7 +60,7 @@ public partial class BrickShieldSkillComponent : Node, ISkill
_shieldHealth.MaxHealth = (float)newHealth; _shieldHealth.MaxHealth = (float)newHealth;
} }
} }
private void OnShieldDestroyed() private void OnShieldDestroyed()
{ {
if (_gameManager != null && _skillData != null && _skillManager != null) if (_gameManager != null && _skillData != null && _skillManager != null)

View File

@@ -1,5 +1,6 @@
using System; using System;
using Godot; using Godot;
using Mr.BrickAdventures;
using Mr.BrickAdventures.Autoloads; using Mr.BrickAdventures.Autoloads;
using Mr.BrickAdventures.scripts.Resources; using Mr.BrickAdventures.scripts.Resources;
@@ -35,7 +36,7 @@ public partial class CollectableComponent : Node
if (Owner.HasNode("FadeAwayComponent")) if (Owner.HasNode("FadeAwayComponent"))
_hasFadeAway = true; _hasFadeAway = true;
_floatingTextManager = GetNode<FloatingTextManager>("/root/FloatingTextManager"); _floatingTextManager = GetNode<FloatingTextManager>(Constants.FloatingTextManagerPath);
} }
private async void OnArea2DBodyEntered(Node2D body) private async void OnArea2DBodyEntered(Node2D body)
@@ -53,12 +54,18 @@ public partial class CollectableComponent : Node
{ {
case CollectableType.Coin: case CollectableType.Coin:
_floatingTextManager?.ShowCoin((int)Data.Amount, ownerNode.GlobalPosition); _floatingTextManager?.ShowCoin((int)Data.Amount, ownerNode.GlobalPosition);
EventBus.EmitCoinCollected((int)Data.Amount, ownerNode.GlobalPosition);
break; break;
case CollectableType.Health: case CollectableType.Health:
_floatingTextManager?.ShowMessage("Healed!", ownerNode.GlobalPosition); _floatingTextManager?.ShowMessage("Healed!", ownerNode.GlobalPosition);
EventBus.EmitItemCollected(Data.Type, Data.Amount, ownerNode.GlobalPosition);
break; break;
case CollectableType.Kid: case CollectableType.Kid:
_floatingTextManager?.ShowMessage("Rescued!", ownerNode.GlobalPosition); _floatingTextManager?.ShowMessage("Rescued!", ownerNode.GlobalPosition);
EventBus.EmitChildRescued(ownerNode.GlobalPosition);
break;
default:
EventBus.EmitItemCollected(Data.Type, Data.Amount, ownerNode.GlobalPosition);
break; break;
} }
} }

View File

@@ -1,5 +1,6 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using Godot; using Godot;
using Mr.BrickAdventures.Autoloads;
namespace Mr.BrickAdventures.scripts.components; namespace Mr.BrickAdventures.scripts.components;
@@ -23,7 +24,7 @@ public partial class EnemyDeathComponent : Node
GD.PushError("EnemyDeathComponent: Health is not set."); GD.PushError("EnemyDeathComponent: Health is not set.");
return; return;
} }
Health.Death += OnDeath; Health.Death += OnDeath;
} }
@@ -34,6 +35,12 @@ public partial class EnemyDeathComponent : Node
private async Task Die() private async Task Die()
{ {
// Emit enemy defeated event for statistics and other systems
if (Owner is Node2D ownerNode)
{
EventBus.EmitEnemyDefeated(Owner, ownerNode.GlobalPosition);
}
CollisionShape.SetDisabled(true); CollisionShape.SetDisabled(true);
var tween = CreateTween(); var tween = CreateTween();
tween.TweenProperty(Owner, "scale", Vector2.Zero, TweenDuration); tween.TweenProperty(Owner, "scale", Vector2.Zero, TweenDuration);

View File

@@ -1,6 +1,8 @@
using Godot; using Godot;
using Mr.BrickAdventures;
using Mr.BrickAdventures.Autoloads; using Mr.BrickAdventures.Autoloads;
using Mr.BrickAdventures.scripts.interfaces; using Mr.BrickAdventures.scripts.interfaces;
using Mr.BrickAdventures.scripts.State;
namespace Mr.BrickAdventures.scripts.components; namespace Mr.BrickAdventures.scripts.components;
@@ -12,28 +14,30 @@ public partial class ExitDoorComponent : Area2D, IUnlockable
[Export] public AudioStreamPlayer2D OpenDoorSfx { get; set; } [Export] public AudioStreamPlayer2D OpenDoorSfx { get; set; }
[Export] public int OpenedDoorFrame { get; set; } = 0; [Export] public int OpenedDoorFrame { get; set; } = 0;
[Export] public string AchievementId = "level_complete_1"; [Export] public string AchievementId = "level_complete_1";
[Signal] public delegate void ExitTriggeredEventHandler(); [Signal] public delegate void ExitTriggeredEventHandler();
private GameManager _gameManager; private GameManager _gameManager;
private AchievementManager _achievementManager; private AchievementManager _achievementManager;
public override void _Ready() public override void _Ready()
{ {
_gameManager = GetNode<GameManager>("/root/GameManager"); _gameManager = GetNode<GameManager>(Constants.GameManagerPath);
_achievementManager = GetNode<AchievementManager>("/root/AchievementManager"); _achievementManager = GetNode<AchievementManager>(Constants.AchievementManagerPath);
BodyEntered += OnExitAreaBodyEntered; BodyEntered += OnExitAreaBodyEntered;
} }
private void OnExitAreaBodyEntered(Node2D body) private void OnExitAreaBodyEntered(Node2D body)
{ {
if (Locked) return; if (Locked) return;
EmitSignalExitTriggered(); EmitSignalExitTriggered();
_achievementManager.UnlockAchievement(AchievementId); _achievementManager.UnlockAchievement(AchievementId);
_gameManager.UnlockLevel((int)_gameManager.PlayerState["current_level"] + 1); // Get current level from GameStateStore
var currentLevel = GameStateStore.Instance?.Session.CurrentLevel ?? 0;
_gameManager.UnlockLevel(currentLevel + 1);
CallDeferred(nameof(GoToNextLevel)); CallDeferred(nameof(GoToNextLevel));
} }

View File

@@ -1,5 +1,6 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using Godot; using Godot;
using Mr.BrickAdventures;
using Mr.BrickAdventures.Autoloads; using Mr.BrickAdventures.Autoloads;
namespace Mr.BrickAdventures.scripts.components; namespace Mr.BrickAdventures.scripts.components;
@@ -11,22 +12,22 @@ public partial class HealthComponent : Node2D
[Export] public float MaxHealth { get; set; } = 1.0f; [Export] public float MaxHealth { get; set; } = 1.0f;
[Export] public AudioStreamPlayer2D HurtSfx { get; set; } [Export] public AudioStreamPlayer2D HurtSfx { get; set; }
[Export] public AudioStreamPlayer2D HealSfx { get; set; } [Export] public AudioStreamPlayer2D HealSfx { get; set; }
[Signal] public delegate void HealthChangedEventHandler(float delta, float totalHealth); [Signal] public delegate void HealthChangedEventHandler(float delta, float totalHealth);
[Signal] public delegate void DeathEventHandler(); [Signal] public delegate void DeathEventHandler();
private FloatingTextManager _floatingTextManager; private FloatingTextManager _floatingTextManager;
public override void _Ready() public override void _Ready()
{ {
_floatingTextManager = GetNode<FloatingTextManager>("/root/FloatingTextManager"); _floatingTextManager = GetNode<FloatingTextManager>(Constants.FloatingTextManagerPath);
} }
public void SetHealth(float newValue) public void SetHealth(float newValue)
{ {
_ = ApplyHealthChange(newValue); _ = ApplyHealthChange(newValue);
} }
public void IncreaseHealth(float delta) public void IncreaseHealth(float delta)
{ {
_ = ApplyHealthChange(Health + delta); _ = ApplyHealthChange(Health + delta);
@@ -46,7 +47,7 @@ public partial class HealthComponent : Node2D
if (delta == 0.0f) if (delta == 0.0f)
return; return;
if (delta < 0.0f) if (delta < 0.0f)
_floatingTextManager?.ShowDamage(Mathf.Abs(delta), GlobalPosition); _floatingTextManager?.ShowDamage(Mathf.Abs(delta), GlobalPosition);
else else
@@ -64,16 +65,27 @@ public partial class HealthComponent : Node2D
await HurtSfx.ToSignal(HurtSfx, AudioStreamPlayer2D.SignalName.Finished); await HurtSfx.ToSignal(HurtSfx, AudioStreamPlayer2D.SignalName.Finished);
} }
} }
Health = newHealth; Health = newHealth;
if (Health <= 0f) if (Health <= 0f)
{ {
EmitSignalDeath(); EmitSignalDeath();
// Emit global event if this is the player
if (Owner is PlayerController)
EventBus.EmitPlayerDied(GlobalPosition);
} }
else else
{ {
EmitSignalHealthChanged(delta, Health); EmitSignalHealthChanged(delta, Health);
// Emit global events if this is the player
if (Owner is PlayerController)
{
if (delta < 0f)
EventBus.EmitPlayerDamaged(Mathf.Abs(delta), Health, GlobalPosition);
else
EventBus.EmitPlayerHealed(delta, Health, GlobalPosition);
}
} }
} }
} }

View File

@@ -1,5 +1,6 @@
using System.Threading.Tasks; using System.Threading.Tasks;
using Godot; using Godot;
using Mr.BrickAdventures;
using Mr.BrickAdventures.Autoloads; using Mr.BrickAdventures.Autoloads;
namespace Mr.BrickAdventures.scripts.components; namespace Mr.BrickAdventures.scripts.components;
@@ -15,25 +16,25 @@ public partial class LeverComponent : Node
[Signal] [Signal]
public delegate void ActivatedEventHandler(); public delegate void ActivatedEventHandler();
private FloatingTextManager _floatingTextManager; private FloatingTextManager _floatingTextManager;
public override void _Ready() public override void _Ready()
{ {
_floatingTextManager = GetNode<FloatingTextManager>("/root/FloatingTextManager"); _floatingTextManager = GetNode<FloatingTextManager>(Constants.FloatingTextManagerPath);
if (Area == null) if (Area == null)
{ {
GD.PushError("LeverComponent: Area is not set."); GD.PushError("LeverComponent: Area is not set.");
return; return;
} }
if (Sprite == null) if (Sprite == null)
{ {
GD.PushError("LeverComponent: Sprite is not set."); GD.PushError("LeverComponent: Sprite is not set.");
return; return;
} }
Area.BodyEntered += OnBodyEntered; Area.BodyEntered += OnBodyEntered;
Area.AreaEntered += OnAreaEntered; Area.AreaEntered += OnAreaEntered;
} }
@@ -58,7 +59,7 @@ public partial class LeverComponent : Node
await timer.ToSignal(timer, Timer.SignalName.Timeout); await timer.ToSignal(timer, Timer.SignalName.Timeout);
Sprite.Frame = StartAnimationIndex; Sprite.Frame = StartAnimationIndex;
} }
private void HandleTriggerLogic(Node2D obj) private void HandleTriggerLogic(Node2D obj)
{ {
var triggerLever = obj.GetNodeOrNull<TriggerLeverComponent>("TriggerLeverComponent"); var triggerLever = obj.GetNodeOrNull<TriggerLeverComponent>("TriggerLeverComponent");

View File

@@ -2,6 +2,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Godot; using Godot;
using Mr.BrickAdventures;
using Mr.BrickAdventures.Autoloads; using Mr.BrickAdventures.Autoloads;
namespace Mr.BrickAdventures.scripts.components; namespace Mr.BrickAdventures.scripts.components;
@@ -10,7 +11,7 @@ namespace Mr.BrickAdventures.scripts.components;
public partial class PlayerController : CharacterBody2D public partial class PlayerController : CharacterBody2D
{ {
[Export] private Node MovementAbilitiesContainer { get; set; } [Export] private Node MovementAbilitiesContainer { get; set; }
[ExportGroup("Movement Ability Scenes")] [ExportGroup("Movement Ability Scenes")]
[Export] public PackedScene GroundMovementScene { get; set; } [Export] public PackedScene GroundMovementScene { get; set; }
[Export] public PackedScene JumpMovementScene { get; set; } [Export] public PackedScene JumpMovementScene { get; set; }
@@ -19,23 +20,23 @@ public partial class PlayerController : CharacterBody2D
[Export] public PackedScene SpaceshipMovementScene { get; set; } [Export] public PackedScene SpaceshipMovementScene { get; set; }
[Export] public PackedScene WallJumpScene { get; set; } [Export] public PackedScene WallJumpScene { get; set; }
[Export] public PackedScene GridMovementScene { get; set; } [Export] public PackedScene GridMovementScene { get; set; }
[Signal] public delegate void JumpInitiatedEventHandler(); [Signal] public delegate void JumpInitiatedEventHandler();
[Signal] public delegate void MovementAbilitiesChangedEventHandler(); [Signal] public delegate void MovementAbilitiesChangedEventHandler();
public Vector2 LastDirection { get; private set; } = Vector2.Right; public Vector2 LastDirection { get; private set; } = Vector2.Right;
public Vector2 PreviousVelocity { get; private set; } = Vector2.Zero; public Vector2 PreviousVelocity { get; private set; } = Vector2.Zero;
private List<MovementAbility> _abilities = []; private List<MovementAbility> _abilities = [];
private PlayerInputHandler _inputHandler; private PlayerInputHandler _inputHandler;
public IReadOnlyList<MovementAbility> GetActiveAbilities() => _abilities; public IReadOnlyList<MovementAbility> GetActiveAbilities() => _abilities;
public override void _Ready() public override void _Ready()
{ {
var skillManager = GetNodeOrNull<SkillManager>("/root/SkillManager"); var skillManager = GetNodeOrNull<SkillManager>(Constants.SkillManagerPath);
skillManager?.RegisterPlayer(this); skillManager?.RegisterPlayer(this);
_inputHandler = GetNode<PlayerInputHandler>("PlayerInputHandler"); _inputHandler = GetNode<PlayerInputHandler>("PlayerInputHandler");
foreach (var child in MovementAbilitiesContainer.GetChildren()) foreach (var child in MovementAbilitiesContainer.GetChildren())
{ {
@@ -45,20 +46,20 @@ public partial class PlayerController : CharacterBody2D
_abilities.Add(ability); _abilities.Add(ability);
} }
} }
_ = ConnectJumpAndGravityAbilities(); _ = ConnectJumpAndGravityAbilities();
EmitSignalMovementAbilitiesChanged(); EmitSignalMovementAbilitiesChanged();
} }
public override void _PhysicsProcess(double delta) public override void _PhysicsProcess(double delta)
{ {
var velocity = Velocity; var velocity = Velocity;
foreach (var ability in _abilities) foreach (var ability in _abilities)
{ {
velocity = ability.ProcessMovement(velocity, delta); velocity = ability.ProcessMovement(velocity, delta);
} }
if (_inputHandler.MoveDirection.X != 0) if (_inputHandler.MoveDirection.X != 0)
{ {
LastDirection = new Vector2(_inputHandler.MoveDirection.X > 0 ? 1 : -1, 0); LastDirection = new Vector2(_inputHandler.MoveDirection.X > 0 ? 1 : -1, 0);
@@ -68,14 +69,14 @@ public partial class PlayerController : CharacterBody2D
Velocity = velocity; Velocity = velocity;
MoveAndSlide(); MoveAndSlide();
} }
public void AddAbility(MovementAbility ability) public void AddAbility(MovementAbility ability)
{ {
MovementAbilitiesContainer.AddChild(ability); MovementAbilitiesContainer.AddChild(ability);
ability.Initialize(this); ability.Initialize(this);
_abilities.Add(ability); _abilities.Add(ability);
} }
public void ClearMovementAbilities() public void ClearMovementAbilities()
{ {
foreach (var ability in _abilities) foreach (var ability in _abilities)
@@ -84,7 +85,7 @@ public partial class PlayerController : CharacterBody2D
} }
_abilities.Clear(); _abilities.Clear();
} }
public void RemoveAbility<T>() where T : MovementAbility public void RemoveAbility<T>() where T : MovementAbility
{ {
for (var i = _abilities.Count - 1; i >= 0; i--) for (var i = _abilities.Count - 1; i >= 0; i--)
@@ -102,20 +103,20 @@ public partial class PlayerController : CharacterBody2D
public void SetPlatformMovement() public void SetPlatformMovement()
{ {
ClearMovementAbilities(); ClearMovementAbilities();
if (GroundMovementScene != null) AddAbility(GroundMovementScene.Instantiate<MovementAbility>()); if (GroundMovementScene != null) AddAbility(GroundMovementScene.Instantiate<MovementAbility>());
if (JumpMovementScene != null) AddAbility(JumpMovementScene.Instantiate<MovementAbility>()); if (JumpMovementScene != null) AddAbility(JumpMovementScene.Instantiate<MovementAbility>());
if (GravityScene != null) AddAbility(GravityScene.Instantiate<MovementAbility>()); if (GravityScene != null) AddAbility(GravityScene.Instantiate<MovementAbility>());
if (OneWayPlatformScene != null) AddAbility(OneWayPlatformScene.Instantiate<MovementAbility>()); if (OneWayPlatformScene != null) AddAbility(OneWayPlatformScene.Instantiate<MovementAbility>());
_ = ConnectJumpAndGravityAbilities(); _ = ConnectJumpAndGravityAbilities();
EmitSignalMovementAbilitiesChanged(); EmitSignalMovementAbilitiesChanged();
} }
public void SetSpaceshipMovement() public void SetSpaceshipMovement()
{ {
ClearMovementAbilities(); ClearMovementAbilities();
if (SpaceshipMovementScene != null) AddAbility(SpaceshipMovementScene.Instantiate<MovementAbility>()); if (SpaceshipMovementScene != null) AddAbility(SpaceshipMovementScene.Instantiate<MovementAbility>());
EmitSignalMovementAbilitiesChanged(); EmitSignalMovementAbilitiesChanged();
} }
@@ -130,10 +131,10 @@ public partial class PlayerController : CharacterBody2D
private async Task ConnectJumpAndGravityAbilities() private async Task ConnectJumpAndGravityAbilities()
{ {
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame); await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
var jumpAbility = _abilities.OfType<VariableJumpAbility>().FirstOrDefault(); var jumpAbility = _abilities.OfType<VariableJumpAbility>().FirstOrDefault();
var gravityAbility = _abilities.OfType<GravityAbility>().FirstOrDefault(); var gravityAbility = _abilities.OfType<GravityAbility>().FirstOrDefault();
if (jumpAbility != null && gravityAbility != null) if (jumpAbility != null && gravityAbility != null)
{ {
gravityAbility.AscendGravity = jumpAbility.AscendGravity; gravityAbility.AscendGravity = jumpAbility.AscendGravity;

View File

@@ -1,4 +1,5 @@
using Godot; using Godot;
using Mr.BrickAdventures;
using Mr.BrickAdventures.Autoloads; using Mr.BrickAdventures.Autoloads;
namespace Mr.BrickAdventures.scripts.components; namespace Mr.BrickAdventures.scripts.components;
@@ -10,12 +11,12 @@ public partial class PlayerDeathComponent : Node2D
[Export] public PackedScene DeathEffect { get; set; } [Export] public PackedScene DeathEffect { get; set; }
[Export] public HealthComponent HealthComponent { get; set; } [Export] public HealthComponent HealthComponent { get; set; }
[Export] public Vector2 EffectScale { get; set; } = new Vector2(1.5f, 1.5f); [Export] public Vector2 EffectScale { get; set; } = new Vector2(1.5f, 1.5f);
private GameManager _gameManager; private GameManager _gameManager;
public override void _Ready() public override void _Ready()
{ {
_gameManager = GetNode<GameManager>("/root/GameManager"); _gameManager = GetNode<GameManager>(Constants.GameManagerPath);
HealthComponent.Death += OnDeath; HealthComponent.Death += OnDeath;
} }
@@ -30,8 +31,8 @@ public partial class PlayerDeathComponent : Node2D
effect.GlobalPosition = GlobalPosition; effect.GlobalPosition = GlobalPosition;
effect.Scale = EffectScale; effect.Scale = EffectScale;
} }
_gameManager.RemoveLives(1); // Lives are now decremented by LivesStateHandler via PlayerDied event
_gameManager.ResetCurrentSessionState(); // Session state is reset by LivesStateHandler as well
} }
} }

View File

@@ -1,43 +0,0 @@
using Godot;
using Mr.BrickAdventures.Autoloads;
using Mr.BrickAdventures.scripts.Resources;
namespace Mr.BrickAdventures.scripts.components;
[GlobalClass]
public partial class ScoreComponent : Node
{
private GameManager _gameManager;
private const string CoinsGroupName = "coins";
public override async void _Ready()
{
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
_gameManager = GetNode<GameManager>("/root/GameManager");
if (_gameManager == null)
{
GD.PrintErr("GameManager not found in the scene tree.");
return;
}
var coins = GetTree().GetNodesInGroup(CoinsGroupName);
foreach (var coin in coins)
{
var c = coin.GetNodeOrNull<CollectableComponent>("CollectableComponent");
if (c != null)
{
c.Collected += OnCollected;
}
}
}
private void OnCollected(float amount, CollectableType type, Node2D body)
{
if (type != CollectableType.Coin) return;
var coinAmount = (int)amount;
var currentCoins = (int)_gameManager.CurrentSessionState["coins_collected"];
_gameManager.CurrentSessionState["coins_collected"] = currentCoins + coinAmount;
}
}

View File

@@ -1 +0,0 @@
uid://ccqb8kd5m0eh7

View File

@@ -1,8 +1,10 @@
using Godot; using Godot;
using Godot.Collections; using Godot.Collections;
using Mr.BrickAdventures;
using Mr.BrickAdventures.Autoloads; using Mr.BrickAdventures.Autoloads;
using Mr.BrickAdventures.scripts.interfaces; using Mr.BrickAdventures.scripts.interfaces;
using Mr.BrickAdventures.scripts.Resources; using Mr.BrickAdventures.scripts.Resources;
using Mr.BrickAdventures.scripts.State;
namespace Mr.BrickAdventures.scripts.components; namespace Mr.BrickAdventures.scripts.components;
@@ -18,8 +20,8 @@ public partial class SkillUnlockerComponent : Node
public override void _Ready() public override void _Ready()
{ {
_gameManager = GetNode<GameManager>("/root/GameManager"); _gameManager = GetNode<GameManager>(Constants.GameManagerPath);
SkillManager = GetNode<SkillManager>("/root/SkillManager"); SkillManager = GetNode<SkillManager>(Constants.SkillManagerPath);
} }
private bool HasEnoughCoins(int amount) private bool HasEnoughCoins(int amount)
@@ -37,8 +39,8 @@ public partial class SkillUnlockerComponent : Node
skill.IsActive = true; skill.IsActive = true;
_gameManager.RemoveCoins(skill.Upgrades[0].Cost); _gameManager.RemoveCoins(skill.Upgrades[0].Cost);
var skillsUnlocked = (Array<SkillData>)_gameManager.CurrentSessionState["skills_unlocked"]; // Add to session state via GameStateStore
skillsUnlocked.Add(skill); GameStateStore.Instance?.UnlockSkillInSession(skill);
SkillManager.AddSkill(skill); SkillManager.AddSkill(skill);
EmitSignalSkillUnlocked(skill); EmitSignalSkillUnlocked(skill);