class DroidController: def __init__(self, area): self.location = (0, 0) self.area = area self.cpu = CPU() self.process = Process(Memory(read_program('input.txt'))) self.process.io.wait_input = self.provide_input self.process.io.listeners = [self.handle_output] self.latest_direction = Direction.UP self.location_gen = next_location_generator(self.location, self.area) self.step_count = 0 self.oxygen_system_step_count = 0 def start(self): self.cpu.process(self.process) def provide_input(self): # print(area.get_map_string()) move = next(self.location_gen, 0) self.latest_direction = Direction.get_by_value(move) # print(f'Droid is attempting to move {self.latest_direction}') return move def handle_output(self, value): if value == 0: area.place_wall(self, self.latest_direction) elif value == 1: area.move_droid(self, self.latest_direction) elif value == 2: area.move_droid(self, self.latest_direction) area.place_oxygen_system(self) self.oxygen_system_step_count = droid.step_count
def __init__(self, area): self.location = (0, 0) self.area = area self.cpu = CPU() self.process = Process(Memory(read_program('input.txt'))) self.process.io.wait_input = self.provide_input self.process.io.listeners = [self.handle_output] self.latest_direction = Direction.UP self.location_gen = next_location_generator(self.location, self.area)
def is_intersection(x, y, grid): if grid[y][x] != 35: return False total_neighbours = 0 for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]: try: if grid[y + dy][x + dx] == 35: total_neighbours += 1 except IndexError: pass return total_neighbours >= 3 if __name__ == '__main__': scaffolding = [] cpu = CPU() process = Process(Memory(read_program('input.txt'))) collector = OutputCollector( output_method=OutputCollector.Method.END_INT_EXCLUDE, output_until=10, callback=lambda val: scaffolding.append(val)) collector.attach(process) cpu.process(process) print('\n'.join(''.join(chr(x) for x in sub) for sub in scaffolding)) total_alignment_parameter = 0 for y, row in enumerate(scaffolding): for x, el in enumerate(row): if is_intersection(x, y, scaffolding): total_alignment_parameter += x * y write_output(total_alignment_parameter)
def move(self): self.position = self.direction.move(self.position) def print_matrix(matrix): print('\n'.join(''.join(color.value[1] for color in row) for row in matrix)) def write_output(result, width, height): header = f'P6\n{width} {height}\n255\n' with open('output.ppm', 'wb') as out_file: out_file.write(bytearray(header, 'ascii')) out_file.write(bytearray(result)) if __name__ == '__main__': raw_memory = read_program('input.txt') robot = Robot(raw_memory) cpu = CPU() grid = Grid() robot.run(cpu, grid) matrix = grid.get_color_matrix() color_array = [ color_byte for row in matrix for color in row for color_byte in color.value[2] ] write_output(color_array, len(matrix[0]), len(matrix)) print_matrix(matrix)
def report(self): return (CPU.report(), RAM.report(), VGA.report())