15_goblins.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. #!/usr/bin/env python3
  2. import sys
  3. from operator import attrgetter
  4. from heapq import heappush, heappop
  5. SPACE, WALL = 0, 1
  6. GOBLINS, ELVES = 0, 1
  7. class Unit:
  8. counts = [0, 0]
  9. def __init__(self, pos, team, ap):
  10. self.pos = pos
  11. self.team = team
  12. self.hp = 200
  13. self.ap = ap
  14. self.counts[team] += 1
  15. def neighbouring_enemies(self):
  16. for nb in (self.pos - w, self.pos - 1, self.pos + 1, self.pos + w):
  17. u = grid[nb]
  18. if u not in (SPACE, WALL) and u.team != self.team and u.hp > 0:
  19. yield u
  20. def hit(self, ap):
  21. self.hp -= ap
  22. if self.hp <= 0:
  23. grid[self.pos] = SPACE
  24. self.counts[self.team] -= 1
  25. if self.counts[self.team] == 0:
  26. raise BattleLost(self.team)
  27. def fight(self):
  28. enemies = list(self.neighbouring_enemies())
  29. if enemies:
  30. min(enemies, key=attrgetter('hp', 'pos')).hit(self.ap)
  31. return len(enemies) > 0
  32. def move(self):
  33. step = self.step_to_nearest_enemy()
  34. if step is None:
  35. return False
  36. grid[self.pos] = SPACE
  37. grid[step] = self
  38. self.pos = step
  39. return True
  40. def step_to_nearest_enemy(self):
  41. inf = len(grid) + 1
  42. source = self.pos
  43. Q = [(0, source)]
  44. for v, cell in enumerate(grid):
  45. if v != source:
  46. if cell == SPACE:
  47. heappush(Q, (inf, v))
  48. size = max(v for d, v in Q) + 1
  49. dist = [inf] * size
  50. dist[source] = 0
  51. prev = [None] * size
  52. while Q:
  53. udist, u = heappop(Q)
  54. if udist == dist[u]:
  55. for v in (u - w, u - 1, u + 1, u + w):
  56. if grid[v] == SPACE:
  57. alt = udist + 1
  58. if alt < dist[v]:
  59. dist[v] = alt
  60. prev[v] = u
  61. heappush(Q, (alt, v))
  62. def adjacent_enemies(v):
  63. if dist[v] < inf and grid[v] == SPACE:
  64. for nb in (v - w, v - 1, v + 1, v + w):
  65. u = grid[nb]
  66. if u not in (WALL, SPACE) and u.team != self.team and u.hp > 0:
  67. yield u
  68. shortest = {}
  69. for v, d in enumerate(dist):
  70. for u in adjacent_enemies(v):
  71. step = v
  72. pathlen = 1
  73. while prev[step] != source:
  74. step = prev[step]
  75. pathlen += 1
  76. entry = pathlen, v, step
  77. if u not in shortest or entry < shortest[u]:
  78. shortest[u] = entry
  79. if len(shortest):
  80. return min(shortest.values())[-1]
  81. class BattleLost(Exception):
  82. def __init__(self, team):
  83. self.team = team
  84. def parse(f):
  85. grid = []
  86. w = 0
  87. for y, line in enumerate(f):
  88. for x, c in enumerate(line.rstrip()):
  89. if c == '#':
  90. grid.append(WALL)
  91. elif c in '.':
  92. grid.append(SPACE)
  93. else:
  94. grid.append(Unit(y * w + x, ELVES if c == 'E' else GOBLINS, 3))
  95. w = x + 1
  96. return grid, w
  97. def show():
  98. def red(text):
  99. return '\x1b[31m' + text + '\x1b[0m'
  100. def green(text):
  101. return '\x1b[32m' + text + '\x1b[0m'
  102. h = len(grid) // w
  103. for y in range(h):
  104. line = ''
  105. hps = []
  106. for x in range(w):
  107. cell = grid[y * w + x]
  108. if cell not in (WALL, SPACE):
  109. t = green('E') if cell.team == ELVES else red('G')
  110. hps.append('%s(%d)' % (t, cell.hp))
  111. line += t
  112. else:
  113. line += '#' if cell == WALL else ' '
  114. if hps:
  115. line += ' ' + ', '.join(hps)
  116. print(line)
  117. def simulate(ap, verbose):
  118. global units
  119. rounds = 0
  120. clear = '\033c'
  121. try:
  122. if verbose:
  123. print(clear + 'after 0 rounds with', ap, 'ap:')
  124. show()
  125. while True:
  126. for unit in units:
  127. if unit.hp > 0 and not unit.fight() and unit.move():
  128. unit.fight()
  129. units = sorted((u for u in units if u.hp > 0), key=attrgetter('pos'))
  130. rounds += 1
  131. if verbose:
  132. print(clear + 'after', rounds, 'rounds with', ap, 'ap:')
  133. show()
  134. except BattleLost as lost:
  135. if verbose:
  136. print(clear + 'after', rounds, 'rounds with', ap, 'ap:')
  137. show()
  138. return lost.team, rounds, sum(u.hp for u in units if u.hp > 0)
  139. def reset(elf_ap):
  140. Unit.counts = [0, 0]
  141. grid = []
  142. units = []
  143. for i, cell in enumerate(startgrid):
  144. if cell in (SPACE, WALL):
  145. grid.append(cell)
  146. else:
  147. unit = Unit(i, cell.team, elf_ap if cell.team == ELVES else 3)
  148. grid.append(unit)
  149. units.append(unit)
  150. return grid, units
  151. def report(loser, rounds, hp, ap):
  152. print('Combat ends after', rounds, 'full rounds with', ap, 'attack power:')
  153. winner = 'Goblins' if loser == ELVES else 'Elves'
  154. print(winner, 'win with', hp, 'hit points left')
  155. print('Outcome:', rounds, '*', hp, '=', rounds * hp)
  156. # part 1
  157. elf_ap = 3
  158. verbose = len(sys.argv) == 2 and sys.argv[-1] == '-v'
  159. startgrid, w = parse(sys.stdin)
  160. grid, units = reset(elf_ap)
  161. startelves = sum(1 for u in units if u.team == ELVES)
  162. outcome = outcome3 = simulate(elf_ap, verbose)
  163. # part 2
  164. numelves = 0
  165. while numelves != startelves:
  166. elf_ap += 1
  167. grid, units = reset(elf_ap)
  168. outcome = simulate(elf_ap, verbose)
  169. numelves = sum(1 for u in units if u.team == ELVES)
  170. report(*outcome3, 3)
  171. print()
  172. print('Elves need', elf_ap, 'attack power not to let any elf die:')
  173. report(*outcome, elf_ap)