15_goblins.py 5.4 KB

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