AIAgent.cs 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. /// <summary>
  5. /// AI Agent that navigates the maze with limited knowledge
  6. /// Only knows about the room it's currently in and rooms visited by same character type
  7. /// </summary>
  8. public class AIAgent : MonoBehaviour
  9. {
  10. [Header("Agent Identity")]
  11. [SerializeField] private string agentCharacterType = "Default";
  12. [SerializeField] private int agentId;
  13. [Header("Agent Personalization")]
  14. private string agentName;
  15. private AgentStats agentStats;
  16. [Header("AI Settings")]
  17. [SerializeField] private float movementSpeed = 2f;
  18. [SerializeField] private float pathUpdateInterval = 0.5f;
  19. [SerializeField] private float stoppingDistance = 0.1f;
  20. private float actualMovementSpeed; // Per-agent speed variation to reduce synchronization
  21. [Header("Pathfinding")]
  22. [SerializeField] private bool showPath = true;
  23. [SerializeField] private LineRenderer pathRenderer;
  24. [SerializeField] private Color pathColor = Color.yellow;
  25. private MazeController mazeController;
  26. private MazeData maze;
  27. private MazePathfinder pathfinder;
  28. private AIRoomMemory roomMemory;
  29. private List<Vector2Int> currentPath = new();
  30. private int currentPathIndex = 0;
  31. private float lastPathUpdate = 0f;
  32. private Vector2Int currentRoom = Vector2Int.zero;
  33. private Vector2Int targetRoom = Vector2Int.zero;
  34. private Vector2Int targetExitTile = Vector2Int.zero; // Target hallway exit to move toward
  35. private Queue<int> recentRooms = new Queue<int>(); // Track last N rooms to avoid backtracking
  36. private const int RECENT_ROOMS_BUFFER_SIZE = 10; // Larger buffer = less backtracking
  37. private MazeRoom lastRoomExitedFrom = null; // Track which room we exited to prevent immediate backtracking
  38. private bool hasReachedGoal = false; // Track if agent has reached the goal room
  39. private bool commitedToExit = false; // Track if agent has committed to a specific hallway exit
  40. private float nextRandomWait = 0f; // Random wait time before exploring new areas
  41. private float agentRandomOffset = 0f; // Per-agent random offset to desync movement
  42. // Intelligence-driven disposition (seeded at spawn from Intelligence stat)
  43. // Will drive group-up logic, risk assessment, and future combat decisions
  44. private float groupUpAffinity; // 0-1: likelihood to seek allies over going solo
  45. private float riskTolerance; // 0-1: willingness to enter dangerous/unknown situations
  46. private bool knowsExitLocation = false; // True once agent has "seen" the exit room
  47. // ----- Group membership -----
  48. private AgentGroup currentGroup = null;
  49. private bool isGroupFollower = false; // True when this agent defers movement to the leader
  50. void Start()
  51. {
  52. mazeController = FindAnyObjectByType<MazeController>();
  53. if (mazeController == null)
  54. {
  55. Debug.LogError("AIAgent: MazeController not found in scene!");
  56. enabled = false;
  57. return;
  58. }
  59. maze = mazeController.GetCurrentMaze();
  60. if (maze == null)
  61. {
  62. Debug.LogError("AIAgent: Current maze is null!");
  63. enabled = false;
  64. return;
  65. }
  66. pathfinder = new MazePathfinder(maze);
  67. roomMemory = AIRoomMemoryManager.GetMemory(agentCharacterType);
  68. // Initialize personalization
  69. agentName = AgentNameGenerator.GenerateRandomName();
  70. agentStats = new AgentStats();
  71. gameObject.name = $"Agent_{agentId} ({agentName})";
  72. // Seed intelligence-driven disposition from stats
  73. groupUpAffinity = agentStats.GroupUpAffinity;
  74. riskTolerance = agentStats.RiskTolerance;
  75. // Initialize with a random start point
  76. if (maze.StartPoints.Count > 0)
  77. {
  78. int startIndex = agentId % maze.StartPoints.Count; // Distribute agents across start points
  79. Vector2Int startPos = maze.StartPoints[startIndex];
  80. // Get the start room and spawn randomly within it
  81. MazeRoom startRoom = maze.GetRoomAtTile(startPos.x, startPos.y);
  82. if (startRoom != null)
  83. {
  84. // Spawn at random position within start room
  85. Vector2Int randomPosInRoom = new Vector2Int(
  86. Random.Range(startRoom.MinX + 1, startRoom.MaxX),
  87. Random.Range(startRoom.MinY + 1, startRoom.MaxY)
  88. );
  89. transform.position = new Vector3(randomPosInRoom.x + 0.5f, 1f, randomPosInRoom.y + 0.5f);
  90. }
  91. else
  92. {
  93. // Fallback to exact start point
  94. transform.position = new Vector3(startPos.x + 0.5f, 1f, startPos.y + 0.5f);
  95. }
  96. // Rotate to be visible from above - 90 degrees around X axis
  97. transform.rotation = Quaternion.Euler(90, 0, 0);
  98. UpdateCurrentRoom(); // This will add to recentRooms and visit room
  99. }
  100. else
  101. {
  102. Debug.LogError("AIAgent: No start points found in maze!");
  103. enabled = false;
  104. return;
  105. }
  106. // Setup per-agent random offset to desync decision timings (prevents all agents moving in sync)
  107. agentRandomOffset = Random.Range(0f, pathUpdateInterval * 0.5f);
  108. nextRandomWait = Time.time + Random.Range(2f, 4f); // Random initial wait before first decision
  109. // Scale movement speed by the agent's Speed stat:
  110. // Speed=1 → ~1× base, Speed=100 → 2× base, plus ±10% desync jitter
  111. float speedMultiplier = 1f + (agentStats.Speed / 100f);
  112. actualMovementSpeed = movementSpeed * speedMultiplier * Random.Range(0.9f, 1.1f);
  113. Debug.Log($"[Agent {agentId}] {agentName} | {agentStats} | GroupUp: {groupUpAffinity:P0} | Risk: {riskTolerance:P0}");
  114. // Setup path renderer
  115. if (showPath && pathRenderer == null)
  116. {
  117. pathRenderer = gameObject.AddComponent<LineRenderer>();
  118. pathRenderer.startWidth = 0.1f;
  119. pathRenderer.endWidth = 0.1f;
  120. pathRenderer.material = new Material(Shader.Find("Sprites/Default"));
  121. pathRenderer.startColor = pathColor;
  122. pathRenderer.endColor = pathColor;
  123. }
  124. }
  125. void Update()
  126. {
  127. if (maze == null) return;
  128. // Followers defer all movement to the group leader
  129. if (isGroupFollower)
  130. {
  131. if (currentGroup != null && currentGroup.Leader != null)
  132. transform.position = currentGroup.Leader.transform.position;
  133. return;
  134. }
  135. // Update current room
  136. UpdateCurrentRoom();
  137. // Update pathfinding periodically with agent-specific offset to desync behavior
  138. if (Time.time - lastPathUpdate > pathUpdateInterval + agentRandomOffset)
  139. {
  140. UpdatePathToGoal();
  141. lastPathUpdate = Time.time;
  142. }
  143. // Move along path
  144. FollowPath();
  145. // Debug visualization
  146. if (showPath && pathRenderer != null)
  147. {
  148. UpdatePathVisualization();
  149. }
  150. }
  151. /// <summary>
  152. /// Updates the current room based on position
  153. /// </summary>
  154. private void UpdateCurrentRoom()
  155. {
  156. Vector2Int tilePos = WorldToTile(transform.position);
  157. MazeRoom room = maze.GetRoomAtTile(tilePos.x, tilePos.y);
  158. if (room != null)
  159. {
  160. if (currentRoom.x != room.Id)
  161. {
  162. currentRoom = new Vector2Int(room.Id, 0);
  163. roomMemory.VisitRoom(room.Id);
  164. // Track recent rooms to avoid immediate backtracking
  165. recentRooms.Enqueue(room.Id);
  166. if (recentRooms.Count > RECENT_ROOMS_BUFFER_SIZE)
  167. recentRooms.Dequeue();
  168. }
  169. }
  170. }
  171. /// <summary>
  172. /// Updates pathfinding to reach the goal
  173. /// Agent only knows about current room and visited rooms
  174. /// NEW LOGIC: Pick a hallway exit from current room and move straight to it
  175. /// </summary>
  176. private void UpdatePathToGoal()
  177. {
  178. if (maze.ExitPoints.Count == 0)
  179. {
  180. Debug.LogWarning($"AIAgent {agentId}: No exit points in maze!");
  181. return;
  182. }
  183. Vector2Int currentPos = WorldToTile(transform.position);
  184. MazeRoom currentRoomData = maze.GetRoomAtTile(currentPos.x, currentPos.y);
  185. // CHECK FOR GOAL ROOM FIRST - this should work even while following path
  186. var goalRooms = maze.GetRoomsByType(MazeRoom.RoomType.End);
  187. if (currentRoomData != null && goalRooms.Contains(currentRoomData))
  188. {
  189. if (!hasReachedGoal)
  190. {
  191. hasReachedGoal = true;
  192. currentPath.Clear();
  193. currentPathIndex = 0;
  194. }
  195. return; // Stay stopped
  196. }
  197. // If we already have a valid path and we're following it, don't recalculate (stay committed)
  198. if (currentPath.Count > 0 && currentPathIndex < currentPath.Count)
  199. {
  200. return; // Keep following existing path
  201. }
  202. // If we've committed to reaching an exit and haven't reached it yet, keep trying
  203. if (commitedToExit && targetExitTile != Vector2Int.zero)
  204. {
  205. // Try to find a path to the committed exit
  206. if (currentPath.Count == 0)
  207. {
  208. currentPath = FindPathInRoom(currentPos, targetExitTile, currentRoomData);
  209. currentPathIndex = 0;
  210. if (currentPath.Count > 0)
  211. {
  212. Debug.Log($"AIAgent {agentId}: Re-committed to exit {targetExitTile}");
  213. return;
  214. }
  215. }
  216. }
  217. // If in hallway (no room), just keep moving along current path
  218. // The hallway pathfinding will naturally move us toward exits
  219. if (currentRoomData == null)
  220. {
  221. // If we have a current path, keep following it through hallway
  222. if (currentPath.Count > 0 && currentPathIndex < currentPath.Count)
  223. {
  224. return; // Keep following path
  225. }
  226. // In hallway with no path - find next room to enter
  227. // PRIORITY 1: Find unvisited rooms, avoid the room we just exited
  228. // Collect all unvisited rooms
  229. List<MazeRoom> unvisitedRooms = new();
  230. foreach (var room in maze.Rooms)
  231. {
  232. // Skip the room we just exited (backtracking prevention)
  233. if (lastRoomExitedFrom != null && room.Id == lastRoomExitedFrom.Id)
  234. continue;
  235. // Prioritize unvisited rooms
  236. if (!roomMemory.HasVisited(room.Id))
  237. {
  238. unvisitedRooms.Add(room);
  239. }
  240. }
  241. MazeRoom targetRoom = null;
  242. // Random decision: 70% closest unvisited, 30% random unvisited (increases exploration variety)
  243. if (unvisitedRooms.Count > 0)
  244. {
  245. if (Random.value < 0.7f && unvisitedRooms.Count > 0)
  246. {
  247. // Pick closest unvisited room
  248. float closestUnvisitedDistance = float.MaxValue;
  249. foreach (var room in unvisitedRooms)
  250. {
  251. Vector2Int roomCenter = room.GetCenter();
  252. float distance = Vector2Int.Distance(currentPos, roomCenter);
  253. if (distance < closestUnvisitedDistance)
  254. {
  255. closestUnvisitedDistance = distance;
  256. targetRoom = room;
  257. }
  258. }
  259. }
  260. else
  261. {
  262. // Pick random unvisited room for variety
  263. targetRoom = unvisitedRooms[Random.Range(0, unvisitedRooms.Count)];
  264. }
  265. }
  266. // If no unvisited room found, pick nearest room (except the one we came from)
  267. if (targetRoom == null)
  268. {
  269. float closestDistance = float.MaxValue;
  270. foreach (var room in maze.Rooms)
  271. {
  272. // Skip the room we just exited
  273. if (lastRoomExitedFrom != null && room.Id == lastRoomExitedFrom.Id)
  274. continue;
  275. Vector2Int roomCenter = room.GetCenter();
  276. float distance = Vector2Int.Distance(currentPos, roomCenter);
  277. if (distance < closestDistance)
  278. {
  279. closestDistance = distance;
  280. targetRoom = room;
  281. }
  282. }
  283. }
  284. // Exit-room caution: if the chosen target is the exit room and we spotted
  285. // it through a short corridor, smarter agents may hesitate or route around.
  286. // (Low intelligence agents rush straight in; high intelligence agents are cautious
  287. // and may wait for allies — once group logic is implemented.)
  288. if (targetRoom != null)
  289. {
  290. var goalRoomsCheck = maze.GetRoomsByType(MazeRoom.RoomType.End);
  291. if (goalRoomsCheck.Contains(targetRoom))
  292. {
  293. knowsExitLocation = true;
  294. // High-intelligence agents (INT > 50) pause briefly to "assess"
  295. // before committing — placeholder for future ally/fight evaluation
  296. if (agentStats.Intelligence > 50)
  297. {
  298. nextRandomWait = Time.time + (agentStats.Intelligence / 100f) * 2f;
  299. }
  300. }
  301. }
  302. if (targetRoom != null)
  303. {
  304. currentPath = FindPathToNearestRoom(currentPos, targetRoom);
  305. currentPathIndex = 0;
  306. if (currentPath.Count > 0)
  307. {
  308. bool isUnvisited = !roomMemory.HasVisited(targetRoom.Id);
  309. return;
  310. }
  311. else
  312. {
  313. // Debug.LogWarning($"AIAgent {agentId}: Failed to path to room {targetRoom.Id} from hallway at {currentPos}. Trying any adjacent room.");
  314. // Fallback: try to find ANY adjacent room and move directly toward it
  315. foreach (var room in maze.Rooms)
  316. {
  317. if (lastRoomExitedFrom != null && room.Id == lastRoomExitedFrom.Id)
  318. continue;
  319. currentPath = FindPathToNearestRoom(currentPos, room);
  320. if (currentPath.Count > 0)
  321. {
  322. return;
  323. }
  324. }
  325. Debug.LogError($"AIAgent {agentId}: STUCK in hallway at {currentPos} - no paths found to any room!");
  326. return;
  327. }
  328. }
  329. Debug.LogWarning($"AIAgent {agentId}: In hallway but no reachable rooms!");
  330. return;
  331. }
  332. // MAIN LOGIC: In regular room, find a hallway exit and path to it
  333. // Get all hallway tiles adjacent to this room
  334. List<Vector2Int> hallwayExits = FindHallwayExits(currentRoomData, currentPos);
  335. if (hallwayExits.Count > 0)
  336. {
  337. // Peek through each exit: if the corridor leads directly to the exit room
  338. // and the agent has enough intelligence, avoid that exit for now and pick another.
  339. List<Vector2Int> safeExits = new List<Vector2Int>(hallwayExits);
  340. if (!knowsExitLocation)
  341. {
  342. var goalRoomsList = maze.GetRoomsByType(MazeRoom.RoomType.End);
  343. foreach (var exit in hallwayExits)
  344. {
  345. MazeRoom peekedRoom = PeekCorridorDestination(exit, currentRoomData);
  346. if (peekedRoom != null && goalRoomsList.Contains(peekedRoom))
  347. {
  348. knowsExitLocation = true;
  349. // Low-intelligence agents rush the exit; high-intelligence ones
  350. // reconsider (they may want allies or a better moment)
  351. if (agentStats.Intelligence > 40 && safeExits.Count > 1)
  352. {
  353. safeExits.Remove(exit); // Avoid this corridor for now
  354. }
  355. }
  356. }
  357. }
  358. if (safeExits.Count == 0) safeExits = hallwayExits; // Fallback: all exits
  359. // Pick a random hallway exit from the (possibly filtered) list
  360. Vector2Int chosenExit = safeExits[Random.Range(0, safeExits.Count)];
  361. // Path directly to that exit
  362. currentPath = FindPathInRoom(currentPos, chosenExit, currentRoomData);
  363. currentPathIndex = 0;
  364. if (currentPath.Count > 0)
  365. {
  366. targetExitTile = chosenExit;
  367. commitedToExit = true;
  368. // Add random delay before next decision to increase variety
  369. nextRandomWait = Time.time + Random.Range(1.5f, 3.5f);
  370. }
  371. else
  372. {
  373. Debug.LogWarning($"AIAgent {agentId}: Could not path to hallway exit");
  374. commitedToExit = false;
  375. }
  376. }
  377. else
  378. {
  379. Debug.LogWarning($"AIAgent {agentId}: No hallway exits found from room {currentRoomData.Id}");
  380. commitedToExit = false;
  381. }
  382. }
  383. /// <summary>
  384. /// Chooses the next room to move to
  385. /// Searches around the current room to find adjacent rooms
  386. /// Avoids recently visited rooms to prevent backtracking
  387. /// </summary>
  388. private MazeRoom ChooseNextRoom(MazeRoom currentRoom)
  389. {
  390. // Find all adjacent rooms by checking walkable tiles in all directions from room boundaries
  391. List<MazeRoom> connectedRooms = new();
  392. Vector2Int roomCenter = currentRoom.GetCenter();
  393. // Check from each direction outward from the room center
  394. Vector2Int[] directions = new Vector2Int[]
  395. {
  396. Vector2Int.up, Vector2Int.down, Vector2Int.left, Vector2Int.right,
  397. Vector2Int.up + Vector2Int.left, Vector2Int.up + Vector2Int.right,
  398. Vector2Int.down + Vector2Int.left, Vector2Int.down + Vector2Int.right
  399. };
  400. // Shuffle directions for randomness
  401. for (int i = directions.Length - 1; i > 0; i--)
  402. {
  403. int randomIndex = Random.Range(0, i + 1);
  404. var temp = directions[i];
  405. directions[i] = directions[randomIndex];
  406. directions[randomIndex] = temp;
  407. }
  408. // Try each direction and look for tiles that lead to other rooms
  409. foreach (var dir in directions)
  410. {
  411. for (int dist = 1; dist < 20; dist++) // Search up to 20 tiles away
  412. {
  413. Vector2Int testPos = roomCenter + (dir * dist);
  414. if (!maze.IsInBounds(testPos.x, testPos.y) || !maze.IsWalkable(testPos.x, testPos.y))
  415. continue;
  416. MazeRoom testRoom = maze.GetRoomAtTile(testPos.x, testPos.y);
  417. if (testRoom != null && testRoom.Id != currentRoom.Id && !connectedRooms.Contains(testRoom))
  418. {
  419. connectedRooms.Add(testRoom);
  420. break; // Found a room in this direction, move to next direction
  421. }
  422. }
  423. }
  424. if (connectedRooms.Count == 0)
  425. {
  426. Debug.LogWarning($"AIAgent {agentId}: No adjacent rooms found from room {currentRoom.Id}");
  427. return null;
  428. }
  429. // Filter out recently visited rooms (to avoid backtracking)
  430. List<MazeRoom> nonRecentRooms = connectedRooms.Where(r => !recentRooms.Contains(r.Id)).ToList();
  431. // PRIORITY 1: Strongly prefer completely unvisited rooms (not recently visited either)
  432. var completelyUnvisited = nonRecentRooms.Where(r => !roomMemory.HasVisited(r.Id)).ToList();
  433. if (completelyUnvisited.Count > 0)
  434. {
  435. MazeRoom chosen = completelyUnvisited[Random.Range(0, completelyUnvisited.Count)];
  436. return chosen;
  437. }
  438. // PRIORITY 2: Try non-recent rooms even if visited by this character type
  439. if (nonRecentRooms.Count > 0)
  440. {
  441. // Among non-recent rooms, prefer unvisited by this agent's character type
  442. var unvisitedByType = nonRecentRooms.Where(r => !roomMemory.HasVisited(r.Id)).ToList();
  443. if (unvisitedByType.Count > 0)
  444. {
  445. MazeRoom chosen = unvisitedByType[Random.Range(0, unvisitedByType.Count)];
  446. return chosen;
  447. }
  448. // Otherwise just pick a random non-recent room
  449. MazeRoom chosen2 = nonRecentRooms[Random.Range(0, nonRecentRooms.Count)];
  450. return chosen2;
  451. }
  452. // PRIORITY 3: If all rooms are recent, pick one that's been visited least recently
  453. // Find the room in connectedRooms that was added to recentRooms earliest (will be dequeued first)
  454. MazeRoom leastRecentRoom = connectedRooms[0];
  455. foreach (var room in connectedRooms)
  456. {
  457. if (!roomMemory.HasVisited(room.Id))
  458. {
  459. leastRecentRoom = room;
  460. break;
  461. }
  462. }
  463. Debug.Log($"AIAgent {agentId}: All rooms recent, choosing least-recent room {leastRecentRoom.Id}");
  464. return leastRecentRoom;
  465. }
  466. /// <summary>
  467. /// Finds the nearest room from a position (used when in hallway)
  468. /// </summary>
  469. private MazeRoom FindNearestRoom(Vector2Int position)
  470. {
  471. MazeRoom nearest = null;
  472. float nearestDistance = float.MaxValue;
  473. foreach (var room in maze.Rooms)
  474. {
  475. Vector2Int roomCenter = room.GetCenter();
  476. float distance = Vector2Int.Distance(position, roomCenter);
  477. if (distance < nearestDistance)
  478. {
  479. nearestDistance = distance;
  480. nearest = room;
  481. }
  482. }
  483. return nearest;
  484. }
  485. /// <summary>
  486. /// Finds all hallway exit tiles adjacent to a room
  487. /// These are walkable tiles just outside the room boundary
  488. /// </summary>
  489. /// <summary>
  490. /// Peeks along a corridor starting from a hallway exit tile.
  491. /// Follows walkable non-room tiles up to a short distance and returns
  492. /// the first room found at the other end, or null if no room is close.
  493. /// Used by intelligence logic to detect if an exit leads straight to the goal.
  494. /// </summary>
  495. private MazeRoom PeekCorridorDestination(Vector2Int exitTile, MazeRoom sourceRoom, int maxPeekDistance = 12)
  496. {
  497. // BFS outward from the exit tile, staying in non-room (hallway) tiles
  498. var visited = new HashSet<Vector2Int> { exitTile };
  499. var queue = new Queue<Vector2Int>();
  500. queue.Enqueue(exitTile);
  501. while (queue.Count > 0)
  502. {
  503. Vector2Int tile = queue.Dequeue();
  504. Vector2Int[] dirs = {
  505. new(tile.x + 1, tile.y), new(tile.x - 1, tile.y),
  506. new(tile.x, tile.y + 1), new(tile.x, tile.y - 1)
  507. };
  508. foreach (var next in dirs)
  509. {
  510. if (!maze.IsInBounds(next.x, next.y) || !maze.IsWalkable(next.x, next.y)) continue;
  511. if (visited.Contains(next)) continue;
  512. MazeRoom nextRoom = maze.GetRoomAtTile(next.x, next.y);
  513. if (nextRoom != null && nextRoom.Id != sourceRoom.Id)
  514. return nextRoom; // Found the room at the end of this corridor
  515. // Only continue through hallway tiles and within peek distance
  516. if (nextRoom == null && Vector2Int.Distance(exitTile, next) < maxPeekDistance)
  517. {
  518. visited.Add(next);
  519. queue.Enqueue(next);
  520. }
  521. }
  522. }
  523. return null;
  524. }
  525. private List<Vector2Int> FindHallwayExits(MazeRoom room, Vector2Int currentPos)
  526. {
  527. List<Vector2Int> exits = new();
  528. HashSet<Vector2Int> addedExits = new();
  529. // Check all tiles on the boundary of the room
  530. // North boundary
  531. for (int x = room.MinX; x <= room.MaxX; x++)
  532. {
  533. int y = room.MinY - 1;
  534. if (maze.IsInBounds(x, y) && maze.IsWalkable(x, y) && !addedExits.Contains(new Vector2Int(x, y)))
  535. {
  536. exits.Add(new Vector2Int(x, y));
  537. addedExits.Add(new Vector2Int(x, y));
  538. }
  539. }
  540. // South boundary
  541. for (int x = room.MinX; x <= room.MaxX; x++)
  542. {
  543. int y = room.MaxY + 1;
  544. if (maze.IsInBounds(x, y) && maze.IsWalkable(x, y) && !addedExits.Contains(new Vector2Int(x, y)))
  545. {
  546. exits.Add(new Vector2Int(x, y));
  547. addedExits.Add(new Vector2Int(x, y));
  548. }
  549. }
  550. // West boundary
  551. for (int y = room.MinY; y <= room.MaxY; y++)
  552. {
  553. int x = room.MinX - 1;
  554. if (maze.IsInBounds(x, y) && maze.IsWalkable(x, y) && !addedExits.Contains(new Vector2Int(x, y)))
  555. {
  556. exits.Add(new Vector2Int(x, y));
  557. addedExits.Add(new Vector2Int(x, y));
  558. }
  559. }
  560. // East boundary
  561. for (int y = room.MinY; y <= room.MaxY; y++)
  562. {
  563. int x = room.MaxX + 1;
  564. if (maze.IsInBounds(x, y) && maze.IsWalkable(x, y) && !addedExits.Contains(new Vector2Int(x, y)))
  565. {
  566. exits.Add(new Vector2Int(x, y));
  567. addedExits.Add(new Vector2Int(x, y));
  568. }
  569. }
  570. return exits;
  571. }
  572. /// <summary>
  573. /// Finds a path from current position to the nearest room (when in hallway)
  574. /// </summary>
  575. private List<Vector2Int> FindPathToNearestRoom(Vector2Int start, MazeRoom targetRoom)
  576. {
  577. // Simple pathfinding through hallways using A*
  578. var openSet = new List<Vector2Int> { start };
  579. var cameFrom = new Dictionary<Vector2Int, Vector2Int>();
  580. var gScore = new Dictionary<Vector2Int, float> { [start] = 0 };
  581. var targetCenter = targetRoom.GetCenter();
  582. var fScore = new Dictionary<Vector2Int, float> { [start] = Vector2Int.Distance(start, targetCenter) };
  583. int iterations = 0;
  584. const int maxIterations = 2000; // Increased from 500 to handle larger mazes
  585. while (openSet.Count > 0 && iterations < maxIterations)
  586. {
  587. iterations++;
  588. // Find node with lowest fScore
  589. Vector2Int current = openSet[0];
  590. float lowestF = fScore[current];
  591. for (int i = 1; i < openSet.Count; i++)
  592. {
  593. if (fScore[openSet[i]] < lowestF)
  594. {
  595. current = openSet[i];
  596. lowestF = fScore[current];
  597. }
  598. }
  599. // If we reached the target room, we're done
  600. MazeRoom currentRoom = maze.GetRoomAtTile(current.x, current.y);
  601. if (currentRoom != null && currentRoom.Id == targetRoom.Id)
  602. {
  603. return ReconstructPath(cameFrom, current);
  604. }
  605. openSet.Remove(current);
  606. // Check neighbors
  607. Vector2Int[] neighbors = new[]
  608. {
  609. new Vector2Int(current.x + 1, current.y),
  610. new Vector2Int(current.x - 1, current.y),
  611. new Vector2Int(current.x, current.y + 1),
  612. new Vector2Int(current.x, current.y - 1),
  613. };
  614. foreach (var neighbor in neighbors)
  615. {
  616. if (!maze.IsInBounds(neighbor.x, neighbor.y) || !maze.IsWalkable(neighbor.x, neighbor.y))
  617. continue;
  618. float tentativeG = gScore[current] + 1;
  619. if (!gScore.ContainsKey(neighbor) || tentativeG < gScore[neighbor])
  620. {
  621. cameFrom[neighbor] = current;
  622. gScore[neighbor] = tentativeG;
  623. fScore[neighbor] = tentativeG + Vector2Int.Distance(neighbor, targetCenter);
  624. if (!openSet.Contains(neighbor))
  625. {
  626. openSet.Add(neighbor);
  627. }
  628. }
  629. }
  630. }
  631. // Debug.LogWarning($"AIAgent {agentId}: FindPathToNearestRoom FAILED after {iterations} iterations. Start: {start}, Target room {targetRoom.Id} center: {targetCenter}");
  632. return new List<Vector2Int>();
  633. }
  634. /// <summary>
  635. /// Finds a boundary tile of the current room that points toward the next room
  636. /// </summary>
  637. private Vector2Int FindBoundaryTileToward(MazeRoom currentRoom, MazeRoom nextRoom, Vector2Int currentPos)
  638. {
  639. Vector2Int nextRoomCenter = nextRoom.GetCenter();
  640. Vector2Int closestBoundary = currentRoom.GetCenter();
  641. float closestDistance = float.MaxValue;
  642. // Check all boundary tiles of current room
  643. for (int x = currentRoom.MinX; x <= currentRoom.MaxX; x++)
  644. {
  645. for (int y = currentRoom.MinY; y <= currentRoom.MaxY; y++)
  646. {
  647. // Only check boundary and walkable tiles
  648. if ((x == currentRoom.MinX || x == currentRoom.MaxX || y == currentRoom.MinY || y == currentRoom.MaxY) &&
  649. maze.IsWalkable(x, y))
  650. {
  651. // Find boundary tile closest to next room center
  652. float distToNext = Vector2Int.Distance(new Vector2Int(x, y), nextRoomCenter);
  653. if (distToNext < closestDistance)
  654. {
  655. closestDistance = distToNext;
  656. closestBoundary = new Vector2Int(x, y);
  657. }
  658. }
  659. }
  660. }
  661. return closestBoundary;
  662. }
  663. /// <summary>
  664. /// Finds a path within a single room (limited knowledge)
  665. /// </summary>
  666. private List<Vector2Int> FindPathInRoom(Vector2Int start, Vector2Int goal, MazeRoom room)
  667. {
  668. // Use simple A* within room bounds
  669. var openSet = new List<Vector2Int> { start };
  670. var cameFrom = new Dictionary<Vector2Int, Vector2Int>();
  671. var gScore = new Dictionary<Vector2Int, float> { [start] = 0 };
  672. var fScore = new Dictionary<Vector2Int, float> { [start] = Vector2Int.Distance(start, goal) };
  673. int iterations = 0;
  674. const int maxIterations = 1000;
  675. while (openSet.Count > 0 && iterations < maxIterations)
  676. {
  677. iterations++;
  678. // Find node with lowest fScore
  679. Vector2Int current = openSet[0];
  680. float lowestF = fScore[current];
  681. for (int i = 1; i < openSet.Count; i++)
  682. {
  683. if (fScore[openSet[i]] < lowestF)
  684. {
  685. current = openSet[i];
  686. lowestF = fScore[current];
  687. }
  688. }
  689. if (current == goal)
  690. {
  691. return ReconstructPath(cameFrom, current);
  692. }
  693. openSet.Remove(current);
  694. // Check only neighbors within the room
  695. var neighbors = GetRoomNeighbors(current, room);
  696. foreach (var neighbor in neighbors)
  697. {
  698. float tentativeG = gScore[current] + 1;
  699. if (!gScore.ContainsKey(neighbor) || tentativeG < gScore[neighbor])
  700. {
  701. cameFrom[neighbor] = current;
  702. gScore[neighbor] = tentativeG;
  703. fScore[neighbor] = tentativeG + Vector2Int.Distance(neighbor, goal);
  704. if (!openSet.Contains(neighbor))
  705. {
  706. openSet.Add(neighbor);
  707. }
  708. }
  709. }
  710. }
  711. return new List<Vector2Int>();
  712. }
  713. /// <summary>
  714. /// Gets walkable neighbors within a room or at room boundary
  715. /// Allows pathfinding to reach hallway exits outside room
  716. /// </summary>
  717. private List<Vector2Int> GetRoomNeighbors(Vector2Int position, MazeRoom room)
  718. {
  719. var neighbors = new List<Vector2Int>();
  720. Vector2Int[] directions = new[]
  721. {
  722. new Vector2Int(position.x + 1, position.y),
  723. new Vector2Int(position.x - 1, position.y),
  724. new Vector2Int(position.x, position.y + 1),
  725. new Vector2Int(position.x, position.y - 1),
  726. };
  727. foreach (var dir in directions)
  728. {
  729. // Allow tiles within room OR immediately adjacent to room (boundary)
  730. bool inBounds = maze.IsInBounds(dir.x, dir.y);
  731. bool isWalkable = maze.IsWalkable(dir.x, dir.y);
  732. bool inRoom = room.Contains(dir.x, dir.y);
  733. bool nearBoundary = (dir.x == room.MinX - 1 || dir.x == room.MaxX + 1 ||
  734. dir.y == room.MinY - 1 || dir.y == room.MaxY + 1);
  735. if (inBounds && isWalkable && (inRoom || nearBoundary))
  736. {
  737. neighbors.Add(dir);
  738. }
  739. }
  740. return neighbors;
  741. }
  742. /// <summary>
  743. /// Reconstructs path from A* results
  744. /// </summary>
  745. private List<Vector2Int> ReconstructPath(Dictionary<Vector2Int, Vector2Int> cameFrom, Vector2Int current)
  746. {
  747. var path = new List<Vector2Int> { current };
  748. while (cameFrom.ContainsKey(current))
  749. {
  750. current = cameFrom[current];
  751. path.Insert(0, current);
  752. }
  753. return path;
  754. }
  755. /// <summary>
  756. /// Follows the current path
  757. /// </summary>
  758. private void FollowPath()
  759. {
  760. if (currentPath.Count == 0) return;
  761. Vector2Int currentTarget = currentPath[currentPathIndex];
  762. // Maze coordinates: X,Y → World: X,Z (Y=0 is ground level)
  763. // Keep Y at 1f to stay above the maze floor
  764. Vector3 targetWorldPos = new Vector3(currentTarget.x + 0.5f, 1f, currentTarget.y + 0.5f);
  765. Vector3 direction = (targetWorldPos - transform.position).normalized;
  766. // Move directly instead of using Translate (no rigidbody)
  767. transform.position += direction * actualMovementSpeed * Time.deltaTime;
  768. // Check if we've exited the room (entered hallway)
  769. Vector2Int currentPos = WorldToTile(transform.position);
  770. MazeRoom roomAtPos = maze.GetRoomAtTile(currentPos.x, currentPos.y);
  771. if (roomAtPos == null && currentRoom.x != -1)
  772. {
  773. // We've entered a hallway - track which room we came from to prevent immediate backtracking
  774. lastRoomExitedFrom = maze.Rooms.FirstOrDefault(r => r.Id == currentRoom.x);
  775. commitedToExit = false; // No longer committed to that exit, now in hallway
  776. targetExitTile = Vector2Int.zero; // Clear the target exit
  777. }
  778. // Move to next waypoint when close enough
  779. if (Vector3.Distance(transform.position, targetWorldPos) < stoppingDistance)
  780. {
  781. currentPathIndex++;
  782. if (currentPathIndex >= currentPath.Count)
  783. {
  784. currentPath.Clear();
  785. }
  786. }
  787. }
  788. /// <summary>
  789. /// Updates the path visualization
  790. /// </summary>
  791. private void UpdatePathVisualization()
  792. {
  793. if (currentPath.Count == 0)
  794. {
  795. pathRenderer.positionCount = 0;
  796. return;
  797. }
  798. var positions = new Vector3[currentPath.Count];
  799. for (int i = 0; i < currentPath.Count; i++)
  800. {
  801. // Maze coordinates: X,Y → World: X,Z (Y=0 is ground level)
  802. // Keep Y at 1f to stay above the maze floor
  803. positions[i] = new Vector3(currentPath[i].x + 0.5f, 1f, currentPath[i].y + 0.5f);
  804. }
  805. pathRenderer.positionCount = positions.Length;
  806. pathRenderer.SetPositions(positions);
  807. }
  808. /// <summary>
  809. /// Converts world position to tile coordinate
  810. /// Maze coordinates: X,Y ← World: X,Z (Y=0 is ground level)
  811. /// </summary>
  812. private Vector2Int WorldToTile(Vector3 worldPos)
  813. {
  814. return new Vector2Int(Mathf.FloorToInt(worldPos.x), Mathf.FloorToInt(worldPos.z));
  815. }
  816. /// <summary>
  817. /// Gets agent ID
  818. /// </summary>
  819. public int AgentId => agentId;
  820. /// <summary>
  821. /// Gets agent character type
  822. /// </summary>
  823. public string CharacterType => agentCharacterType;
  824. /// <summary>
  825. /// Gets current room
  826. /// </summary>
  827. public Vector2Int CurrentRoom => currentRoom;
  828. /// <summary>
  829. /// Gets room memory
  830. /// </summary>
  831. public AIRoomMemory RoomMemory => roomMemory;
  832. /// <summary>
  833. /// Gets agent ID (public accessor for triggers)
  834. /// </summary>
  835. public int GetAgentId() => agentId;
  836. /// <summary>
  837. /// Called by ExitRoomTrigger when agent enters the goal room
  838. /// Immediately stops all movement
  839. /// </summary>
  840. public void StopAtGoal()
  841. {
  842. hasReachedGoal = true;
  843. currentPath.Clear();
  844. currentPathIndex = 0;
  845. commitedToExit = false;
  846. }
  847. /// <summary>
  848. /// Gets whether this agent has reached the goal
  849. /// </summary>
  850. public bool HasReachedGoal => hasReachedGoal;
  851. /// <summary>
  852. /// Gets agent's personalized name
  853. /// </summary>
  854. public string AgentName => agentName;
  855. /// <summary>
  856. /// Gets agent's stats
  857. /// </summary>
  858. public AgentStats Stats => agentStats;
  859. /// <summary>
  860. /// 0-1 tendency to seek allies over going solo (driven by Intelligence)
  861. /// </summary>
  862. public float GroupUpAffinity => groupUpAffinity;
  863. /// <summary>
  864. /// 0-1 willingness to take risks in combat or unknown rooms (driven by Intelligence)
  865. /// </summary>
  866. public float RiskTolerance => riskTolerance;
  867. /// <summary>
  868. /// Whether this agent has spotted the exit room (through corridor peeking or direct entry)
  869. /// </summary>
  870. public bool KnowsExitLocation => knowsExitLocation;
  871. void OnMouseDown()
  872. {
  873. // If this agent is in a group, clicking any member shows the group panel
  874. if (currentGroup != null)
  875. AgentInfoPanel.ShowGroupInfo(currentGroup);
  876. else
  877. AgentInfoPanel.ShowAgentInfo(this);
  878. }
  879. public void SetShowPath(bool show)
  880. {
  881. showPath = show;
  882. if (pathRenderer != null)
  883. {
  884. pathRenderer.enabled = show;
  885. }
  886. }
  887. public bool GetShowPath() => showPath;
  888. // ------------------------------------------------------------------ //
  889. // Group API //
  890. // ------------------------------------------------------------------ //
  891. /// <summary>Called by AgentGroup when this agent is added.</summary>
  892. public void JoinGroup(AgentGroup group)
  893. {
  894. currentGroup = group;
  895. isGroupFollower = group.Leader != this;
  896. Debug.Log($"[Agent {agentId}] {agentName} joined group {group.GroupId} as {(isGroupFollower ? "follower" : "leader")}");
  897. }
  898. /// <summary>Called by AgentGroup when this agent leaves or group dissolves.</summary>
  899. public void LeaveGroup()
  900. {
  901. currentGroup = null;
  902. isGroupFollower = false;
  903. // Restore own renderer
  904. var mr = GetComponent<MeshRenderer>();
  905. if (mr != null) mr.enabled = true;
  906. var lr = GetComponent<LineRenderer>();
  907. if (lr != null) lr.enabled = showPath;
  908. }
  909. /// <summary>The group this agent belongs to, or null if solo.</summary>
  910. public AgentGroup Group => currentGroup;
  911. /// <summary>True if another agent is driving this agent's position.</summary>
  912. public bool IsGroupFollower => isGroupFollower;
  913. /// <summary>True if this agent leads a group (is not a follower but group exists).</summary>
  914. public bool IsGroupLeader => currentGroup != null && !isGroupFollower;
  915. }