Program.cs 10 KB

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