Program.cs 10 KB

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