CombatGrid.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. namespace MazeGen
  4. {
  5. /// <summary>
  6. /// Manages the combat grid where combatants are positioned during a fight.
  7. /// Handles placement, collision detection, occupancy tracking, and pathfinding.
  8. /// Grid cells are based on maze room spacing for consistency.
  9. /// </summary>
  10. public class CombatGrid
  11. {
  12. /// <summary>Grid dimensions in squares.</summary>
  13. private Vector2Int _gridSize;
  14. /// <summary>Grid cell size in world units (matches maze room spacing).</summary>
  15. private float _cellSize;
  16. /// <summary>Tracks which combatants occupy each grid position.</summary>
  17. private Dictionary<Vector2Int, List<Combatant>> _occupancy;
  18. /// <summary>All combatants on this grid.</summary>
  19. private List<Combatant> _allCombatants;
  20. /// <summary>
  21. /// Initialize the grid with specified dimensions.
  22. /// Default size is 11x7 squares (standard arena size).
  23. /// </summary>
  24. public CombatGrid(Vector2Int gridSize, float cellSize = 1f)
  25. {
  26. _gridSize = gridSize;
  27. _cellSize = cellSize;
  28. _occupancy = new Dictionary<Vector2Int, List<Combatant>>();
  29. _allCombatants = new List<Combatant>();
  30. // Pre-allocate all cells
  31. for (int x = 0; x < _gridSize.x; x++)
  32. {
  33. for (int y = 0; y < _gridSize.y; y++)
  34. {
  35. Vector2Int pos = new Vector2Int(x, y);
  36. _occupancy[pos] = new List<Combatant>();
  37. }
  38. }
  39. }
  40. public Vector2Int GridSize => _gridSize;
  41. public float CellSize => _cellSize;
  42. /// <summary>
  43. /// Place all combatants on the grid. Agents on left side, monsters on right side.
  44. /// </summary>
  45. public void PlaceAllCombatants(IReadOnlyList<Combatant> combatants)
  46. {
  47. _allCombatants.Clear();
  48. _occupancy.Clear();
  49. // Re-initialize occupancy
  50. for (int x = 0; x < _gridSize.x; x++)
  51. {
  52. for (int y = 0; y < _gridSize.y; y++)
  53. {
  54. Vector2Int pos = new Vector2Int(x, y);
  55. _occupancy[pos] = new List<Combatant>();
  56. }
  57. }
  58. // Separate agents and monsters
  59. var agents = new List<Combatant>();
  60. var monsters = new List<Combatant>();
  61. foreach (var c in combatants)
  62. {
  63. if (c.IsAgent)
  64. agents.Add(c);
  65. else
  66. monsters.Add(c);
  67. }
  68. // Place agents on the left side
  69. PlaceTeam(agents, isAgents: true);
  70. // Place monsters on the right side
  71. PlaceTeam(monsters, isAgents: false);
  72. }
  73. /// <summary>
  74. /// Place a team (agents or monsters) on their respective side of the grid.
  75. /// </summary>
  76. private void PlaceTeam(List<Combatant> team, bool isAgents)
  77. {
  78. if (team.Count == 0) return;
  79. // Calculate starting column and direction
  80. int startColumn = isAgents ? 1 : _gridSize.x - 2;
  81. int columnDirection = isAgents ? 1 : -1;
  82. int combatantsPlaced = 0;
  83. int currentColumn = startColumn;
  84. while (combatantsPlaced < team.Count && currentColumn >= 0 && currentColumn < _gridSize.x)
  85. {
  86. // Try to fill this column from top to bottom
  87. for (int row = 0; row < _gridSize.y && combatantsPlaced < team.Count; row++)
  88. {
  89. Vector2Int position = new Vector2Int(currentColumn, row);
  90. if (IsPositionValid(position, team[combatantsPlaced]))
  91. {
  92. PlaceCombatant(team[combatantsPlaced], position);
  93. combatantsPlaced++;
  94. }
  95. }
  96. currentColumn += columnDirection;
  97. }
  98. // Fallback: if not all placed, fill remaining positions
  99. if (combatantsPlaced < team.Count)
  100. {
  101. for (int x = 0; x < _gridSize.x && combatantsPlaced < team.Count; x++)
  102. {
  103. for (int y = 0; y < _gridSize.y && combatantsPlaced < team.Count; y++)
  104. {
  105. Vector2Int position = new Vector2Int(x, y);
  106. if (_occupancy[position].Count == 0 && IsPositionValid(position, team[combatantsPlaced]))
  107. {
  108. PlaceCombatant(team[combatantsPlaced], position);
  109. combatantsPlaced++;
  110. }
  111. }
  112. }
  113. }
  114. }
  115. /// <summary>
  116. /// Place a single combatant at the specified grid position.
  117. /// Only call after validating with IsPositionValid().
  118. /// </summary>
  119. public void PlaceCombatant(Combatant combatant, Vector2Int position)
  120. {
  121. if (combatant == null) return;
  122. // Remove from old position if already placed
  123. if (_allCombatants.Contains(combatant))
  124. {
  125. foreach (var cellCombatants in _occupancy.Values)
  126. {
  127. cellCombatants.Remove(combatant);
  128. }
  129. }
  130. // Add to new position
  131. combatant.GridPosition = position;
  132. if (!_allCombatants.Contains(combatant))
  133. _allCombatants.Add(combatant);
  134. if (_occupancy.ContainsKey(position))
  135. {
  136. if (!_occupancy[position].Contains(combatant))
  137. _occupancy[position].Add(combatant);
  138. }
  139. }
  140. /// <summary>
  141. /// Check if a position is valid for a combatant to occupy.
  142. /// Considers grid boundaries, size, and occupancy rules.
  143. /// </summary>
  144. public bool IsPositionValid(Vector2Int position, Combatant combatant)
  145. {
  146. if (combatant == null) return false;
  147. // Check grid bounds
  148. if (position.x < 0 || position.x >= _gridSize.x ||
  149. position.y < 0 || position.y >= _gridSize.y)
  150. return false;
  151. // Get the footprint this combatant would occupy
  152. Vector2Int footprint = combatant.GetFootprintSize();
  153. // Check if entire footprint fits in grid
  154. if (position.x + footprint.x > _gridSize.x ||
  155. position.y + footprint.y > _gridSize.y)
  156. return false;
  157. // Check occupancy based on size
  158. if (combatant.Size == MonsterSize.Large)
  159. {
  160. // Large creatures can't share a grid with anything
  161. for (int x = position.x; x < position.x + footprint.x; x++)
  162. {
  163. for (int y = position.y; y < position.y + footprint.y; y++)
  164. {
  165. if (x < 0 || x >= _gridSize.x || y < 0 || y >= _gridSize.y)
  166. return false;
  167. if (_occupancy.ContainsKey(new Vector2Int(x, y)) && _occupancy[new Vector2Int(x, y)].Count > 0)
  168. return false;
  169. }
  170. }
  171. }
  172. else if (combatant.Size == MonsterSize.Medium)
  173. {
  174. // Medium creatures need empty space
  175. if (_occupancy.ContainsKey(position) && _occupancy[position].Count > 0)
  176. return false;
  177. }
  178. else if (combatant.Size == MonsterSize.Small)
  179. {
  180. // Small creatures can stack (up to 4 per square)
  181. if (_occupancy.ContainsKey(position))
  182. {
  183. int creaturesInSquare = 0;
  184. foreach (var c in _occupancy[position])
  185. {
  186. creaturesInSquare += c.Size == MonsterSize.Small ? 1 : 4;
  187. }
  188. if (creaturesInSquare >= 4) return false;
  189. }
  190. }
  191. return true;
  192. }
  193. /// <summary>
  194. /// Try to move a combatant to a new position atomically.
  195. /// Returns true if successful, false if invalid move.
  196. /// </summary>
  197. public bool TryMoveCombatant(Combatant combatant, Vector2Int newPosition)
  198. {
  199. if (!IsPositionValid(newPosition, combatant))
  200. return false;
  201. PlaceCombatant(combatant, newPosition);
  202. return true;
  203. }
  204. /// <summary>
  205. /// Remove a combatant from the grid (e.g., when they die).
  206. /// </summary>
  207. public void RemoveCombatant(Combatant combatant)
  208. {
  209. if (combatant == null) return;
  210. _allCombatants.Remove(combatant);
  211. foreach (var cellCombatants in _occupancy.Values)
  212. {
  213. cellCombatants.Remove(combatant);
  214. }
  215. }
  216. /// <summary>
  217. /// Get all combatants currently on the grid.
  218. /// </summary>
  219. public IReadOnlyList<Combatant> GetAllCombatants() => _allCombatants.AsReadOnly();
  220. /// <summary>
  221. /// Get combatants at a specific grid position.
  222. /// </summary>
  223. public IReadOnlyList<Combatant> GetCombatantsAt(Vector2Int position)
  224. {
  225. if (_occupancy.ContainsKey(position))
  226. return _occupancy[position].AsReadOnly();
  227. return new List<Combatant>().AsReadOnly();
  228. }
  229. /// <summary>
  230. /// Get all reachable positions from a starting position within movement range.
  231. /// Uses BFS (Breadth-First Search) for pathfinding.
  232. /// </summary>
  233. public HashSet<Vector2Int> GetReachablePositions(Combatant actor, int maxMovement)
  234. {
  235. var reachable = new HashSet<Vector2Int>();
  236. var queue = new Queue<(Vector2Int pos, int distance)>();
  237. queue.Enqueue((actor.GridPosition, 0));
  238. reachable.Add(actor.GridPosition);
  239. while (queue.Count > 0)
  240. {
  241. var (currentPos, currentDistance) = queue.Dequeue();
  242. if (currentDistance >= maxMovement)
  243. continue;
  244. // Check all 4 cardinal directions
  245. Vector2Int[] directions = new Vector2Int[]
  246. {
  247. new Vector2Int(1, 0), // Right
  248. new Vector2Int(-1, 0), // Left
  249. new Vector2Int(0, 1), // Up
  250. new Vector2Int(0, -1) // Down
  251. };
  252. foreach (var direction in directions)
  253. {
  254. Vector2Int nextPos = currentPos + direction;
  255. if (!reachable.Contains(nextPos) && IsPositionValid(nextPos, actor))
  256. {
  257. reachable.Add(nextPos);
  258. queue.Enqueue((nextPos, currentDistance + 1));
  259. }
  260. }
  261. }
  262. return reachable;
  263. }
  264. /// <summary>
  265. /// Convert a grid position to world coordinates (for visualization).
  266. /// </summary>
  267. public Vector2 GridToWorldPosition(Vector2Int gridPos)
  268. {
  269. return new Vector2(gridPos.x * _cellSize, gridPos.y * _cellSize);
  270. }
  271. /// <summary>
  272. /// Convert world coordinates to grid position.
  273. /// </summary>
  274. public Vector2Int WorldToGridPosition(Vector2 worldPos)
  275. {
  276. return new Vector2Int(
  277. Mathf.RoundToInt(worldPos.x / _cellSize),
  278. Mathf.RoundToInt(worldPos.y / _cellSize)
  279. );
  280. }
  281. }
  282. }