Revamp the puzzle registration system
This commit is contained in:
@@ -5,7 +5,10 @@ using System.Linq;
|
||||
using UnityEngine;
|
||||
using UnityEngine.SceneManagement;
|
||||
using AppleHills.Core.Settings;
|
||||
using Core; // Added for IInteractionSettings
|
||||
using Core;
|
||||
using UnityEngine.AddressableAssets;
|
||||
using UnityEngine.ResourceManagement.AsyncOperations;
|
||||
using Utils;
|
||||
|
||||
namespace PuzzleS
|
||||
{
|
||||
@@ -26,6 +29,11 @@ namespace PuzzleS
|
||||
// Settings reference
|
||||
private IInteractionSettings _interactionSettings;
|
||||
|
||||
// Current level puzzle data
|
||||
private PuzzleLevelDataSO _currentLevelData;
|
||||
private AsyncOperationHandle<PuzzleLevelDataSO> _levelDataLoadOperation;
|
||||
private bool _isLoadingLevelData = false;
|
||||
|
||||
/// <summary>
|
||||
/// Singleton instance of the PuzzleManager.
|
||||
/// </summary>
|
||||
@@ -50,47 +58,76 @@ namespace PuzzleS
|
||||
// Events to notify about step lifecycle
|
||||
public event Action<PuzzleStepSO> OnStepCompleted;
|
||||
public event Action<PuzzleStepSO> OnStepUnlocked;
|
||||
public event Action<PuzzleLevelDataSO> OnLevelDataLoaded;
|
||||
public event Action<PuzzleLevelDataSO> OnAllPuzzlesComplete;
|
||||
|
||||
private HashSet<PuzzleStepSO> _completedSteps = new HashSet<PuzzleStepSO>();
|
||||
private HashSet<PuzzleStepSO> _unlockedSteps = new HashSet<PuzzleStepSO>();
|
||||
// Registration for ObjectiveStepBehaviour
|
||||
private Dictionary<PuzzleStepSO, ObjectiveStepBehaviour> _stepBehaviours = new Dictionary<PuzzleStepSO, ObjectiveStepBehaviour>();
|
||||
// Runtime dependency graph
|
||||
private Dictionary<PuzzleStepSO, List<PuzzleStepSO>> _runtimeDependencies = new Dictionary<PuzzleStepSO, List<PuzzleStepSO>>();
|
||||
|
||||
void Awake()
|
||||
{
|
||||
_instance = this;
|
||||
// DontDestroyOnLoad(gameObject);
|
||||
SceneManager.sceneLoaded += OnSceneLoaded;
|
||||
|
||||
|
||||
// Initialize settings reference
|
||||
_interactionSettings = GameManager.GetSettingsObject<IInteractionSettings>();
|
||||
}
|
||||
|
||||
void OnEnable()
|
||||
{
|
||||
// Subscribe to scene manager events
|
||||
|
||||
}
|
||||
|
||||
void Start()
|
||||
{
|
||||
SceneManagerService.Instance.SceneLoadCompleted += OnSceneLoadCompleted;
|
||||
|
||||
// Find player transform
|
||||
_playerTransform = GameObject.FindGameObjectWithTag("Player")?.transform;
|
||||
|
||||
// Start proximity check coroutine
|
||||
StartProximityChecks();
|
||||
|
||||
// Load puzzle data for the current scene if not already loading
|
||||
if (_currentLevelData == null && !_isLoadingLevelData)
|
||||
{
|
||||
LoadPuzzleDataForCurrentScene();
|
||||
}
|
||||
}
|
||||
|
||||
void OnDestroy()
|
||||
{
|
||||
SceneManager.sceneLoaded -= OnSceneLoaded;
|
||||
StopProximityChecks();
|
||||
|
||||
// Unsubscribe from scene manager events
|
||||
if (SceneManagerService.Instance != null)
|
||||
{
|
||||
SceneManagerService.Instance.SceneLoadCompleted -= OnSceneLoadCompleted;
|
||||
}
|
||||
|
||||
// Release addressable handle if needed
|
||||
if (_levelDataLoadOperation.IsValid())
|
||||
{
|
||||
Addressables.Release(_levelDataLoadOperation);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
|
||||
/// <summary>
|
||||
/// Called when a scene is loaded
|
||||
/// </summary>
|
||||
public void OnSceneLoadCompleted(string sceneName)
|
||||
{
|
||||
SceneManager.sceneLoaded -= OnSceneLoaded;
|
||||
// Skip for non-gameplay scenes
|
||||
if (sceneName == "BootstrapScene" || string.IsNullOrEmpty(sceneName))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Logging.Debug("[MDPI] OnSceneLoaded");
|
||||
_runtimeDependencies.Clear();
|
||||
BuildRuntimeDependencies();
|
||||
UnlockInitialSteps();
|
||||
Logging.Debug($"[Puzzles] Scene loaded: {sceneName}, loading puzzle data");
|
||||
LoadPuzzleDataForCurrentScene(sceneName);
|
||||
|
||||
// Find player transform again in case it changed with scene load
|
||||
_playerTransform = GameObject.FindGameObjectWithTag("Player")?.transform;
|
||||
@@ -99,6 +136,66 @@ namespace PuzzleS
|
||||
StartProximityChecks();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Load puzzle data for the current scene
|
||||
/// </summary>
|
||||
private void LoadPuzzleDataForCurrentScene(string sceneName = null)
|
||||
{
|
||||
string currentScene = sceneName ?? SceneManagerService.Instance.CurrentGameplayScene;
|
||||
if (string.IsNullOrEmpty(currentScene))
|
||||
{
|
||||
Logging.Warning("[Puzzles] Cannot load puzzle data: Current scene name is empty");
|
||||
return;
|
||||
}
|
||||
|
||||
_isLoadingLevelData = true;
|
||||
string addressablePath = $"Puzzles/{currentScene}";
|
||||
|
||||
Logging.Debug($"[Puzzles] Loading puzzle data from addressable: {addressablePath}");
|
||||
|
||||
// Release previous handle if needed
|
||||
if (_levelDataLoadOperation.IsValid())
|
||||
{
|
||||
Addressables.Release(_levelDataLoadOperation);
|
||||
}
|
||||
|
||||
if (!AppleHillsUtils.AddressableKeyExists(addressablePath))
|
||||
{
|
||||
Logging.Warning($"[Puzzles] Puzzle key does not exist in Addressables: {addressablePath}. Returning early!");
|
||||
return;
|
||||
}
|
||||
|
||||
// Load the level data asset
|
||||
_levelDataLoadOperation = Addressables.LoadAssetAsync<PuzzleLevelDataSO>(addressablePath);
|
||||
_levelDataLoadOperation.Completed += handle =>
|
||||
{
|
||||
_isLoadingLevelData = false;
|
||||
|
||||
if (handle.Status == AsyncOperationStatus.Succeeded)
|
||||
{
|
||||
_currentLevelData = handle.Result;
|
||||
Logging.Debug($"[Puzzles] Loaded level data: {_currentLevelData.levelId} with {_currentLevelData.allSteps.Count} steps");
|
||||
|
||||
// Reset state
|
||||
_completedSteps.Clear();
|
||||
_unlockedSteps.Clear();
|
||||
|
||||
// Unlock initial steps
|
||||
UnlockInitialSteps();
|
||||
|
||||
// Update existing ObjectiveStepBehaviours with the current state
|
||||
UpdateRegisteredStepStates();
|
||||
|
||||
// Notify listeners
|
||||
OnLevelDataLoaded?.Invoke(_currentLevelData);
|
||||
}
|
||||
else
|
||||
{
|
||||
Logging.Warning($"[Puzzles] Failed to load puzzle data for {currentScene}: {handle.OperationException?.Message}");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Start the proximity check coroutine.
|
||||
/// </summary>
|
||||
@@ -138,7 +235,7 @@ namespace PuzzleS
|
||||
foreach (var kvp in _stepBehaviours)
|
||||
{
|
||||
if (kvp.Value == null) continue;
|
||||
if (IsPuzzleStepCompleted(kvp.Value.stepData.stepId)) continue;
|
||||
if (IsPuzzleStepCompleted(kvp.Key.stepId)) continue;
|
||||
|
||||
float distance = Vector3.Distance(_playerTransform.position, kvp.Value.transform.position);
|
||||
|
||||
@@ -164,18 +261,48 @@ namespace PuzzleS
|
||||
public void RegisterStepBehaviour(ObjectiveStepBehaviour behaviour)
|
||||
{
|
||||
if (behaviour?.stepData == null) return;
|
||||
|
||||
if (!_stepBehaviours.ContainsKey(behaviour.stepData))
|
||||
{
|
||||
_stepBehaviours.Add(behaviour.stepData, behaviour);
|
||||
_runtimeDependencies.Clear();
|
||||
foreach (var step in _stepBehaviours.Values)
|
||||
{
|
||||
step.LockStep();
|
||||
}
|
||||
_unlockedSteps.Clear();
|
||||
BuildRuntimeDependencies();
|
||||
UnlockInitialSteps();
|
||||
Logging.Debug($"[Puzzles] Registered step: {behaviour.stepData.stepId} on {behaviour.gameObject.name}");
|
||||
|
||||
// Immediately set the correct state based on current puzzle state
|
||||
UpdateStepState(behaviour);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates a step's state based on the current puzzle state.
|
||||
/// </summary>
|
||||
private void UpdateStepState(ObjectiveStepBehaviour behaviour)
|
||||
{
|
||||
if (behaviour?.stepData == null) return;
|
||||
|
||||
// If step is already completed, ignore
|
||||
if (_completedSteps.Contains(behaviour.stepData))
|
||||
return;
|
||||
|
||||
// If step is already unlocked, update the behaviour
|
||||
if (_unlockedSteps.Contains(behaviour.stepData))
|
||||
{
|
||||
behaviour.UnlockStep();
|
||||
}
|
||||
else
|
||||
{
|
||||
// Make sure it's locked
|
||||
behaviour.LockStep();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the states of all registered step behaviours based on current puzzle state.
|
||||
/// </summary>
|
||||
private void UpdateRegisteredStepStates()
|
||||
{
|
||||
foreach (var kvp in _stepBehaviours)
|
||||
{
|
||||
UpdateStepState(kvp.Value);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,52 +318,19 @@ namespace PuzzleS
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the runtime dependency graph for all registered steps.
|
||||
/// </summary>
|
||||
private void BuildRuntimeDependencies()
|
||||
{
|
||||
_runtimeDependencies = PuzzleGraphUtility.BuildDependencyGraph(_stepBehaviours.Keys);
|
||||
foreach (var step in _runtimeDependencies.Keys)
|
||||
{
|
||||
foreach (var dep in _runtimeDependencies[step])
|
||||
{
|
||||
Logging.Debug($"[Puzzles] Step {step.stepId} depends on {dep.stepId}");
|
||||
}
|
||||
}
|
||||
Logging.Debug($"[Puzzles] Runtime dependencies built. Total steps: {_stepBehaviours.Count}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unlocks all initial steps (those with no dependencies) and any steps whose dependencies are already met.
|
||||
/// Unlocks all initial steps (those with no dependencies)
|
||||
/// </summary>
|
||||
private void UnlockInitialSteps()
|
||||
{
|
||||
// First, unlock all steps with no dependencies (initial steps)
|
||||
var initialSteps = PuzzleGraphUtility.FindInitialSteps(_runtimeDependencies);
|
||||
foreach (var step in initialSteps)
|
||||
if (_currentLevelData == null) return;
|
||||
|
||||
// Unlock initial steps
|
||||
foreach (var step in _currentLevelData.initialSteps)
|
||||
{
|
||||
Logging.Debug($"[Puzzles] Initial step unlocked: {step.stepId}");
|
||||
UnlockStep(step);
|
||||
}
|
||||
|
||||
// Keep trying to unlock steps as long as we're making progress
|
||||
bool madeProgress;
|
||||
do
|
||||
{
|
||||
madeProgress = false;
|
||||
|
||||
// Check all steps that haven't been unlocked yet
|
||||
foreach (var step in _runtimeDependencies.Keys.Where(s => !_unlockedSteps.Contains(s)))
|
||||
{
|
||||
// Check if all dependencies have been completed
|
||||
if (AreRuntimeDependenciesMet(step))
|
||||
{
|
||||
Logging.Debug($"[Puzzles] Chain step unlocked: {step.stepId}");
|
||||
UnlockStep(step);
|
||||
madeProgress = true;
|
||||
}
|
||||
}
|
||||
} while (madeProgress);
|
||||
Logging.Debug($"[Puzzles] Unlocked {_unlockedSteps.Count} initial steps");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -246,24 +340,29 @@ namespace PuzzleS
|
||||
public void MarkPuzzleStepCompleted(PuzzleStepSO step)
|
||||
{
|
||||
if (_completedSteps.Contains(step)) return;
|
||||
if (_currentLevelData == null) return;
|
||||
|
||||
_completedSteps.Add(step);
|
||||
Logging.Debug($"[Puzzles] Step completed: {step.stepId}");
|
||||
|
||||
// Broadcast completion
|
||||
OnStepCompleted?.Invoke(step);
|
||||
|
||||
foreach (var unlock in step.unlocks)
|
||||
// Unlock steps that are unlocked by this step
|
||||
foreach (var unlockStep in _currentLevelData.GetUnlockedSteps(step))
|
||||
{
|
||||
if (AreRuntimeDependenciesMet(unlock))
|
||||
if (AreStepDependenciesMet(unlockStep))
|
||||
{
|
||||
Logging.Debug($"[Puzzles] Unlocking step {unlock.stepId} after completing {step.stepId}");
|
||||
UnlockStep(unlock);
|
||||
Logging.Debug($"[Puzzles] Unlocking step {unlockStep.stepId} after completing {step.stepId}");
|
||||
UnlockStep(unlockStep);
|
||||
}
|
||||
else
|
||||
{
|
||||
Logging.Debug($"[Puzzles] Step {unlock.stepId} not unlocked yet, waiting for other dependencies");
|
||||
Logging.Debug($"[Puzzles] Step {unlockStep.stepId} not unlocked yet, waiting for other dependencies");
|
||||
}
|
||||
}
|
||||
|
||||
// Check if all puzzle steps are now complete
|
||||
CheckPuzzleCompletion();
|
||||
}
|
||||
|
||||
@@ -272,13 +371,33 @@ namespace PuzzleS
|
||||
/// </summary>
|
||||
/// <param name="step">The step to check.</param>
|
||||
/// <returns>True if all dependencies are met, false otherwise.</returns>
|
||||
private bool AreRuntimeDependenciesMet(PuzzleStepSO step)
|
||||
private bool AreStepDependenciesMet(PuzzleStepSO step)
|
||||
{
|
||||
if (!_runtimeDependencies.ContainsKey(step) || _runtimeDependencies[step].Count == 0) return true;
|
||||
foreach (var dep in _runtimeDependencies[step])
|
||||
if (_currentLevelData == null || step == null) return false;
|
||||
|
||||
// If it's an initial step, it has no dependencies
|
||||
if (_currentLevelData.IsInitialStep(step)) return true;
|
||||
|
||||
// Check if dependencies are met using pre-processed data
|
||||
if (_currentLevelData.stepDependencies.TryGetValue(step.stepId, out string[] dependencies))
|
||||
{
|
||||
if (!_completedSteps.Contains(dep)) return false;
|
||||
foreach (var depId in dependencies)
|
||||
{
|
||||
// Find the dependency step
|
||||
bool dependencyMet = false;
|
||||
foreach (var completedStep in _completedSteps)
|
||||
{
|
||||
if (completedStep.stepId == depId)
|
||||
{
|
||||
dependencyMet = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!dependencyMet) return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -290,6 +409,7 @@ namespace PuzzleS
|
||||
{
|
||||
if (_unlockedSteps.Contains(step)) return;
|
||||
_unlockedSteps.Add(step);
|
||||
|
||||
if (_stepBehaviours.TryGetValue(step, out var behaviour))
|
||||
{
|
||||
behaviour.UnlockStep();
|
||||
@@ -301,14 +421,18 @@ namespace PuzzleS
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if the puzzle is complete (all steps finished).
|
||||
/// Checks if the puzzle is complete (all steps in level finished).
|
||||
/// </summary>
|
||||
private void CheckPuzzleCompletion()
|
||||
{
|
||||
if (_completedSteps.Count == _stepBehaviours.Count)
|
||||
if (_currentLevelData == null) return;
|
||||
|
||||
if (_currentLevelData.IsLevelComplete(_completedSteps))
|
||||
{
|
||||
Logging.Debug("[Puzzles] Puzzle complete! All steps finished.");
|
||||
// TODO: Fire puzzle complete event or trigger outcome logic
|
||||
Logging.Debug("[Puzzles] All puzzles complete! Level finished.");
|
||||
|
||||
// Fire level complete event
|
||||
OnAllPuzzlesComplete?.Invoke(_currentLevelData);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -317,9 +441,6 @@ namespace PuzzleS
|
||||
/// </summary>
|
||||
public bool IsStepUnlocked(PuzzleStepSO step)
|
||||
{
|
||||
// _runtimeDependencies.Clear();
|
||||
// BuildRuntimeDependencies();
|
||||
// UnlockInitialSteps();
|
||||
return _unlockedSteps.Contains(step);
|
||||
}
|
||||
|
||||
@@ -332,6 +453,14 @@ namespace PuzzleS
|
||||
{
|
||||
return _completedSteps.Any(step => step.stepId == stepId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Get the current level puzzle data
|
||||
/// </summary>
|
||||
public PuzzleLevelDataSO GetCurrentLevelData()
|
||||
{
|
||||
return _currentLevelData;
|
||||
}
|
||||
|
||||
void OnApplicationQuit()
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user