Пример #1
0
def run_intcode(inputfile, noun=None, verb=None):
    """Runs the Intcode provided in inputfile

    Parameters
    ----------
    inputfile : str
        Name/path of file that contains the puzzle input

    noun : int
        Fixed value to put into memory[1]

    verb : int
        Fixed value to put into memory[2]
    """

    memory = IntcodeVM.read_intcode(inputfile)

    if noun is not None:
        memory[1] = noun
    if verb is not None:
        memory[2] = verb

    machine = IntcodeVM(memory)
    machine.run()
    return machine
Пример #2
0
def move_robot(inputfile, moves, screen):
    source = IntcodeVM.read_intcode(inputfile)
    drawer = GridDrawer(screen)
    source[0] = 2
    machine = IntcodeVM(source, silent=True, output_func=drawer.add_output)
    outputs = machine.run(moves)
    sleep(2)
    return outputs.pop()
Пример #3
0
def play_game(inputfile, screen):
    source = IntcodeVM.read_intcode(inputfile)

    # Insert coin...
    source[0] = 2

    # Boot up arcade machine
    machine = IntcodeVM(source, silent=True)
    grid = {}
    score = 0
    total_bricks = 0
    max_y = 0
    move = None

    # Game loop
    while machine.waiting:
        if move is None:
            outputs = machine.run()
        else:
            outputs = machine.resume([move])

        for o in range(0, len(outputs), 3):
            x, y, tile = outputs[o:o + 3]
            if x == -1 and y == 0:
                score = tile
            else:
                screen.print_at(SYMBOLS[tile], x * 3, y, COLORS[tile])
                grid[(x, y)] = tile

        if total_bricks == 0:
            total_bricks = sum(1 for pos in grid if grid[pos] == BLOCK)

        if max_y == 0:
            max_y = max(grid.keys())[1]

        screen.print_at(
            "Blocks left: %s / %s     " %
            (sum(1 for pos in grid if grid[pos] == 2), total_bricks), 5,
            max_y + 1)
        screen.print_at("Score: %s" % score, 5, max_y + 2)
        screen.move(0, 0)
        screen.refresh()
        sleep(0.01)

        # Breakout AI!!
        paddle = [key for key in grid if grid[key] == PADDLE][0]
        ball = [key for key in grid if grid[key] == BALL][0]
        if paddle[0] < ball[0]:
            move = 1
        elif paddle[0] > ball[0]:
            move = -1
        else:
            move = 0

    screen.print_at("All done, press ENTER to exit!", 5, max_y // 2)
    screen.refresh()
    input()
Пример #4
0
def one_run(inputfile):
    max_thruster = 0
    code = IntcodeVM.read_intcode(inputfile)
    machine = IntcodeVM(code)
    for phases in permutations([0, 1, 2, 3, 4]):
        last_output = 0
        for phase in phases:
            inputs = [phase, last_output]
            outputs = machine.run(inputs)
            last_output = outputs.pop()
        if last_output > max_thruster:
            max_thruster = last_output

    return max_thruster
Пример #5
0
def create_grid(inputfile):
    source = IntcodeVM.read_intcode(inputfile)
    machine = IntcodeVM(source, silent=True)
    outputs = machine.run()
    grid = []
    line = []

    for output in outputs:
        if output == 10:
            if len(line) > 0:
                grid.append(line)
            line = []
        else:
            line.append(chr(output))

    return grid
Пример #6
0
def maze(screen):
    # Initialise droid
    droid = IntcodeVM(
        IntcodeVM.read_intcode(os.path.join(currentdir, "input.txt")), False,
        True)

    # One run to determine the dimensions of the grid
    droid.run()
    area_map, _ = explore(droid)
    minx = min(pos[0] for pos in area_map)
    maxx = max(pos[0] for pos in area_map)
    miny = min(pos[1] for pos in area_map)
    maxy = max(pos[1] for pos in area_map)
    dimensions = (minx, miny, maxx, maxy)

    # Actual run with visualization
    droid.run()
    area_map, distance_map = explore(droid,
                                     screen=screen,
                                     dimensions=dimensions)
    os_pos = [pos for pos in area_map if area_map[pos] == OS][0]

    # breadth-first algorithm for spreading the oxygen
    frontiers = [os_pos]
    minutes = 0
    while len(frontiers) > 0:
        new_frontiers = []
        for frontier in frontiers:
            for (dx, dy) in DIRECTIONS.values():
                new_frontier = (frontier[0] + dx, frontier[1] + dy)
                if area_map.get(new_frontier, WALL) == FREE:
                    area_map[new_frontier] = OS
                    draw_map(area_map, None, screen, dimensions)
                    new_frontiers.append(new_frontier)

        frontiers = new_frontiers
        if len(frontiers) > 0:
            minutes = minutes + 1

    input()
    print("Part 1: %s" % distance_map[os_pos])
    print("Part 2: %s" % minutes)
Пример #7
0
def feedback_loop(inputfile):
    max_thruster = 0
    code = IntcodeVM.read_intcode(inputfile)
    for phases in permutations([5, 6, 7, 8, 9]):
        done = False

        #Initialise machines
        machines = []
        for phase in phases:
            machine = IntcodeVM(code)
            machine.run([phase])
            machines.append(machine)

        last_output = 0
        while not done:
            for machine in machines:
                last_output = machine.resume([last_output])[-1]
                if not machine.waiting:
                    done = True

        if last_output > max_thruster:
            max_thruster = last_output

    return max_thruster
Пример #8
0
    from lib.intcode import IntcodeVM
except ImportError:
    print("Intcode library could not be found")
    exit(1)


def load_input(filename):
    with open(filename, "r") as file:
        inputs = [int(line) for line in file]

    # Add an extra zero at the end so the Intcode program knows when to stop reading
    inputs.append(0)
    return inputs


code1 = IntcodeVM.read_intcode(os.path.join(currentdir, "01_part1.ic"))
machine = IntcodeVM(code1)

print("Testcases")
outputs = machine.run([12, 0])
assert outputs.pop() == 2
outputs = machine.run([14, 0])
assert outputs.pop() == 2
outputs = machine.run([1969, 0])
assert outputs.pop() == 654
outputs = machine.run([100756, 0])
assert outputs.pop() == 33583


inputs = load_input(os.path.join(currentdir, "testinput.txt"))
outputs = machine.run(inputs)
Пример #9
0
 def test_loading(self):
     """Program should load correctly from input file"""
     program = IntcodeVM.read_intcode(
         os.path.join(currentdir, "testinput1.txt"))
     self.assertListEqual(program,
                          [1, 9, 10, 3, 2, 3, 11, 0, 99, 30, 40, 50])
Пример #10
0
                else:
                    output = computer.resume()

                if len(output) > 0:
                    self.idle[c] = 0
                    self.outputs[c].extend(output)

    def handle_outputs(self):
        for c in range(len(self.computers)):
            if len(self.outputs[c]) < 3:
                continue

            end = (len(self.outputs[c]) // 3) * 3

            for o in range(0, end, 3):
                dest = self.outputs[c][o]
                x = self.outputs[c][o + 1]
                y = self.outputs[c][o + 2]
                if dest == 255:
                    self.nat_package = [x, y]
                else:
                    self.packets[dest].append([x, y])

            self.outputs[c] = self.outputs[c][end:]


source = IntcodeVM.read_intcode(os.path.join(currentdir, "input.txt"))
network = Network(source)
print("Part 1: %s" % network.run())
print("Part 2: %s" % network.run(True))
Пример #11
0
        Path/Filename of Intcode source code

    hull : dict<(int,int): int>
        Initial state of the hull
    """

    robot_pos = (0, 0)
    robot_dir = (0, -1)
    machine = IntcodeVM(inputfile, silent=True)
    machine.run()

    while machine.waiting:
        color, turn = machine.resume([hull.get(robot_pos, BLACK)])
        hull[robot_pos] = color
        robot_dir = TURNS[robot_dir][turn]
        robot_pos = (robot_pos[0] + robot_dir[0], robot_pos[1] + robot_dir[1])

    return hull


hull = paint_hull(IntcodeVM.read_intcode(os.path.join(currentdir,
                                                      "input.txt")))
print("Part 1: %s" % len(hull.keys()))
print_hull(hull)

hull = paint_hull(
    IntcodeVM.read_intcode(os.path.join(currentdir, "input.txt")),
    {(0, 0): WHITE})
print("Part 2:")
print_hull(hull)
Пример #12
0
        for x in range(minx, minx + 5):
            if check_field(machine, x, y):
                startx = x
                minx = x
                break

        if startx is None:
            # No tractor beam in this row
            continue

        x = startx
        while check_row(machine, x, y, size):
            if check_square(machine, x, y, size):
                return (x, y)
            x = x + 1


machine = IntcodeVM(IntcodeVM.read_intcode(
    os.path.join(currentdir, "input.txt")),
                    silent=True)
affected = []
for y in range(50):
    for x in range(50):
        if check_field(machine, x, y):
            affected.append((x, y))

print("Part 1: %s" % len(affected))

x, y = find_square(machine, 100)
print("Part 2: %s" % (x * 10000 + y))