def _run_program(robot, program): computer = Computer(program) computer.write(robot.camera()) while not computer.is_halted: computer.step() if computer.num_outputs == 2: robot.paint(computer.read()) robot.move(computer.read()) computer.write(robot.camera())
def _run_assembler(program, assembler): computer = Computer(program) while not computer.needs_input: computer.step() computer.print_ascii() computer.write_ascii(assembler) while not computer.is_halted: computer.step() return computer.print_ascii()
def animate(self, program, robot): """ Animate the routine """ labels = self._animation_labels(robot) program = program.copy() program[0] = 2 computer = Computer(program) while not computer.needs_input: computer.step() for char in "".join(self) + "y\n": computer.write(ord(char)) gk.start() rows = 37 cols = 45 grid = gk.create_grid(rows, cols, "Vacuum Robot") grid.map_color('.', gk.Colors.Navy) grid.map_color('#', gk.Colors.Gray) grid.map_color('A', gk.Colors.Red) grid.map_color('B', gk.Colors.Green) grid.map_color('C', gk.Colors.Blue) lines = [[' '] * cols for _ in range(rows)] row = 0 col = 0 frame = -2 input("Press enter to begin animation...") while not computer.is_halted: while not computer.num_outputs: computer.step() val = computer.read() if val < 255: if val == ord('\n'): if col: row += 1 col = 0 else: self.draw(grid, lines, labels, frame) row = 0 col = 0 frame += 1 else: lines[row][col] = chr(val) col += 1 self.draw(grid, lines, labels, frame) gk.stop()
def solve(d): size = 1000 hit = set() extremes = [[0, 0] for _ in range(size)] # seen_wide = False # wide_width = 200 for y in range(size): for x in range(y, 2 * y): computer = Computer(d, x) while True: retcode, retval = computer.step() if retcode == 0 and retval == 3: computer.set_input(y) break retcode, retval = computer.get_output() if retval == 1: # if (y, x - wide_width) in hit: # seen_wide = True hit.add((y, x)) # if seen_wide and (y - 99) in hit: if (y - 99, x + 99) in hit: return 10000 * x + y - 99 if extremes[y][0] == 0: extremes[y][0] = x if (y - 99, x + 99) in hit: print(y, x) extremes[y][1] = x return len(hit)
def solve(data, inp): painted = defaultdict(int) y = 0 x = 0 output_count = 0 directions = ((-1, 0), (0, 1), (1, 0), (0, -1)) facing = 0 computer = Computer(data, inp) retval, retcode = 0, 0 while retcode != -1: retcode, retval = computer.step() if retcode == 0: computer.set_input(painted[(y, x)]) continue if output_count % 2 == 0: painted[(y, x)] = retval else: if retval == 0: facing = (facing - 1) % 4 else: facing = (facing + 1) % 4 y += directions[facing][0] x += directions[facing][1] computer.set_input(painted[(y, x)]) output_count += 1 return len(painted)
def solve(d): inp = """OR E J OR H J AND D J OR A T AND B T AND C T NOT T T AND T J RUN """ p = 0 steps = 0 computer = Computer(d, ord(inp[p])) while True: steps += 1 retcode, retval = computer.step() if retcode == -1: break if retcode == 0 and retval == 3: p += 1 if p < len(inp): computer.set_input(ord(inp[p])) if retcode == 1 and retval > 255: return retval return steps
def solve(d): items, paths = get_data() program = get_program() computer = Computer(d, ord(program[0])) p = 1 while True: retcode, retval = computer.step() if retcode == 1: print(chr(retval), end='') if (chr(retval)) == '?': print('') inp = input() + '\n' if not program: program = inp computer.set_input(ord(program[0])) p = 1 elif retcode == 0 and retval == 3: if p < len(program): computer.set_input(ord(program[p])) p += 1 else: program = '' elif retcode == -1: return
def run(value): output = [] cpu = Computer(opcodes) cpu.receive_input(value) while not cpu.halted: out = cpu.step() if out != None: output.append(out) return output
def _ascii(program): computer = Computer(program) last = None output = StringIO() while not computer.is_halted: while not computer.num_outputs: computer.step() tile = chr(computer.read()) if last == tile == '\n': break last = tile output.write(tile) sys.stdout.write(tile) return output.getvalue()
def _main(): with open(asset("day25.txt")) as file: program = [int(part) for part in file.read().split(',')] computer = Computer(program) commands = [ "south", "take mouse", "north", "west", "north", "north", "north", "west", "take semiconductor", "east", "south", "west", "south", "take hypercube", "north", "east", "south", "west", "take antenna", "west", "south", "south", "south" ] computer.write_ascii("\n".join(commands) + '\n') while not computer.is_halted: while not computer.num_outputs and not computer.is_halted: computer.step() if computer.num_outputs: computer.print_ascii()
def _run_program_animated(robot, program): grid = gk.create_grid(6, 43, "Painting Robot") gk.start() computer = Computer(program) computer.write(robot.camera()) _draw(grid, robot) input("Press enter to begin...") while not computer.is_halted: computer.step() if computer.num_outputs == 2: robot.paint(computer.read()) robot.move(computer.read()) computer.write(robot.camera()) _draw(grid, robot) gk.next_frame() input("Press any key to finish...") gk.stop()
def run(self, program): """ Run the movement routine on the robot """ program = program.copy() program[0] = 2 computer = Computer(program) while not computer.needs_input: computer.step() for char in "".join(self) + "n\n": computer.write(ord(char)) val = None while not computer.is_halted: while not computer.num_outputs: computer.step() val = computer.read() if val < 255: sys.stdout.write(chr(val)) return val
def solve(d): exploreputer = Computer(d, 1) grid, height, width = get_grid(exploreputer) moves = get_moves(grid, height, width) movement, funca, funcb, funcc = programify(infuse_numbers(moves)) inputs = [] for c in movement: inputs.append(ord(c)) inputs.append(10) for c in funca: inputs.append(ord(c)) inputs.append(10) for c in funcb: inputs.append(ord(c)) inputs.append(10) for c in funcc: inputs.append(ord(c)) inputs.append(10) inputs.append(ord('n')) inputs.append(10) moveputer = Computer(d, inputs[0], 2) inppos = 1 retcode, retval = 0, 0 dust = 0 while retcode != -1: retcode, retval = moveputer.step() if retcode == 0 and retval == 3: if inppos < len(inputs): moveputer.set_input(inputs[inppos]) inppos += 1 if retcode == 1: dust = retval return dust
class NetworkComputer: def __init__(self, address: int, memory: List[int]): self.address = address self.computer = Computer(memory) self.input_buffer = [address] def _input_func(self) -> int: if self.input_buffer: return self.input_buffer.pop(0) else: return -1 def _step_computer(self) -> Optional[int]: return self.computer.step(self._input_func) def _get_next_output(self) -> int: while (output := self._step_computer()) is None: pass return output
def solve(d): count = 0 for x in range(50): for y in range(50): computer = Computer(d, x) while True: retcode, retval = computer.step() if retcode == 0 and retval == 3: computer.set_input(y) break retcode, retval = computer.get_output() if retval == 1: count += 1 return count
class Robot: def __init__(self, pos, opcodes): self.cpu = Computer(opcodes) self.pos = pos self.dir = (0, 1) def move(self): self.pos = self.pos[0] + self.dir[0], self.pos[1] + self.dir[1] def turn_right(self): self.dir = self.dir[1], -1 * self.dir[0] def turn_left(self): self.dir = -1 * self.dir[1], self.dir[0] def run(self): while not self.cpu.halted: out = self.cpu.step() if out != None: return out
def solve(d): computer = Computer(d, 0, 2) count = 0 retcode = 0 loops = 0 lowest = 100 highest = -100 out = [-1, -1, -1] score = 0 ballx = 0 padx = 0 cells = {} while retcode != -1: retcode, retval = computer.step() if retcode != 1: continue if out[:2] == [-1, 0] and loops % 3 == 2: score = retval else: out[loops % 3] = retval if loops % 3 == 2: cells[(out[1], out[0])] = out[2] if retval == 3: padx = out[0] if retval == 4: ballx = out[0] else: lowest = min(lowest, retval) highest = max(highest, retval) computer.set_input(0 if ballx == padx else -1 if ballx < padx else 1) loops += 1 return score
def tilex(t): for row in screen: for x, tile in enumerate(row): if tile == t: return x return 0 # part one cpu = Computer(opcodes[:]) screen = [[0] * 50 for _ in range(30)] outs = [] while not cpu.halted: out = cpu.step() if out != None: outs.append(out) if len(outs) == 3: x, y, tile_id = outs if x == None: break screen[y][x] = tile_id outs = [] print(sum([row.count(2) for row in screen])) # part two opcodes[0] = 2 cpu = Computer(opcodes[:]) screen = [[0] * 50 for _ in range(30)] score = 0
class RepairDrone: """ Represents the repair drone """ def __init__(self, program, move_cb=None): self._cpu = Computer(program) self.location = Vector(0, 0) self._empty = set() self._walls = set() self._oxygen_system = None self._move_cb = move_cb def explore(self): """ Explore the sector. Returns: a sector map """ locs = [self.location] iteration = 0 self._walls = set() self._empty = set() self._oxygen_system = None while locs: loc = locs.pop() iteration += 1 if loc in self._walls or loc in self._empty: continue if iteration % 100 == 0: print("robot at", loc, len(locs), len(self._walls)) status = self.move_to(loc) if status == Status.Wall: self._walls.add(loc) continue assert self.location == loc if status == Status.OxygenSystem: print(loc, "is the oxygen system") self._oxygen_system = loc self._empty.add(loc) locs.extend(loc.neighbors()) return Sector(self._walls, self._empty, self._oxygen_system) def move(self, direction): """ Move the drone in the specified direction """ self.location += direction if self._move_cb: self._move_cb(self.location, self._walls, self._empty, self._oxygen_system) def find_shortest_path(self, location): """ Find the shortest path to a location """ start = self.location goal = location return a_star(start, goal, Neighbors(self._empty | {location})) def move_to(self, location): """ Move to the specified location """ if (location - self.location).length == 1: commands = [_to_command(location - self.location)] else: path = self.find_shortest_path(location) commands = [ _to_command(pos1 - pos0) for pos0, pos1 in zip(path[:-1], path[1:]) ] status = Status.Empty for command in commands: while not self._cpu.needs_input: self._cpu.step() self._cpu.write(command) while not self._cpu.num_outputs: self._cpu.step() status = self._cpu.read() if status != Status.Wall: self.move(Directions[command - 1]) return Status(status)
elif tile == 3: ch = '-' elif tile == 4: ch = 'o' print(ch, end='') print('\n', end='') # Mission 1: Get block tiles when game exits intcode = [int(token) for token in tokens] arcade = Computer(intcode) game = {} status = 'ok' while status != 'halt': status = arcade.step() if len(arcade.outputs) == 3: game[(arcade.outputs[0], arcade.outputs[1])] = arcade.outputs[2] arcade.outputs = [] print(sum(tiles == 2 for coord, tiles in game.items())) print_game(game) # Mission 2: Find score after breaking the last block # Game did not run because I didn't put in any quarters - Set memory address 0 to 2 to play for free # Input instruction to joy stick # - neutral position, provide 0 # - tilted to the left provide -1 # - tilted to the right provide 1 # Segment display single number for player's current score