AdventurersGuild.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. /// <summary>
  5. /// Manages the Adventurer's Guild - quest board, quest generation, and guild services
  6. /// </summary>
  7. public class AdventurersGuild : MonoBehaviour
  8. {
  9. [Header("Guild Configuration")]
  10. [Tooltip("Maximum number of quests on the board")]
  11. public int maxQuestBoardSize = 8;
  12. [Tooltip("How often new quests are added (in game hours)")]
  13. public float questRefreshRate = 24f;
  14. [Header("Available Quests")]
  15. [SerializeField] private List<Quest> availableQuests = new List<Quest>();
  16. [SerializeField] private List<Quest> questBoard = new List<Quest>();
  17. [Header("Guild Services")]
  18. [Tooltip("Can abandon quests here")]
  19. public bool allowQuestAbandonment = true;
  20. [Tooltip("Can view completed quest history")]
  21. public bool showQuestHistory = true;
  22. [Header("Debug")]
  23. public bool enableDebugLogs = false;
  24. private float timeSinceLastRefresh = 0f;
  25. private void Start()
  26. {
  27. // Wait a frame to ensure QuestManager is initialized
  28. StartCoroutine(InitializeGuild());
  29. }
  30. private System.Collections.IEnumerator InitializeGuild()
  31. {
  32. yield return null; // Wait one frame
  33. // Ensure QuestManager exists
  34. if (QuestManager.Instance == null)
  35. {
  36. var questManagerObject = new GameObject("QuestManager");
  37. questManagerObject.AddComponent<QuestManager>();
  38. if (enableDebugLogs)
  39. Debug.Log("✅ AdventurersGuild created QuestManager instance");
  40. }
  41. LoadAvailableQuests();
  42. RefreshQuestBoard();
  43. if (enableDebugLogs)
  44. Debug.Log($"🏛️ AdventurersGuild initialized with {availableQuests.Count} available quests");
  45. }
  46. private void Update()
  47. {
  48. // Auto-refresh quest board periodically
  49. if (QuestManager.Instance != null)
  50. {
  51. timeSinceLastRefresh += Time.deltaTime * QuestManager.Instance.gameTimeSpeed;
  52. if (timeSinceLastRefresh >= questRefreshRate)
  53. {
  54. RefreshQuestBoard();
  55. timeSinceLastRefresh = 0f;
  56. }
  57. }
  58. }
  59. /// <summary>
  60. /// Load all available quests from Resources folder
  61. /// </summary>
  62. private void LoadAvailableQuests()
  63. {
  64. availableQuests.Clear();
  65. LogDebug("🔍 Starting quest loading process...");
  66. // First, try to load quests from specific subfolders
  67. var combatQuests = Resources.LoadAll<Quest>("Quests/Combat");
  68. var rescueQuests = Resources.LoadAll<Quest>("Quests/Rescue");
  69. var retrievalQuests = Resources.LoadAll<Quest>("Quests/Retrieval");
  70. var explorationQuests = Resources.LoadAll<Quest>("Quests/Exploration");
  71. LogDebug($"📁 Found quests in subfolders: Combat={combatQuests.Length}, Rescue={rescueQuests.Length}, Retrieval={retrievalQuests.Length}, Exploration={explorationQuests.Length}");
  72. availableQuests.AddRange(combatQuests);
  73. availableQuests.AddRange(rescueQuests);
  74. availableQuests.AddRange(retrievalQuests);
  75. availableQuests.AddRange(explorationQuests);
  76. // Also load any quests directly in the Quests folder
  77. var allQuests = Resources.LoadAll<Quest>("Quests");
  78. LogDebug($"📁 Found {allQuests.Length} quests in main Quests folder");
  79. foreach (var quest in allQuests)
  80. {
  81. if (quest != null)
  82. {
  83. LogDebug($" - Found quest: {quest.name} ({quest.questTitle})");
  84. if (!availableQuests.Contains(quest))
  85. {
  86. availableQuests.Add(quest);
  87. LogDebug($" ✅ Added to available quests");
  88. }
  89. else
  90. {
  91. LogDebug($" ⚠️ Already in list, skipping");
  92. }
  93. }
  94. else
  95. {
  96. LogDebug($" - ❌ Found NULL quest in Resources/Quests");
  97. }
  98. }
  99. // Finally, load any quests from the root Resources folder
  100. var rootQuests = Resources.LoadAll<Quest>("");
  101. foreach (var quest in rootQuests)
  102. {
  103. if (!availableQuests.Contains(quest))
  104. {
  105. availableQuests.Add(quest);
  106. }
  107. }
  108. LogDebug($"📚 Loaded {availableQuests.Count} available quests");
  109. // If no quests found, create some default ones
  110. if (availableQuests.Count == 0)
  111. {
  112. LogDebug("⚠️ No quests found in Resources. Creating default quests...");
  113. CreateDefaultQuests();
  114. }
  115. if (enableDebugLogs && availableQuests.Count > 0)
  116. {
  117. Debug.Log("📋 Available quests:");
  118. foreach (var quest in availableQuests)
  119. {
  120. Debug.Log($" - {quest.questTitle} ({quest.name})");
  121. }
  122. }
  123. }
  124. /// <summary>
  125. /// Create default quests if none are found in Resources
  126. /// </summary>
  127. private void CreateDefaultQuests()
  128. {
  129. LogDebug("Creating default starter quests...");
  130. var starterQuest = ScriptableObject.CreateInstance<Quest>();
  131. starterQuest.questTitle = "Goblin Trouble";
  132. starterQuest.questDescription = "Goblins have been spotted near the village outskirts. Deal with them before they cause real trouble.";
  133. starterQuest.questType = QuestType.Combat;
  134. starterQuest.difficulty = QuestDifficulty.Easy;
  135. starterQuest.timeLimitDays = 7;
  136. starterQuest.targetAreaName = "Village Outskirts";
  137. starterQuest.targetMapPosition = new Vector2Int(45, 55);
  138. starterQuest.goldReward = 50;
  139. starterQuest.renownReward = 5;
  140. starterQuest.minimumRenown = 0; // Available to all players
  141. starterQuest.goals.Add(new QuestGoal
  142. {
  143. description = "Defeat 3 Goblins",
  144. goalType = QuestGoalType.KillEnemies,
  145. targetName = "Goblin",
  146. targetCount = 3
  147. });
  148. availableQuests.Add(starterQuest);
  149. var deliveryQuest = ScriptableObject.CreateInstance<Quest>();
  150. deliveryQuest.questTitle = "Message Delivery";
  151. deliveryQuest.questDescription = "The village elder needs an important message delivered to the neighboring settlement.";
  152. deliveryQuest.questType = QuestType.Delivery;
  153. deliveryQuest.difficulty = QuestDifficulty.Easy;
  154. deliveryQuest.timeLimitDays = 5;
  155. deliveryQuest.targetAreaName = "Nearby Settlement";
  156. deliveryQuest.targetMapPosition = new Vector2Int(60, 40);
  157. deliveryQuest.goldReward = 40;
  158. deliveryQuest.renownReward = 3;
  159. deliveryQuest.minimumRenown = 0;
  160. deliveryQuest.goals.Add(new QuestGoal
  161. {
  162. description = "Deliver message to Settlement Leader",
  163. goalType = QuestGoalType.ReachLocation,
  164. targetName = "Settlement",
  165. targetCount = 1
  166. });
  167. availableQuests.Add(deliveryQuest);
  168. LogDebug($"✅ Created {availableQuests.Count} default quests");
  169. }
  170. /// <summary>
  171. /// Refresh the quest board with new available quests
  172. /// </summary>
  173. public void RefreshQuestBoard()
  174. {
  175. questBoard.Clear();
  176. if (availableQuests.Count == 0)
  177. {
  178. LogDebug("⚠️ No available quests to populate quest board");
  179. return;
  180. }
  181. // Filter quests based on current renown and prerequisites
  182. var eligibleQuests = availableQuests.Where(q => IsQuestEligible(q)).ToList();
  183. // Randomly select quests for the board
  184. var questsToAdd = Mathf.Min(maxQuestBoardSize, eligibleQuests.Count);
  185. var selectedQuests = eligibleQuests.OrderBy(x => Random.value).Take(questsToAdd);
  186. questBoard.AddRange(selectedQuests);
  187. LogDebug($"🗂️ Quest board refreshed: {questBoard.Count} quests available");
  188. }
  189. /// <summary>
  190. /// Check if a quest is eligible for the current party
  191. /// </summary>
  192. private bool IsQuestEligible(Quest quest)
  193. {
  194. if (quest == null) return false;
  195. var questManager = QuestManager.Instance;
  196. if (questManager == null) return false;
  197. // Check renown requirement
  198. if (questManager.GetRenown() < quest.minimumRenown)
  199. return false;
  200. // Check if already have this quest active
  201. var activeQuests = questManager.GetActiveQuests();
  202. if (activeQuests.Any(aq => aq.questData == quest))
  203. return false;
  204. // Check prerequisites (simplified - just check if we've completed them)
  205. // In a full implementation, you'd check the QuestManager's completed quests
  206. return true;
  207. }
  208. /// <summary>
  209. /// Accept a quest from the guild board
  210. /// </summary>
  211. public bool AcceptQuest(Quest quest)
  212. {
  213. if (quest == null || !questBoard.Contains(quest))
  214. {
  215. LogDebug("❌ Cannot accept quest: not available on board");
  216. return false;
  217. }
  218. var questManager = QuestManager.Instance;
  219. if (questManager == null)
  220. {
  221. LogDebug("❌ QuestManager not found");
  222. return false;
  223. }
  224. if (!questManager.CanAcceptMoreQuests())
  225. {
  226. LogDebug("❌ Cannot accept more quests");
  227. return false;
  228. }
  229. bool accepted = questManager.AcceptQuest(quest);
  230. if (accepted)
  231. {
  232. // Remove from board (could be optional - some quests might be repeatable)
  233. questBoard.Remove(quest);
  234. LogDebug($"✅ Accepted quest from guild: {quest.questTitle}");
  235. }
  236. return accepted;
  237. }
  238. /// <summary>
  239. /// Get all quests currently on the board
  240. /// </summary>
  241. public List<Quest> GetQuestBoard() => new List<Quest>(questBoard);
  242. /// <summary>
  243. /// Generate a random quest based on current area/difficulty
  244. /// </summary>
  245. public Quest GenerateRandomQuest(Vector2Int nearPosition, QuestDifficulty targetDifficulty = QuestDifficulty.Normal)
  246. {
  247. // This would be used for dynamic quest generation
  248. // For now, just return a random quest from available ones
  249. var eligibleQuests = availableQuests.Where(q =>
  250. q.difficulty == targetDifficulty && IsQuestEligible(q)).ToList();
  251. if (eligibleQuests.Count == 0) return null;
  252. var randomQuest = eligibleQuests[Random.Range(0, eligibleQuests.Count)];
  253. // Modify the quest position to be near the requested position
  254. var questCopy = Object.Instantiate(randomQuest);
  255. questCopy.targetMapPosition = nearPosition + new Vector2Int(
  256. Random.Range(-10, 11), Random.Range(-10, 11));
  257. return questCopy;
  258. }
  259. /// <summary>
  260. /// Get quest recommendations based on party strength/renown
  261. /// </summary>
  262. public List<Quest> GetRecommendedQuests(int count = 3)
  263. {
  264. var questManager = QuestManager.Instance;
  265. if (questManager == null) return new List<Quest>();
  266. int renown = questManager.GetRenown();
  267. // Recommend quests slightly above and below current renown level
  268. var recommended = questBoard.Where(q =>
  269. q.minimumRenown <= renown + 10 && q.minimumRenown >= renown - 5)
  270. .OrderBy(q => Mathf.Abs(q.minimumRenown - renown))
  271. .Take(count)
  272. .ToList();
  273. return recommended;
  274. }
  275. /// <summary>
  276. /// Calculate travel time to quest location from current position
  277. /// </summary>
  278. public float CalculateTravelTimeToQuest(Quest quest, Vector2Int currentPosition)
  279. {
  280. if (quest == null) return 0f;
  281. return quest.CalculateTravelTime(currentPosition);
  282. }
  283. private void LogDebug(string message)
  284. {
  285. if (enableDebugLogs)
  286. {
  287. Debug.Log($"[AdventurersGuild] {message}");
  288. }
  289. }
  290. #region Context Menu Debug Methods
  291. [ContextMenu("Refresh Quest Board")]
  292. private void DebugRefreshQuestBoard()
  293. {
  294. RefreshQuestBoard();
  295. }
  296. [ContextMenu("List Available Quests")]
  297. private void DebugListAvailableQuests()
  298. {
  299. LogDebug($"Available Quests ({availableQuests.Count}):");
  300. foreach (var quest in availableQuests)
  301. {
  302. LogDebug($" - {quest.questTitle} (Difficulty: {quest.difficulty}, Renown: {quest.minimumRenown})");
  303. }
  304. }
  305. [ContextMenu("List Quest Board")]
  306. private void DebugListQuestBoard()
  307. {
  308. LogDebug($"Quest Board ({questBoard.Count}):");
  309. foreach (var quest in questBoard)
  310. {
  311. LogDebug($" - {quest.questTitle} (Reward: {quest.goldReward}g, Time: {quest.timeLimitDays}d)");
  312. }
  313. }
  314. [ContextMenu("Force Load Quests")]
  315. private void DebugForceLoadQuests()
  316. {
  317. LoadAvailableQuests();
  318. LogDebug($"Forced quest loading complete. Found {availableQuests.Count} quests.");
  319. }
  320. [ContextMenu("Check Quest Eligibility")]
  321. private void DebugCheckQuestEligibility()
  322. {
  323. LogDebug("Checking quest eligibility...");
  324. LogDebug($"Current Renown: {QuestManager.Instance?.GetRenown() ?? -1}");
  325. foreach (var quest in availableQuests)
  326. {
  327. bool eligible = IsQuestEligible(quest);
  328. LogDebug($" - {quest.questTitle}: {(eligible ? "✅ ELIGIBLE" : "❌ NOT ELIGIBLE")} (Min Renown: {quest.minimumRenown})");
  329. }
  330. }
  331. [ContextMenu("Create Simple Test Quest")]
  332. private void DebugCreateSimpleQuest()
  333. {
  334. var simpleQuest = ScriptableObject.CreateInstance<Quest>();
  335. simpleQuest.questTitle = "Simple Test Quest";
  336. simpleQuest.questDescription = "A basic quest for testing the quest board display.";
  337. simpleQuest.questType = QuestType.Combat;
  338. simpleQuest.difficulty = QuestDifficulty.Easy;
  339. simpleQuest.timeLimitDays = 7;
  340. simpleQuest.targetAreaName = "Nearby Forest";
  341. simpleQuest.targetMapPosition = new Vector2Int(50, 50);
  342. simpleQuest.goldReward = 50;
  343. simpleQuest.renownReward = 5;
  344. simpleQuest.minimumRenown = 0; // No requirements
  345. simpleQuest.goals.Add(new QuestGoal
  346. {
  347. description = "Defeat 3 Goblins",
  348. goalType = QuestGoalType.KillEnemies,
  349. targetName = "Goblin",
  350. targetCount = 3
  351. });
  352. // Add directly to available quests and quest board
  353. availableQuests.Add(simpleQuest);
  354. questBoard.Add(simpleQuest);
  355. LogDebug($"✅ Created and added simple test quest: {simpleQuest.questTitle}");
  356. LogDebug($"Quest Board now has {questBoard.Count} quests");
  357. }
  358. [ContextMenu("Force Reload Available Quests")]
  359. private void DebugReloadQuests()
  360. {
  361. LogDebug("🔄 Manually reloading available quests...");
  362. LoadAvailableQuests();
  363. RefreshQuestBoard();
  364. }
  365. [ContextMenu("List Resources/Quests Contents")]
  366. private void DebugListQuestResources()
  367. {
  368. LogDebug("🔍 Checking Resources/Quests folder contents...");
  369. var allQuests = Resources.LoadAll<Quest>("Quests");
  370. LogDebug($"Resources.LoadAll<Quest>(\"Quests\") returned {allQuests.Length} items");
  371. for (int i = 0; i < allQuests.Length; i++)
  372. {
  373. var quest = allQuests[i];
  374. if (quest != null)
  375. {
  376. LogDebug($" {i}: {quest.name} - Title: '{quest.questTitle}' - Type: {quest.questType}");
  377. }
  378. else
  379. {
  380. LogDebug($" {i}: NULL quest object");
  381. }
  382. }
  383. // Also check with UnityEngine.Object
  384. var allObjects = Resources.LoadAll("Quests");
  385. LogDebug($"Resources.LoadAll(\"Quests\") returned {allObjects.Length} objects of any type");
  386. for (int i = 0; i < allObjects.Length; i++)
  387. {
  388. var obj = allObjects[i];
  389. if (obj != null)
  390. {
  391. LogDebug($" {i}: {obj.name} - Type: {obj.GetType().Name}");
  392. }
  393. else
  394. {
  395. LogDebug($" {i}: NULL object");
  396. }
  397. }
  398. }
  399. [ContextMenu("Check Quest Board Eligibility")]
  400. private void DebugCheckQuestBoardEligibility()
  401. {
  402. LogDebug("🔍 Checking quest eligibility for quest board...");
  403. LogDebug($"Current Renown: {QuestManager.Instance?.GetRenown() ?? -1}");
  404. LogDebug($"Available Quests: {availableQuests.Count}");
  405. foreach (var quest in availableQuests)
  406. {
  407. if (quest != null)
  408. {
  409. bool eligible = IsQuestEligible(quest);
  410. LogDebug($" - {quest.questTitle}:");
  411. LogDebug($" Min Renown Required: {quest.minimumRenown}");
  412. LogDebug($" Quest Type: {quest.questType}");
  413. LogDebug($" Difficulty: {quest.difficulty}");
  414. LogDebug($" Eligible: {(eligible ? "✅ YES" : "❌ NO")}");
  415. if (!eligible && QuestManager.Instance != null)
  416. {
  417. // Check specific reasons
  418. if (QuestManager.Instance.GetRenown() < quest.minimumRenown)
  419. {
  420. LogDebug($" ❌ Reason: Not enough renown ({QuestManager.Instance.GetRenown()} < {quest.minimumRenown})");
  421. }
  422. // Check if quest is already active
  423. var activeQuests = QuestManager.Instance.GetActiveQuests();
  424. bool alreadyActive = activeQuests.Any(aq => aq.questData.name == quest.name);
  425. if (alreadyActive)
  426. {
  427. LogDebug($" ❌ Reason: Quest already active");
  428. }
  429. }
  430. }
  431. }
  432. }
  433. #endregion
  434. }