AutonomousAgentBrain.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5. namespace MazeGen
  6. {
  7. /// <summary>
  8. /// Drives one agent's autonomous exploration: waits out a (randomized) initial delay so
  9. /// many agents don't all decide in lockstep, then ticks a steady decision interval -
  10. /// each time it fires, picks an exit and asks the MazeAgentController to use it. Stops
  11. /// deciding once the agent reaches an exit room or the level has ended.
  12. ///
  13. /// Agents can "peek" into adjacent rooms before entering to see if there are monsters.
  14. /// Based on the perceived threat level, they may choose to retreat rather than fight.
  15. /// </summary>
  16. public class AutonomousAgentBrain : MonoBehaviour
  17. {
  18. private MazeAgentController _controller;
  19. private MazeGenerator _generator;
  20. private float _decisionInterval;
  21. private float _exploreChance;
  22. private float _retreatThreshold = 1.5f; // CR above this = retreat (configurable)
  23. private Func<bool> _isLevelEnded;
  24. private float _timer;
  25. private Dictionary<int, int> _peekCount = new Dictionary<int, int>(); // Track how many times agent peeked at a room
  26. public void Initialize(MazeAgentController controller, MazeGenerator generator, float initialDelay, float decisionInterval, float exploreChance, float retreatThreshold, Func<bool> isLevelEnded)
  27. {
  28. _controller = controller;
  29. _generator = generator;
  30. _decisionInterval = Mathf.Max(0.05f, decisionInterval);
  31. _exploreChance = Mathf.Clamp01(exploreChance);
  32. _retreatThreshold = Mathf.Max(0, retreatThreshold);
  33. _isLevelEnded = isLevelEnded;
  34. _timer = Mathf.Max(0f, initialDelay);
  35. }
  36. private void Update()
  37. {
  38. if (_controller?.Agent == null || _controller.Agent.IsFinished || _controller.Agent.IsDead) return;
  39. if (_isLevelEnded != null && _isLevelEnded()) return;
  40. _timer -= Time.deltaTime;
  41. if (_timer > 0f) return;
  42. _timer = _decisionInterval;
  43. Exit choice = ChooseExit(_controller.Agent, _controller.Agent.CurrentRoom);
  44. if (choice != null)
  45. _controller.TryUseExit(choice);
  46. }
  47. /// <summary>
  48. /// Picks the next exit to take. Strongly prefers an unused exit (fresh, unexplored
  49. /// territory); failing that, prefers a used exit into a room this agent personally
  50. /// hasn't visited yet (following where another agent has already been); only
  51. /// backtracks into a room it's already visited as a last resort. `exploreChance`
  52. /// adds some randomness so a "follow" opportunity is occasionally taken even when
  53. /// exploring is available, rather than being 100% deterministic.
  54. ///
  55. /// A few anti-stuck rules keep this from looping forever around a small ring of
  56. /// already-explored rooms (e.g. a square formed by a loop-closing connection):
  57. /// - The door leading straight back to the room the agent just came from is excluded
  58. /// from consideration unless it's the only door available at all, so agents don't
  59. /// ping-pong between two rooms.
  60. /// - When forced to backtrack, exits that "peek" into a room with its own unexplored
  61. /// option beyond it (an unused exit, or one leading somewhere this agent hasn't
  62. /// personally seen) are preferred over ones that only lead deeper into fully-picked-
  63. /// over territory - this steers the agent back out of a dead loop instead of just
  64. /// circling it.
  65. /// - Ties are broken toward whichever room this agent has personally visited the
  66. /// fewest times, so a small loop gets cycled through rather than bounced around.
  67. ///
  68. /// Also evaluates monster threats in adjacent rooms - if a room looks too dangerous,
  69. /// the agent will retreat (choose a different exit) if possible.
  70. /// </summary>
  71. private Exit ChooseExit(MazeAgent agent, Room room)
  72. {
  73. Exit reverseExit = FindReverseExit(agent, room);
  74. var explore = new List<Exit>();
  75. var follow = new List<Exit>();
  76. var backtrack = new List<Exit>();
  77. foreach (var exit in room.Exits)
  78. {
  79. if (exit == reverseExit) continue;
  80. if (!exit.IsUsed)
  81. {
  82. explore.Add(exit);
  83. continue;
  84. }
  85. bool leadsToVisited = exit.ConnectedRoomId.HasValue && agent.HasVisited(exit.ConnectedRoomId.Value);
  86. (leadsToVisited ? backtrack : follow).Add(exit);
  87. }
  88. // Filter exits by threat level - remove dangerous ones if safer options exist
  89. explore = FilterByThreat(explore, agent);
  90. follow = FilterByThreat(follow, agent);
  91. backtrack = FilterByThreat(backtrack, agent);
  92. if (explore.Count > 0 && UnityEngine.Random.value < _exploreChance)
  93. return RandomPick(explore);
  94. if (follow.Count > 0)
  95. return LeastVisitedPick(agent, follow);
  96. if (explore.Count > 0)
  97. return RandomPick(explore);
  98. if (backtrack.Count > 0)
  99. return ChooseBacktrack(agent, backtrack);
  100. // Excluding the reverse door left nothing - it's genuinely the only way out
  101. // (e.g. a single-exit dead end), so take it (even if dangerous).
  102. return reverseExit;
  103. }
  104. /// <summary>The door in `room` that leads straight back to wherever the agent's last move came from, if any.</summary>
  105. private static Exit FindReverseExit(MazeAgent agent, Room room)
  106. {
  107. int? reverseExitId = agent.LastUsedExit?.ConnectedExitId;
  108. if (!reverseExitId.HasValue) return null;
  109. return room.Exits.Find(e => e.Id == reverseExitId.Value);
  110. }
  111. private Exit ChooseBacktrack(MazeAgent agent, List<Exit> backtrack)
  112. {
  113. var promising = backtrack.Where(e => LeadsTowardUnexploredOptions(agent, e)).ToList();
  114. return LeastVisitedPick(agent, promising.Count > 0 ? promising : backtrack);
  115. }
  116. /// <summary>
  117. /// One-step lookahead: does the room beyond `exit` itself have any door (other than
  118. /// the one leading straight back here) that's still unused or leads somewhere this
  119. /// agent hasn't personally been? If so, backtracking this way still has somewhere
  120. /// useful to go; if not, it just leads deeper into already-picked-over territory.
  121. /// </summary>
  122. private bool LeadsTowardUnexploredOptions(MazeAgent agent, Exit exit)
  123. {
  124. if (!exit.ConnectedRoomId.HasValue) return false;
  125. Room target = _generator.Graph.Get(exit.ConnectedRoomId.Value);
  126. if (target == null) return false;
  127. int reverseExitId = exit.ConnectedExitId ?? -1;
  128. foreach (var candidate in target.Exits)
  129. {
  130. if (candidate.Id == reverseExitId) continue;
  131. if (!candidate.IsUsed) return true;
  132. if (candidate.ConnectedRoomId.HasValue && !agent.HasVisited(candidate.ConnectedRoomId.Value)) return true;
  133. }
  134. return false;
  135. }
  136. private static Exit LeastVisitedPick(MazeAgent agent, List<Exit> exits)
  137. {
  138. int bestVisits = int.MaxValue;
  139. var bestExits = new List<Exit>();
  140. foreach (var exit in exits)
  141. {
  142. int visits = exit.ConnectedRoomId.HasValue ? agent.VisitCount(exit.ConnectedRoomId.Value) : 0;
  143. if (visits < bestVisits)
  144. {
  145. bestVisits = visits;
  146. bestExits.Clear();
  147. bestExits.Add(exit);
  148. }
  149. else if (visits == bestVisits)
  150. {
  151. bestExits.Add(exit);
  152. }
  153. }
  154. return RandomPick(bestExits);
  155. }
  156. private static Exit RandomPick(List<Exit> exits) => exits[UnityEngine.Random.Range(0, exits.Count)];
  157. /// <summary>
  158. /// Peek into a room (via an exit) to see if there are monsters and how many.
  159. /// Returns the perceived challenge rating, or 0 if no monsters/already explored.
  160. /// Agent sees incomplete info (60-100% of actual monsters, doesn't know about hidden ones).
  161. /// </summary>
  162. public float PeekThroughExit(Exit exit, MazeAgent agent)
  163. {
  164. if (!exit.ConnectedRoomId.HasValue)
  165. return 0; // Unresolved exit - can't peek yet
  166. Room nextRoom = _generator.Graph.Get(exit.ConnectedRoomId.Value);
  167. if (nextRoom == null || nextRoom.Encounter == null)
  168. return 0; // No encounter in this room
  169. return nextRoom.Encounter.GetPerceivedChallengeRating(agent.CharacterSheet);
  170. }
  171. /// <summary>
  172. /// Decide if an exit is worth taking based on threat level inside.
  173. /// Returns true if the exit is relatively safe or if the agent has no choice,
  174. /// false if the agent decides to retreat from this exit.
  175. /// </summary>
  176. private bool ShouldTakeExit(Exit exit, MazeAgent agent)
  177. {
  178. if (!exit.ConnectedRoomId.HasValue)
  179. return true; // Unresolved exit - proceed cautiously
  180. Room nextRoom = _generator.Graph.Get(exit.ConnectedRoomId.Value);
  181. if (nextRoom == null || nextRoom.Encounter == null)
  182. return true; // No encounter, safe to enter
  183. // Peek and evaluate threat
  184. float perceivedCR = nextRoom.Encounter.GetPerceivedChallengeRating(agent.CharacterSheet);
  185. // If threat is below threshold, take it. If above, retreat with some randomness.
  186. if (perceivedCR <= _retreatThreshold)
  187. return true; // Manageable threat
  188. // Higher difficulty = more likely to retreat, but add randomness for personality
  189. float retreatChance = Mathf.Clamp01((perceivedCR - _retreatThreshold) / 2.0f);
  190. return UnityEngine.Random.value > retreatChance;
  191. }
  192. /// <summary>
  193. /// Filter exits: remove those the agent wants to retreat from due to high threat.
  194. /// This is called during exit selection so dangerous rooms are avoided when possible.
  195. /// </summary>
  196. private List<Exit> FilterByThreat(List<Exit> exits, MazeAgent agent)
  197. {
  198. var safeExits = new List<Exit>();
  199. foreach (var exit in exits)
  200. {
  201. if (ShouldTakeExit(exit, agent))
  202. safeExits.Add(exit);
  203. }
  204. // If all exits are dangerous, agent must take one anyway (don't get stuck)
  205. return safeExits.Count > 0 ? safeExits : exits;
  206. }
  207. }
  208. }