-
Notifications
You must be signed in to change notification settings - Fork 3
/
day13.py
executable file
·110 lines (92 loc) · 2.94 KB
/
day13.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#!/usr/bin/env python
from collections import defaultdict
from os import system
from aoc.computer import Computer
def parse(filename):
with open(filename) as f:
return [int(num) for num in f.readline().strip().split(",")]
class Breakout:
def __init__(self, program_in):
self.program = program_in
self.cpu = Computer(self.program, [])
self.grid = defaultdict(lambda: 0)
def input(self, val):
self.cpu.add_input(val)
def add_quarters(self):
self.cpu.memory[0] = 2
def run_and_return_grid(self):
cpu = self.cpu
self.cpu.memory[0] = 2
grid = self.grid
cpu.execute()
while cpu.has_output():
x = cpu.pop_output()
y = cpu.pop_output()
what = cpu.pop_output()
grid[complex(x, y)] = what
return grid
def is_halted(self):
return self.cpu.is_halted()
def display(self):
system("clear")
for y in range(25):
for x in range(45):
char = self.grid[complex(x, y)]
print_char = " "
if char == 1:
print_char = "W"
elif char == 2:
print_char = "B"
elif char == 3:
print_char = "="
elif char == 4:
print_char = "*"
print(print_char, end="")
print("")
print(f"Score {self.grid[complex(-1, 0)]}")
def score(self):
return self.grid[complex(-1, 0)]
def get_move(self):
grid = self.grid
ball = list(grid.keys())[list(grid.values()).index(4)]
ball_x = int(ball.real)
paddle = list(grid.keys())[list(grid.values()).index(3)]
paddle_x = int(paddle.real)
if ball_x > paddle_x:
return "r"
if ball_x < paddle_x:
return "l"
return "."
@staticmethod
def part1(program_in):
robot = Breakout(program_in)
grid = robot.run_and_return_grid()
return list(grid.values()).count(2)
@staticmethod
def part2(program_in, *, display_to_screen=False):
robot = Breakout(program_in)
grid = robot.run_and_return_grid()
robot.add_quarters()
if display_to_screen:
robot.display()
while True:
a = robot.get_move()
if a == "l":
robot.input(-1)
elif a == "r":
robot.input(1)
else:
robot.input(0)
if robot.is_halted():
break
grid = robot.run_and_return_grid()
if display_to_screen:
robot.display()
return robot.score()
if __name__ == "__main__":
program = parse("../../13/input.txt")
print("Part 1:")
print(Breakout.part1(program))
print("Part 2:")
# print(Breakout.part2(program, display_to_screen=True))
print(Breakout.part2(program))