# AI Agent System - Setup & Usage Guide ## Overview The AI Agent System allows you to spawn intelligent agents that navigate the maze with limited knowledge, just like a real player would. Each agent only knows about: - The room they are currently in - Which rooms their character type has visited before - Where the exits of the current room lead This creates a realistic exploration experience where agents must be smart about which paths to take based on shared information from other agents of the same type. ## Components ### 1. **AIAgent** (`AIAgent.cs`) - **Purpose**: Individual AI agent that navigates the maze - **Key Features**: - Limited knowledge (only knows current room) - Shares room memory with other agents of same character type - Pathfinds using A* algorithm within room bounds - Moves toward goal room while exploring unvisited rooms - Visual path debugging with LineRenderer - **Inspector Properties**: - `agentCharacterType`: Type/name of the agent (e.g., "Warrior", "Scout") - `movementSpeed`: How fast the agent moves (default: 2) - `pathUpdateInterval`: How often to recalculate path (default: 0.5s) - `stoppingDistance`: Distance to stop at waypoint (default: 0.1) - `showPath`: Draw path visualization (default: true) - `pathColor`: Color of path visualization ### 2. **AIAgentManager** (`AIAgentManager.cs`) - **Purpose**: Manages spawning and tracking of all AI agents - **Key Features**: - Configurable initial agent count - Spawn agents on startup or during gameplay - Track active agents - Reset agents when new maze is generated - Get agent statistics - Multiple character types supported - **Inspector Properties**: - `initialAgentCount`: How many agents to spawn at start (default: 10) - `agentCharacterType`: Default character type for agents (default: "Default") - `spawnDelay`: Delay between spawning each agent (default: 0.1s) - `agentPrefab`: Prefab to use for agent (auto-created if not set) - `showAgentPaths`: Show paths for all agents (default: true) - `agentPathColor`: Color for agent paths (default: yellow) - **Key Methods**: ```csharp // Spawn a single agent AIAgent agent = agentManager.SpawnAgent(); // Spawn multiple agents agentManager.SpawnAgents(5); // Get agent counts int total = agentManager.GetAgentCount(); int byType = agentManager.GetAgentCountByType("Warrior"); // Get stats for display string stats = agentManager.GetAgentStats(); // Reset for new maze agentManager.ResetForNewMaze(); ``` ### 3. **AIRoomMemory** (`AIRoomMemory.cs`) - **Purpose**: Tracks which rooms have been visited by agents of a character type - **Key Features**: - Shared memory system per character type - Tracks visited room IDs - Tracks last visit time per room - Filter unvisited rooms for exploration - Global manager for all character types - **Usage**: ```csharp // Get or create memory for a character type AIRoomMemory memory = AIRoomMemoryManager.GetMemory("Warrior"); // Mark a room as visited memory.VisitRoom(roomId); // Check if room was visited if (memory.HasVisited(roomId)) { ... } // Get all visited rooms HashSet visited = memory.GetVisitedRooms(); // Filter unvisited from a list var unvisited = memory.FilterUnvisitedRooms(roomList); ``` ### 4. **AIAgentUIDisplay** (`AIAgentUIDisplay.cs`) - Optional - **Purpose**: Display agent statistics and provide controls - **Features**: - Real-time agent count display - Exploration statistics per character type - Runtime agent spawning with keyboard shortcuts - Auto-creates UI if needed - **Keyboard Controls**: - `A`: Spawn 1 agent - `S`: Spawn 5 agents - `C`: Clear all agents ## Setup Instructions ### Quick Setup (Automatic) 1. **Attach to MazeController**: - Select your GameObject with MazeController component - In Inspector, check the "Spawn AI Agents" checkbox under AI Agents section - (Optional) Customize agent count, type, and spawn delay 2. **That's it!** Agents will spawn automatically when the maze generates ### Manual Setup 1. **Create Agent Manager**: - Create an empty GameObject as child of MazeController - Add `AIAgentManager` component - Configure agent count and type - In MazeController, assign this manager to the `agentManager` field 2. **Add UI Display (Optional)**: - Create empty GameObject - Add `AIAgentUIDisplay` component - Choose to auto-create UI or assign existing TextMeshPro elements 3. **In MazeController**: - Ensure `spawnAIAgents` is checked ## Usage Examples ### Example 1: Spawn Agents on Start ```csharp public class GameManager : MonoBehaviour { void Start() { MazeController maze = FindFirstObjectByType(); AIAgentManager agentManager = maze.GetAgentManager(); // Agents already spawned if spawnAIAgents is enabled Debug.Log($"Spawned {agentManager.GetAgentCount()} agents"); } } ``` ### Example 2: Spawn More Agents During Gameplay ```csharp public class AISpawner : MonoBehaviour { private AIAgentManager agentManager; void Start() { MazeController maze = FindFirstObjectByType(); agentManager = maze.GetAgentManager(); } void Update() { // Spawn 3 agents every 10 seconds if (Input.GetKeyDown(KeyCode.E)) { agentManager.SpawnAgents(3); } } } ``` ### Example 3: Create Different Agent Types ```csharp public class MultiTypeAgentSpawner : MonoBehaviour { void Start() { MazeController maze = FindFirstObjectByType(); AIAgentManager agentManager = maze.GetAgentManager(); // Current agents are "Default" type // To spawn other types, you would need to: // 1. Create new managers for each type // 2. Or modify agentCharacterType and spawn // Example: Manually spawn agents of different types SpawnAgentType("Warrior", 5); SpawnAgentType("Scout", 3); SpawnAgentType("Rogue", 2); } void SpawnAgentType(string type, int count) { for (int i = 0; i < count; i++) { // This would require extending AIAgentManager or creating type-specific managers } } } ``` ### Example 4: Monitor Agent Progress ```csharp public class AgentProgressMonitor : MonoBehaviour { private AIAgentManager agentManager; private float checkInterval = 2f; private float lastCheck = 0f; void Start() { MazeController maze = FindFirstObjectByType(); agentManager = maze.GetAgentManager(); } void Update() { if (Time.time - lastCheck > checkInterval) { string stats = agentManager.GetAgentStats(); Debug.Log(stats); lastCheck = Time.time; } } } ``` ## Agent Behavior ### Decision Making 1. **Current State**: Agent determines its current room 2. **Goal Check**: If in goal room, path to exit 3. **Room Selection**: Choose next room to visit based on: - Unvisited rooms (priority) - Rooms visited by same character type - Adjacent rooms to current location 4. **Pathfinding**: Use A* within current room bounds only 5. **Movement**: Follow calculated path at configured speed ### Limitations (By Design) - Cannot see through walls into adjacent rooms - Only knows about rooms their character type has explored - Must reach room exits to move to adjacent rooms - Cannot take shortcuts through unknown areas ## Performance Considerations - **Agent Count**: Each agent runs pathfinding update at configurable interval - **Default**: 10 agents with 0.5s update interval - **Scaling**: For 100+ agents, consider increasing update interval - **Memory**: Shared room memory per character type is very efficient ### Optimization Tips 1. Increase `pathUpdateInterval` for more agents (0.5s → 1.0s) 2. Reduce `spawnDelay` for faster agent creation 3. Use fewer agent types (shared memory is more efficient) 4. Disable `showPath` for better performance ## Future Enhancements The system is designed to be extensible: 1. **Combat Stats**: Add health, damage, experience to AIAgent 2. **Combat System**: Agents can engage enemies 3. **Different Behavior Types**: Scouts move faster, Warriors are stronger, etc. 4. **Persistence**: Save agent progress and continue sessions 5. **Multiplayer**: Display other players' agents 6. **Advanced AI**: Learning from explored areas, tactical decisions ## Troubleshooting ### Agents not spawning? - Check `spawnAIAgents` is enabled on MazeController - Verify `initialAgentCount` > 0 - Check console for errors ### Agents moving too slow/fast? - Adjust `movementSpeed` on AIAgent or prefab ### Agents not exploring? - Verify maze has multiple rooms (check room count in console) - Check that exit points are properly set up ### UI not showing? - Check TextMeshPro is imported in project - Or disable `autoCreateUI` and assign UI elements manually ## API Reference ### AIAgent ```csharp public class AIAgent : MonoBehaviour { public int AgentId { get; } public string CharacterType { get; } public Vector2Int CurrentRoom { get; } public AIRoomMemory RoomMemory { get; } } ``` ### AIAgentManager ```csharp public class AIAgentManager : MonoBehaviour { public AIAgent SpawnAgent(); public void SpawnAgents(int count); public void RemoveAgent(AIAgent agent); public List GetActiveAgents(); public List GetAgentsByType(string characterType); public int GetAgentCount(); public int GetAgentCountByType(string characterType); public void ClearAllAgents(); public void ResetForNewMaze(); public string GetAgentStats(); public int InitialAgentCount { get; } public void SetInitialAgentCount(int count); } ``` ### AIRoomMemory ```csharp public class AIRoomMemory { public void VisitRoom(int roomId); public bool HasVisited(int roomId); public HashSet GetVisitedRooms(); public List FilterUnvisitedRooms(List rooms); public string CharacterType { get; } public int VisitedCount { get; } } ``` ### AIRoomMemoryManager ```csharp public class AIRoomMemoryManager : MonoBehaviour { public static AIRoomMemory GetMemory(string characterType); public static void ClearMemory(string characterType); public static void ClearAllMemories(); } ``` --- **Happy maze exploring!** 🎮