13_arcade.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #!/usr/bin/env python3
  2. import sys
  3. from itertools import islice
  4. from time import sleep
  5. from intcode import read_program, run
  6. def makegrid(game):
  7. x, y, ident = islice(game, 3)
  8. coords = []
  9. while x != -1:
  10. coords.append((x, y, ident))
  11. x, y, ident = islice(game, 3)
  12. score = ident
  13. width = max(x for x, y, ident in coords) + 1
  14. height = max(y for x, y, ident in coords) + 1
  15. grid = [[0] * width for y in range(height)]
  16. for x, y, ident in coords:
  17. grid[y][x] = ident
  18. return grid, score
  19. def draw(grid, score):
  20. print('\033c', end='')
  21. for row in grid:
  22. print(''.join(' @x_o'[c] for c in row))
  23. print('score:', score)
  24. def play(code, verbose):
  25. game = run(code, lambda: xball - xpaddle, 1000)
  26. grid, score = makegrid(game)
  27. xpaddle = xball = 0
  28. if verbose:
  29. draw(grid, score)
  30. try:
  31. while True:
  32. x, y, ident = islice(game, 3)
  33. if x == -1:
  34. score = ident
  35. else:
  36. grid[y][x] = ident
  37. if ident == 3:
  38. xpaddle = x
  39. elif ident == 4:
  40. xball = x
  41. if verbose:
  42. draw(grid, score)
  43. sleep(.003)
  44. except (StopIteration, ValueError):
  45. return score
  46. # part 1
  47. code = read_program(sys.stdin)
  48. outp = list(run(code, lambda: 0, 1000))
  49. print(outp[2::3].count(2))
  50. # part 2
  51. code[0] = 2
  52. print(play(code, '-v' in sys.argv))