Program.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. namespace D15._1
  6. {
  7. abstract class Unit
  8. {
  9. public int HP = 200;
  10. public int Atk = 3;
  11. public (int X, int Y) Coord;
  12. public bool IsHealthy = true;
  13. public void Move((int mx, int my) mv) => Coord = (Coord.X + mv.mx, Coord.Y + mv.my);
  14. public void Attack(Unit target)
  15. {
  16. target.ReceiveAttack(Atk);
  17. }
  18. private void ReceiveAttack(int atk)
  19. {
  20. HP -= atk;
  21. if (HP <= 0) IsHealthy = false;
  22. }
  23. }
  24. class Gob : Unit { }
  25. class Elf : Unit { }
  26. class Map : HashSet<(int x, int y)> { }
  27. class Units : List<Unit> { }
  28. class Program
  29. {
  30. static readonly (int mx, int my)[] MoveSequence = new [] { (0, -1), (-1, 0), (1, 0), (0, 1) };
  31. static int round = 0;
  32. static void Main(string[] args)
  33. {
  34. if (args.Length < 1) return;
  35. if (File.Exists(args[0]) == false) return;
  36. var file = File.OpenText(args[0]);
  37. var map = new Map();
  38. var strMap = new List<string>();
  39. var units = new Units();
  40. FillMap(file, map, strMap, units);
  41. PrintMap(map, strMap, units);
  42. bool continueCombat = true;
  43. do
  44. {
  45. Console.WriteLine($"Playing round {round + 1}");
  46. continueCombat = Tick(map, units);
  47. if (continueCombat) round++;
  48. PrintMap(map, strMap, units);
  49. } while (continueCombat);
  50. TheAnswerIs(units, round);
  51. }
  52. private static void PrintMap(Map map, List<string> strMap, Units units)
  53. {
  54. for (int y = 0; y < strMap.Count; ++y)
  55. {
  56. var line = strMap[y];
  57. List<Unit> ul = new List<Unit>();
  58. for (var x = 0; x < line.Length; ++x)
  59. {
  60. if (!map.Contains((x, y)))
  61. Console.Write("#");
  62. else
  63. {
  64. var u = units.FirstOrDefault(un => un.Coord == (x, y));
  65. if (u?.IsHealthy == false) u = null;
  66. if (u != null) ul.Add(u);
  67. if (u != null && u is Gob) Console.Write("G");
  68. else if (u != null && u is Elf) Console.Write("E");
  69. else Console.Write(".");
  70. }
  71. }
  72. if (ul.Count > 0)
  73. Console.Write($"\t{ string.Join(", ", ul.Select(u => $"{ (u is Gob ? 'G' : 'E') }({u.HP})")) }");
  74. Console.WriteLine();
  75. }
  76. }
  77. private static void TheAnswerIs(Units units, int round)
  78. {
  79. var hitPoints = 0;
  80. foreach (var unit in units)
  81. {
  82. Console.WriteLine($"Fighter {unit.GetType().Name} : { (unit.IsHealthy ? $"{unit.HP}HP" : $" - DEAD - ({unit.HP})") }");
  83. if (unit.IsHealthy) hitPoints += unit.HP;
  84. }
  85. Console.WriteLine($"\nCombat ends after { round } rounds with { hitPoints } remaining HP");
  86. Console.WriteLine($"The answer is : { hitPoints * round }\n");
  87. }
  88. private static bool Tick(Map map, Units units)
  89. {
  90. units.Sort((a, b) =>
  91. {
  92. if (a.Coord.Y == b.Coord.Y) return a.Coord.X - b.Coord.X;
  93. return a.Coord.Y - b.Coord.Y;
  94. });
  95. for (int i = 0; i < units.Count; ++i)
  96. {
  97. var unit = units[i];
  98. if (unit.IsHealthy == false) continue;
  99. List<Unit> filtered = FilterOnHealthyFoes(units, unit);
  100. if (filtered == null || filtered.Count == 0) return false;
  101. var inRange = new Map();
  102. var inRangeActions = new Dictionary<(int x, int y), List<(int x, int y)>>();
  103. var unitNeedsToMove = GetTilesInRange(map, inRange, unit, filtered);
  104. if (unitNeedsToMove)
  105. MoveUnit(map, units, unit, inRange, inRangeActions);
  106. var targetHasDied = AttackNearestTarget(unit, filtered);
  107. // If last target has died we end up the simulation
  108. if (targetHasDied && filtered.Count == 1)
  109. {
  110. bool isFullRound = true;
  111. for (var j = i + 1; j < units.Count; ++j)
  112. {
  113. if (units[j].IsHealthy == false) continue;
  114. isFullRound = false;
  115. break;
  116. }
  117. return isFullRound;
  118. }
  119. }
  120. return true;
  121. }
  122. private static bool AttackNearestTarget(Unit unit, List<Unit> filtered)
  123. {
  124. var target = GetTarget(unit, filtered);
  125. if (target != null)
  126. {
  127. unit.Attack(target);
  128. if (target.IsHealthy == false)
  129. return true;
  130. }
  131. return false;
  132. }
  133. private static Unit GetTarget(Unit unit, List<Unit> filtered)
  134. {
  135. Unit minHpTarget = null;
  136. foreach (var mv in MoveSequence)
  137. {
  138. (int x, int y) targetc = (unit.Coord.X + mv.mx, unit.Coord.Y + mv.my);
  139. var target = filtered.FirstOrDefault(f => f.Coord == targetc);
  140. if (target != default && (minHpTarget == null || target.HP < minHpTarget.HP))
  141. minHpTarget = target;
  142. }
  143. return minHpTarget;
  144. }
  145. private static void MoveUnit(Map map, Units units, Unit unit, Map inRange, Dictionary<(int x, int y), List<(int x, int y)>> inRangeActions)
  146. {
  147. foreach (var r in inRange)
  148. GetBreadthFirstSearch(unit, map, units, inRangeActions, r);
  149. if (inRangeActions.Count == 0)
  150. return;
  151. var shortest = inRangeActions
  152. .OrderBy(ir => ir.Value.Count)
  153. .FirstOrDefault();
  154. unit.Move(shortest.Value.First());
  155. }
  156. // https://en.wikipedia.org/wiki/Breadth-first_search
  157. private static void GetBreadthFirstSearch(Unit unit, Map map, Units units, Dictionary<(int x, int y), List<(int x, int y)>> inRangeActions, (int x, int y) root)
  158. {
  159. var nodesToVisit = new Queue<(int x, int y)>();
  160. var visitedNodes = new HashSet<(int x, int y)>();
  161. var meta = new Dictionary<(int x, int y), (int x, int y)>()
  162. {
  163. { unit.Coord, (0, 0) }
  164. };
  165. nodesToVisit.Enqueue(unit.Coord);
  166. while (nodesToVisit.Count > 0)
  167. {
  168. var node = nodesToVisit.Dequeue();
  169. // Found it!
  170. if (node == root)
  171. {
  172. GetActionList(inRangeActions, root, meta, node);
  173. break;
  174. }
  175. foreach (var mv in MoveSequence)
  176. {
  177. (int x, int y) successor = (node.x + mv.mx, node.y + mv.my);
  178. // Continue if successor is not a valid tile
  179. if (map.Contains(successor) == false) continue;
  180. if (units.FirstOrDefault(u => u.IsHealthy && u.Coord == successor) != default) continue;
  181. if (visitedNodes.Contains(successor)) continue;
  182. if (nodesToVisit.Contains(successor) == false)
  183. {
  184. meta.TryAdd(successor, mv);
  185. nodesToVisit.Enqueue(successor);
  186. }
  187. }
  188. visitedNodes.Add(node);
  189. }
  190. }
  191. private static void GetActionList(Dictionary<(int x, int y), List<(int x, int y)>> inRangeActions, (int x, int y) root, Dictionary<(int x, int y), (int x, int y)> meta, (int x, int y) node)
  192. {
  193. var actionList = new List<(int x, int y)>();
  194. while (meta[node] != (0, 0))
  195. {
  196. var action = meta[node];
  197. node = (node.x - action.x, node.y - action.y);
  198. actionList.Add(action);
  199. }
  200. actionList.Reverse();
  201. inRangeActions.Add(root, actionList);
  202. }
  203. private static bool GetTilesInRange(Map map, Map inRange, Unit unit, List<Unit> filtered)
  204. {
  205. foreach (var foe in filtered)
  206. {
  207. foreach (var move in MoveSequence)
  208. {
  209. (int x, int y) nc = (foe.Coord.X + move.mx, foe.Coord.Y + move.my);
  210. // Unit has no need to move
  211. if (nc.x == unit.Coord.X && nc.y == unit.Coord.Y)
  212. return false;
  213. if (map.Contains(nc))
  214. inRange.Add(nc);
  215. }
  216. }
  217. return inRange.Count > 0;
  218. }
  219. private static List<Unit> FilterOnHealthyFoes(Units units, Unit unit)
  220. {
  221. List<Unit> filtered = null;
  222. switch (unit)
  223. {
  224. case var un when un is Gob: filtered = units.Where(u => u is Elf && u.IsHealthy).ToList(); break;
  225. case var un when un is Elf: filtered = units.Where(u => u is Gob && u.IsHealthy).ToList(); break;
  226. }
  227. return filtered;
  228. }
  229. private static void FillMap(StreamReader file, Map map, List<string> strMap, Units units)
  230. {
  231. int y = 0;
  232. do
  233. {
  234. var line = file.ReadLine();
  235. if (line == null) break;
  236. strMap.Add(line);
  237. for (int x = 0; x < line.Length; ++x)
  238. {
  239. (int x, int y) coord = (x, y);
  240. if (line[x] == 'G') units.Add(new Gob() { Coord = coord });
  241. if (line[x] == 'E') units.Add(new Elf() { Coord = coord });
  242. if (line[x] != '#') map.Add(coord);
  243. }
  244. y++;
  245. } while (true);
  246. }
  247. }
  248. }