15_goblins.py 5.5 KB

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