ActiveQuest.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. using System;
  4. /// <summary>
  5. /// Runtime instance of a quest that tracks progress and time
  6. /// </summary>
  7. [System.Serializable]
  8. public class ActiveQuest
  9. {
  10. [Header("Quest Reference")]
  11. public Quest questData;
  12. public string questId; // Unique identifier
  13. [Header("Progress Tracking")]
  14. public List<QuestGoal> activeGoals;
  15. public QuestStatus status = QuestStatus.Active;
  16. [Header("Time Tracking")]
  17. public float timeStarted; // Game time when quest was accepted
  18. public float timeRemaining; // Hours remaining
  19. [Header("Completion Data")]
  20. public float timeCompleted = -1f;
  21. public Vector2Int completionPosition;
  22. public ActiveQuest(Quest quest)
  23. {
  24. questData = quest;
  25. questId = System.Guid.NewGuid().ToString();
  26. // Copy goals from quest data
  27. activeGoals = new List<QuestGoal>();
  28. foreach (var goal in quest.goals)
  29. {
  30. activeGoals.Add(new QuestGoal
  31. {
  32. description = goal.description,
  33. goalType = goal.goalType,
  34. targetName = goal.targetName,
  35. targetCount = goal.targetCount,
  36. currentProgress = 0,
  37. isHidden = goal.isHidden,
  38. isOptional = goal.isOptional
  39. });
  40. }
  41. timeStarted = Time.time;
  42. timeRemaining = quest.GetTotalTimeLimitHours();
  43. status = QuestStatus.Active;
  44. }
  45. /// <summary>
  46. /// Update quest progress (called every frame or game tick)
  47. /// </summary>
  48. public void UpdateQuest(float deltaTimeHours)
  49. {
  50. if (status != QuestStatus.Active) return;
  51. timeRemaining -= deltaTimeHours;
  52. // Check if time has run out
  53. if (timeRemaining <= 0f && questData.canFail)
  54. {
  55. status = QuestStatus.Failed;
  56. OnQuestFailed();
  57. return;
  58. }
  59. // Check if all required goals are completed
  60. if (AreAllRequiredGoalsCompleted())
  61. {
  62. status = QuestStatus.Completed;
  63. timeCompleted = Time.time;
  64. OnQuestCompleted();
  65. }
  66. }
  67. /// <summary>
  68. /// Progress a specific goal
  69. /// </summary>
  70. public bool ProgressGoal(QuestGoalType goalType, string targetName = "", int amount = 1)
  71. {
  72. bool progressMade = false;
  73. foreach (var goal in activeGoals)
  74. {
  75. if (goal.goalType == goalType &&
  76. (string.IsNullOrEmpty(targetName) || goal.targetName.Equals(targetName, StringComparison.OrdinalIgnoreCase)))
  77. {
  78. int oldProgress = goal.currentProgress;
  79. goal.currentProgress = Mathf.Min(goal.currentProgress + amount, goal.targetCount);
  80. if (goal.currentProgress > oldProgress)
  81. {
  82. progressMade = true;
  83. Debug.Log($"🎯 Quest Progress: {goal.description} ({goal.currentProgress}/{goal.targetCount})");
  84. }
  85. }
  86. }
  87. return progressMade;
  88. }
  89. /// <summary>
  90. /// Check if quest can be completed at current position
  91. /// </summary>
  92. public bool CanCompleteAtPosition(Vector2Int position)
  93. {
  94. return questData.CanCompleteAtPosition(position) && AreAllRequiredGoalsCompleted();
  95. }
  96. /// <summary>
  97. /// Attempt to complete the quest at given position
  98. /// </summary>
  99. public bool TryCompleteQuest(Vector2Int position)
  100. {
  101. if (!CanCompleteAtPosition(position)) return false;
  102. status = QuestStatus.Completed;
  103. timeCompleted = Time.time;
  104. completionPosition = position;
  105. OnQuestCompleted();
  106. return true;
  107. }
  108. private bool AreAllRequiredGoalsCompleted()
  109. {
  110. foreach (var goal in activeGoals)
  111. {
  112. if (!goal.isOptional && !goal.IsCompleted)
  113. return false;
  114. }
  115. return true;
  116. }
  117. private void OnQuestCompleted()
  118. {
  119. Debug.Log($"✅ Quest Completed: {questData.questTitle}");
  120. QuestManager.Instance?.CompleteQuest(this);
  121. }
  122. private void OnQuestFailed()
  123. {
  124. Debug.Log($"❌ Quest Failed: {questData.questTitle} (Time's up!)");
  125. QuestManager.Instance?.FailQuest(this);
  126. }
  127. /// <summary>
  128. /// Get time remaining as formatted string
  129. /// </summary>
  130. public string GetTimeRemainingString()
  131. {
  132. if (timeRemaining <= 0) return "EXPIRED";
  133. int days = Mathf.FloorToInt(timeRemaining / 24f);
  134. int hours = Mathf.FloorToInt(timeRemaining % 24f);
  135. int minutes = Mathf.FloorToInt((timeRemaining % 1f) * 60f);
  136. if (days > 0)
  137. return $"{days}d {hours}h {minutes}m";
  138. else if (hours > 0)
  139. return $"{hours}h {minutes}m";
  140. else
  141. return $"{minutes}m";
  142. }
  143. /// <summary>
  144. /// Get progress percentage (0-1)
  145. /// </summary>
  146. public float GetOverallProgress()
  147. {
  148. if (activeGoals.Count == 0) return 1f;
  149. float totalProgress = 0f;
  150. int requiredGoals = 0;
  151. foreach (var goal in activeGoals)
  152. {
  153. if (!goal.isOptional)
  154. {
  155. totalProgress += goal.ProgressPercent;
  156. requiredGoals++;
  157. }
  158. }
  159. return requiredGoals > 0 ? totalProgress / requiredGoals : 1f;
  160. }
  161. /// <summary>
  162. /// Get urgency level based on time remaining
  163. /// </summary>
  164. public QuestUrgency GetUrgency()
  165. {
  166. float totalTime = questData.GetTotalTimeLimitHours();
  167. float timePercent = timeRemaining / totalTime;
  168. if (timePercent > 0.75f) return QuestUrgency.Low;
  169. if (timePercent > 0.5f) return QuestUrgency.Medium;
  170. if (timePercent > 0.25f) return QuestUrgency.High;
  171. return QuestUrgency.Critical;
  172. }
  173. /// <summary>
  174. /// Get time remaining in hours (used by UI)
  175. /// </summary>
  176. public float GetTimeRemaining()
  177. {
  178. return timeRemaining;
  179. }
  180. /// <summary>
  181. /// Get urgency level (compatibility method)
  182. /// </summary>
  183. public QuestUrgency GetUrgencyLevel()
  184. {
  185. return GetUrgency();
  186. }
  187. /// <summary>
  188. /// Get number of completed objectives
  189. /// </summary>
  190. public int GetCompletedObjectivesCount()
  191. {
  192. int completed = 0;
  193. foreach (var goal in activeGoals)
  194. {
  195. if (goal.currentProgress >= goal.targetCount)
  196. completed++;
  197. }
  198. return completed;
  199. }
  200. /// <summary>
  201. /// Get progress of a specific objective
  202. /// </summary>
  203. public int GetObjectiveProgress(int objectiveIndex)
  204. {
  205. if (objectiveIndex >= 0 && objectiveIndex < activeGoals.Count)
  206. return activeGoals[objectiveIndex].currentProgress;
  207. return 0;
  208. }
  209. /// <summary>
  210. /// Convert this active quest to save data
  211. /// </summary>
  212. public ActiveQuestSaveData ToSaveData()
  213. {
  214. var saveData = new ActiveQuestSaveData
  215. {
  216. questId = this.questId,
  217. questAssetName = questData?.name ?? "",
  218. questTitle = questData?.questTitle ?? "Unknown Quest",
  219. status = this.status,
  220. elapsedTimeHours = (questData?.GetTotalTimeLimitHours() ?? 0) - timeRemaining
  221. };
  222. // Save goal progress
  223. foreach (var goal in activeGoals)
  224. {
  225. saveData.goals.Add(new QuestGoalSaveData
  226. {
  227. description = goal.description,
  228. goalType = goal.goalType,
  229. targetName = goal.targetName,
  230. targetCount = goal.targetCount,
  231. currentProgress = goal.currentProgress,
  232. isHidden = goal.isHidden,
  233. isOptional = goal.isOptional
  234. });
  235. }
  236. return saveData;
  237. }
  238. /// <summary>
  239. /// Create an ActiveQuest from save data
  240. /// </summary>
  241. public static ActiveQuest FromSaveData(ActiveQuestSaveData saveData)
  242. {
  243. // Try to find the original quest asset
  244. Quest questAsset = null;
  245. if (!string.IsNullOrEmpty(saveData.questAssetName))
  246. {
  247. questAsset = Resources.Load<Quest>($"Quests/{saveData.questAssetName}");
  248. if (questAsset == null)
  249. {
  250. questAsset = Resources.Load<Quest>(saveData.questAssetName);
  251. }
  252. }
  253. // If we can't find the asset, create a minimal one
  254. if (questAsset == null)
  255. {
  256. Debug.LogWarning($"Could not find quest asset '{saveData.questAssetName}' for saved quest '{saveData.questTitle}'. Creating placeholder.");
  257. questAsset = ScriptableObject.CreateInstance<Quest>();
  258. questAsset.questTitle = saveData.questTitle;
  259. questAsset.questDescription = "This quest was loaded from save data but the original asset is missing.";
  260. questAsset.timeLimitDays = 7; // Default
  261. }
  262. // Create the active quest
  263. var activeQuest = new ActiveQuest(questAsset);
  264. activeQuest.questId = saveData.questId;
  265. activeQuest.status = saveData.status;
  266. // Calculate time remaining from elapsed time
  267. float totalTime = questAsset.GetTotalTimeLimitHours();
  268. activeQuest.timeRemaining = Mathf.Max(0, totalTime - saveData.elapsedTimeHours);
  269. // Restore goal progress
  270. for (int i = 0; i < activeQuest.activeGoals.Count && i < saveData.goals.Count; i++)
  271. {
  272. var goal = activeQuest.activeGoals[i];
  273. var savedGoal = saveData.goals[i];
  274. goal.currentProgress = savedGoal.currentProgress;
  275. }
  276. return activeQuest;
  277. }
  278. }
  279. public enum QuestStatus
  280. {
  281. Active,
  282. Completed,
  283. Failed,
  284. Abandoned
  285. }
  286. public enum QuestUrgency
  287. {
  288. Low,
  289. Medium,
  290. High,
  291. Critical
  292. }