Esempio n. 1
0
def prints2ascii(prints, prune=True):
    ascii_prints = "".join(map(chr, prints)).split('\n')
    if prune:
        ascii_prints = [row for row in ascii_prints if len(row) > 0]
    return ascii_prints


from intcode import IntCodeComputer

program = list(map(int, open('data/input25').read().strip().split(',')))
computer = IntCodeComputer(program, resume=True)

cmds = """\
east
take manifold
south
take whirled peas
north
west
south
take space heater
south
take dark matter
north
east
north
west
south
take antenna
north
east
Esempio n. 2
0
            if tile[0] == -1:
                score = tile[2]
            if tile[2] == 4:
                ball_pos = tile[-3:]
            if tile[2] == 3:
                paddle_pos = tile[:2]
        except InputInterrupt:
            if show:
                render(tiles)
            c.inputs.append(cmp(ball_pos[0], paddle_pos[0]))

    return score


if __name__ == "__main__":
    program = list(map(int, open('inputs/day13.txt').read().split(',')))

    c = IntCodeComputer(program)

    # part 1
    output = list(chunks(c.run_no_interrupt(), 3))
    tile_counts = Counter([x[2] for x in output])
    print(", ".join(f"{tiles_icons[k]} : {v}" for k, v in tile_counts.items()))

    free_play = [2] + program[1:]
    c = IntCodeComputer(free_play)

    score = play(c)
    print("Final Score: ", score)
Esempio n. 3
0
def main():
    args, file_in = parse_args()
    instructions = np.loadtxt(file_in, delimiter=',', dtype=np.int)
    comp = IntCodeComputer(stdin=iter([2]))
    print(list(comp.run(instructions)))
Esempio n. 4
0
def test_part2():
    comp = IntCodeComputer('input.txt', [])
    bot = PaintBot(comp, initial_color=1)
    bot.build_panels()
    # Identifier is GARPKZUL
    assert bot.render() == '''..##...##..###..###..#..#.####.#..#.#......
Esempio n. 5
0
from intcode import IntCodeComputer
import logging
import sys

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
if __name__ == "__main__":
    p = [
        109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0,
        99
    ]
    c = IntCodeComputer(p)
    assert (c.run_no_interrupt() == p)

    c = IntCodeComputer([1102, 34915192, 34915192, 7, 4, 7, 99, 0])
    assert (len(str(c.run_no_interrupt()[0])) == 16)

    c = IntCodeComputer([104, 1125899906842624, 99])
    assert (c.run_no_interrupt()[0] == 1125899906842624)

    program = list(map(int, open('inputs/day9.txt').read().split(',')))

    logger.info("Running BOOST test mode")
    c = IntCodeComputer(program, [1])
    c.run_no_interrupt()
    print("BOOST Keycode", c.outputs[0])

    logger.info("Running BOOST sensor mode")
    c = IntCodeComputer(program, [2])
    c.run_no_interrupt()
    print("BOOST coordinates", c.outputs[0])
Esempio n. 6
0
class ASCIIBot:
    def __init__(self, instructions):
        self.map = np.zeros((100, 100), dtype=np.int8)
        self.start = (0, 0)  # row, col
        # instructions[0] = 1  # part 1
        instructions[0] = 2  # part 2
        self.input_commands = []
        self.input_commands += self.movement_program()
        self.input_commands += [ord('n'), ord('\n')]
        print(self.input_commands)
        print([chr(x) for x in self.input_commands])
        stdin = patient_generator(self.input_commands)
        self.computer = IntCodeComputer(stdin=stdin, stdout=None)
        self.computer_gen = self.computer.run(instructions)

    def load_camera_image(self):
        row_idx = 0
        col_idx = 0
        max_col = 0
        for pixel_val in self.computer_gen:
            if pixel_val == 10:
                # new line
                row_idx += 1
                col_idx = 0
                continue
            if pixel_val in [ord("<"), ord(">"), ord("v"), ord("^")]:
                # where's the vacuum?
                self.start = (row_idx, col_idx)
            self.map[row_idx, col_idx] = pixel_val
            if col_idx > max_col:
                max_col = col_idx
            col_idx += 1
        self.map = self.map[:row_idx - 1, :max_col + 1]

    def get_intersection_map(self):
        align_map = self.map == 35
        align_map[1:, :] &= self.map[:-1, :] == 35
        align_map[:-1, :] &= self.map[1:, :] == 35
        align_map[:, 1:] &= self.map[:, :-1] == 35
        align_map[:, :-1] &= self.map[:, 1:] == 35
        return align_map

    def __str__(self):
        s = ""
        for row in self.map:
            s += "".join(chr(x) for x in row) + "\n"
        return s

    def movement_program(self):
        main_program = "A,A,B,C,B,C,B,C,A,C\n"
        func_a = """R,6,L,8,R,8\n"""
        func_b = """R,4,R,6,R,6,R,4,R,4\n"""
        func_c = """L,8,R,6,L,10,L,10\n"""
#         total = """
# R,6,L,8,R,8
# R,6,L,8,R,8
#
# R,4,R,6,R,6,R,4,R,4,
# L,8 R,6,L,10,L,10
#
# R,4,R,6,R,6,R,4,R,4,
# L,8,R,6,L,10,L,10
#
# R,4,R,6,R,6,R,4,R,4,
# L,8,R,6,L,10,L,10
#
# R,6,L,8,R,8
#
# L,8,R,6,L,10,L,10"""
        total = []
        def _to_intcode(insts):
            for x in insts:
                yield ord(x)
        total.extend(_to_intcode(main_program))
        total.extend(_to_intcode(func_a))
        total.extend(_to_intcode(func_b))
        total.extend(_to_intcode(func_c))
        return total

    def walk_scaffolding(self):
        curr_row, curr_col = self.start
        move_hor = False  # we check up/down first so False is OK
        while True:
            # we don't know which direction to face
            # and need to turn
            next_row, next_col = curr_row, curr_col
            # up
            if move_hor and curr_row - 1 >= 0 and self.map[curr_row - 1, curr_col] == SCAFF:
                next_row = curr_row - 1
                turn = 'L' if self.map[curr_row, curr_col] == ord('>') else 'R'
                move_hor = False
                movement = -1
            # down
            elif move_hor and curr_row + 1 <= self.map.shape[0] and self.map[curr_row + 1, curr_col] == SCAFF:
                next_row = curr_row + 1
                turn = 'R' if self.map[curr_row, curr_col] == ord('>') else 'L'
                move_hor = False
                movement = 1
            # left
            elif curr_col - 1 >= 0 and self.map[curr_row, curr_col - 1] == SCAFF:
                next_col = curr_col - 1
                turn = 'L' if self.map[curr_row, curr_col] == ord('^') else 'R'
                move_hor = True
                movement = -1
            # right
            elif curr_col + 1 <= self.map.shape[1] and self.map[curr_row, curr_col + 1] == SCAFF:
                next_col = curr_col + 1
                turn = 'R' if self.map[curr_row, curr_col] == ord('^') else 'L'
                move_hor = True
                movement = 1
            else:
                print("WE'RE DONE")
                break

            # how far do we go now
            while (0 <= next_row < self.map.shape[0] and
                   0 <= next_col < self.map.shape[1] and
                   self.map[next_row, next_col] == SCAFF):
                if move_hor:
                    next_col += movement
                else:
                    next_row += movement
            if move_hor:
                next_col -= movement
                count = abs(next_col - curr_col)
            else:
                next_row -= movement
                count = abs(next_row - curr_row)
            print("{},{}".format(turn, count))
            if move_hor:
                self.map[next_row, next_col] = ord("<") if movement < 0 else ord(">")
            else:
                self.map[next_row, next_col] = ord("^") if movement < 0 else ord("v")
            curr_row, curr_col = next_row, next_col
Esempio n. 7
0
from intcode import IntCodeComputer

droidcode = [int(x) for x in open("input.txt", "r").readline().split(",")]
droid = IntCodeComputer(droidcode)


def inputify(lines):
    output = []
    for line in lines:
        for char in line:
            output.append(ord(char))
        output.append(10)

    return output


def outputify(codes):
    output = []
    for char in codes:
        if 0 <= char <= 255:
            output.append(chr(char))
        else:
            output.extend(outputify(inputify([str(char)])))
    return "".join(output)


springcode = [
    "OR E J", "OR H J", "AND D J", "OR C T", "AND B T", "NOT T T", "AND T J",
    "NOT A T", "OR T J", "RUN"
]
Esempio n. 8
0

def parse_result(r):
    out = []
    for v in r[0]:
        try:
            ch = chr(v)
            out.append(ch)
        except:
            print('Big value: ', v)
            continue
    print(r[1])
    print(''.join(out))


pc_1 = IntCodeComputer(source='input', buffered=True)

program_1 = [
    'NOT A T\n',
    'OR T J\n',
    'NOT B T\n',
    'OR T J\n',
    'NOT C T\n',
    'OR T J\n',  # At this point, if A, B, or C is FALSE, J is TRUE.
    'AND D J\n',  # If the destination D is TRUE (safe), jump now.
    'WALK\n',
]

result = pc_1.run()
parse_result(result)
Esempio n. 9
0
def analyze_perm_2(p):
    pcs = [IntCodeComputer(source='input', buffered=True) for _ in range(5)]
    sig = 0
Esempio n. 10
0
from itertools import permutations

from intcode import IntCodeComputer

amp_control = [3,8,1001,8,10,8,105,1,0,0,21,42,51,60,77,94,175,256,337,418,99999,3,9,1001,9,4,9,102,5,9,9,1001,9,3,9,102,5,9,9,4,9,99,3,9,102,2,9,9,4,9,99,3,9,1001,9,3,9,4,9,99,3,9,101,4,9,9,1002,9,4,9,101,5,9,9,4,9,99,3,9,1002,9,5,9,101,3,9,9,102,2,9,9,4,9,99,3,9,1001,9,1,9,4,9,3,9,1002,9,2,9,4,9,3,9,102,2,9,9,4,9,3,9,102,2,9,9,4,9,3,9,102,2,9,9,4,9,3,9,101,2,9,9,4,9,3,9,101,2,9,9,4,9,3,9,101,2,9,9,4,9,3,9,1001,9,1,9,4,9,3,9,101,1,9,9,4,9,99,3,9,1001,9,2,9,4,9,3,9,101,1,9,9,4,9,3,9,102,2,9,9,4,9,3,9,1001,9,1,9,4,9,3,9,101,2,9,9,4,9,3,9,1002,9,2,9,4,9,3,9,1001,9,1,9,4,9,3,9,101,1,9,9,4,9,3,9,1001,9,2,9,4,9,3,9,1002,9,2,9,4,9,99,3,9,101,2,9,9,4,9,3,9,102,2,9,9,4,9,3,9,101,2,9,9,4,9,3,9,102,2,9,9,4,9,3,9,1002,9,2,9,4,9,3,9,102,2,9,9,4,9,3,9,102,2,9,9,4,9,3,9,101,2,9,9,4,9,3,9,1001,9,2,9,4,9,3,9,101,2,9,9,4,9,99,3,9,101,2,9,9,4,9,3,9,1002,9,2,9,4,9,3,9,1001,9,1,9,4,9,3,9,101,1,9,9,4,9,3,9,1001,9,1,9,4,9,3,9,1002,9,2,9,4,9,3,9,1002,9,2,9,4,9,3,9,101,1,9,9,4,9,3,9,102,2,9,9,4,9,3,9,101,2,9,9,4,9,99,3,9,1001,9,2,9,4,9,3,9,101,2,9,9,4,9,3,9,1002,9,2,9,4,9,3,9,101,2,9,9,4,9,3,9,101,2,9,9,4,9,3,9,102,2,9,9,4,9,3,9,1002,9,2,9,4,9,3,9,102,2,9,9,4,9,3,9,1002,9,2,9,4,9,3,9,101,1,9,9,4,9,99]

amp1 = IntCodeComputer(amp_control)
amp2 = IntCodeComputer(amp_control)
amp3 = IntCodeComputer(amp_control)
amp4 = IntCodeComputer(amp_control)
amp5 = IntCodeComputer(amp_control)

maxres = 0
for p1, p2, p3, p4, p5 in permutations([0, 1, 2, 3, 4]):
    amp1 = IntCodeComputer(amp_control)
    result1 = amp1.run([p1, 0])
    amp2 = IntCodeComputer(amp_control)
    result2 = amp2.run([p2, result1[0]])
    amp3 = IntCodeComputer(amp_control)
    result3 = amp3.run([p3, result2[0]])
    amp4 = IntCodeComputer(amp_control)
    result4 = amp4.run([p4, result3[0]])
    amp5 = IntCodeComputer(amp_control)
    result5 = amp5.run([p5, result4[0]])

    if result5[0] > maxres:
        maxres = result5[0]

print(maxres)
Esempio n. 11
0
import numpy as np
from intcode import IntCodeComputer
from collections import defaultdict

moves = {
    0: lambda x: (np.array((1, -1)) * x)[::-1],
    1: lambda x: (np.array((-1, 1)) * x)[::-1]
}

if __name__ == '__main__':
    inputs = open('inputs.txt').read()
    program = [int(i) for i in inputs.split(',')]
    panel_colors = defaultdict(lambda: 0)
    panel_colors[(0, 0)] = 1
    computer = IntCodeComputer(inputs, inputs=[], interactive=True)
    position = np.array((0, 0))
    direction = np.array((0, 1))
    output_list = []
    while not computer.done:
        output = computer.run()
        if output == '_':
            computer.inputs.append(panel_colors[tuple(position)])
        elif isinstance(output, int):
            output_list.append(output)
        else:
            # raise ValueError("Unknown output")
            print(output)
        if len(output_list) == 2:
            panel_colors[tuple(position)] = output_list[0]
            direction = moves[output_list[1]](direction)
            position += direction
Esempio n. 12
0

def convert_to_ascii(s):
    return list(map(ord, list(s)))


def parse_result(r):
    out = []
    for v in r[0]:
        try:
            ch = chr(v)
            out.append(ch)
        except:
            print('Big value: ', v)
            continue
    print(r[1])
    print(''.join(out))


pc = IntCodeComputer(source='input', buffered=True)

result = pc.run()
parse_result(result)

while result[1] == 'PENDING':
    inp_raw = input()
    inp = convert_to_ascii(inp_raw + '\n')
    result = pc.run(inp)
    parse_result(result)

Esempio n. 13
0
from intcode import IntCodeComputer

if __name__ == '__main__':
    with open('inputs.txt') as f:
        inputs = f.read()

    computer = IntCodeComputer(inputs, inputs=[1])
    print(computer.run())
Esempio n. 14
0
from intcode import IntCodeComputer

code = [int(x) for x in open("input.txt", "r").readline().split(",")]

total = 0
for x in range(50):
    for y in range(50):
        droid = IntCodeComputer(code[:])
        values = droid.run([x, y])
        print(x, y, values)
        total += values[-1]

print(total)
Esempio n. 15
0
    def io_put(self) -> Generator[None, PaintColor, None]:
        while True:
            raw_paint_color = yield
            paint_color = PaintColor(raw_paint_color)
            self.grid.set(self.robot.x, self.robot.y, paint_color)
            raw_turn_dir = yield
            if raw_turn_dir == 0:
                self.robot.turn_left()
            elif raw_turn_dir == 1:
                self.robot.turn_right()
            else:
                raise Exception(f"Unknown direction: {raw_turn_dir}")
            self.robot.go_forward()

    def __str__(self):
        return self.grid.render_with_robot(self.robot)


with open('input.txt') as INPUT:
    day11_inputs = [int(i) for i in INPUT.read().split(',')]

grid_and_robot = GridAndRobot()
grid_and_robot.grid.set(0, 0, PaintColor.WHITE)
day11_machine_state = MachineState(day11_inputs, grid_and_robot, grid_and_robot)
day11_computer = IntCodeComputer(day11_machine_state)

try:
    day11_computer.exec_program()
except HaltException:
    print(grid_and_robot)
Esempio n. 16
0
from intcode import IntCodeComputer

# Part 1: (STDIN/STDOUT mode)
pc = IntCodeComputer(source='input')
pc.run()

# Part 1: (Programmatic IO mode)
pc = IntCodeComputer(source='input', buffered=True)
result, flag = pc.run(1)
print(result, flag)

# Part 2: (STDIN/STDOUT mode)
pc = IntCodeComputer(source='input')
pc.run()

# Part 2: (Programmatic IO mode)
pc = IntCodeComputer(source='input', buffered=True)
result, flag = pc.run(5)
print(result, flag)
Esempio n. 17
0
                line.append("*")

        image.append("".join(line))
    return "\n".join(image)


infile = open("input2.txt", "r")
code = [int(x) for x in infile.readline().split(",")]

screen = defaultdict(int)
score = 0
prevballpos = 0
ballpos = 17
balldir = 0
paddlepos = 0
game = IntCodeComputer(code)

while not game.halted:
    print("JOYSTICK POS:", balldir)
    output = game.run([0])

    prevballpos = ballpos
    for x, y, tile in divide_chunks(output, 3):
        if (x, y) == (-1, 0):
            score = tile
        else:
            screen[(x, y)] = tile

        if tile == 4:
            ballpos = x
        elif tile == 3:
Esempio n. 18
0
from intcode import IntCodeComputer
from collections import defaultdict
import sys

code = [int(x) for x in open("input.txt", "r").readline().split(",")]

computers = [IntCodeComputer(code[:]) for _ in range(50)]

switch = defaultdict(list)

nat = (None, None)
prevnat = (None, None)

firstrun = True
while True:
    idle = True
    for compidx, computer in enumerate(computers):
        if firstrun:
            output = computer.run([compidx, -1])
        else:
            output = computer.run(switch[compidx] + [-1])
            switch[compidx] = []

        # print(compidx)
        for i in range(len(output) // 3):
            dest = output[i * 3]
            x = output[i * 3 + 1]
            y = output[i * 3 + 2]

            print("---", compidx, dest, x, y)
class Droid:
    def __init__(self, core, loc):
        self.computer = IntCodeComputer()
        self.computer.load_core(core)
        self.computer.state = ProgramState.running
        self.loc = loc
        self.heading = 4
        self.grid_map = {self.loc: 1}
        # self.headings = list(next_heading[self.heading])

    def move(self):
        self.heading = self.get_next_heading()
        self.computer.set_input_buffer([self.heading])
        while len(self.computer.output_buffer) == 0:
            self.computer.step()
        res = self.computer.output_buffer.pop()

        if res != 0:
            self.loc = new_loc(self.loc, self.heading)
            if res == 2:
                self.grid_map[self.loc] = -2  # Oxygen
            else:
                self.grid_map[self.loc] = self.grid_map.get(self.loc,
                                                            0) + 1  # visited
        else:
            self.grid_map[new_loc(self.loc, self.heading)] = -1  # block

        return res

    def get_next_heading(self):
        new_heading = self.heading

        # Find an uncharted way
        for n in [0, 1, 2, 3]:
            _loc = new_loc(self.loc, new_heading)
            if _loc not in self.grid_map:
                return new_heading
            else:
                new_heading = turn_right[new_heading]

        # Find a free way that we have traveled least
        new_heading = self.heading
        min_trips, min_heading = 10000, new_heading
        for n in [0, 1, 2, 3]:
            _loc = new_loc(self.loc, new_heading)
            if self.grid_map[_loc] != -1:
                if self.grid_map[_loc] < min_trips:
                    min_trips = self.grid_map[_loc]
                    min_heading = new_heading
            new_heading = turn_right[new_heading]

        return min_heading

    def display_map(self):
        legend = {-2: "$", -1: "#", 1: ".", 0: " "}
        extent = [-20, -30, 30, 30]
        print(chr(27) + "[2J")
        print(f"h={self.heading}")
        for col in range(extent[0], extent[2]):
            print("".join(
                "*" if (row, col) ==
                self.loc else legend[min(self.grid_map.get((row, col), 0), 1)]
                for row in range(extent[1], extent[3])))
        time.sleep(.1)
def main():
    computer = IntCodeComputer('day_15.input')
    droid = (0, 0)
    game_map = {droid: 3}
    instructions = []

    not_visited = {droid: [1, 2, 3, 4]}

    while True:
        result = []
        if droid in not_visited and len(not_visited[droid]) > 0:
            back_tracking = False
            instruction = not_visited[droid].pop()
        else:
            back_tracking = True
            if not instructions:
                # Done
                break

            prev = instructions.pop()
            if prev == 1:
                instruction = 2
            elif prev == 2:
                instruction = 1
            elif prev == 3:
                instruction = 4
            elif prev == 4:
                instruction = 3

        computer.run([instruction], result)

        new_pos = get_new_position(droid, instruction)
        if new_pos not in game_map:
            game_map[new_pos] = result[0]

        if result[0] != 0:
            droid = new_pos
            if not back_tracking:
                instructions.append(instruction)
            if droid not in not_visited:
                not_visited[droid] = [1, 2, 3, 4]
    print_map(game_map)
    oxygen = [x[0] for x in game_map.items() if x[1] == 2][0]
    graph = convert_to_graph(game_map)
    path = find_shortest_path(graph, (0, 0), oxygen)
    print(oxygen)
    print(path)
    print(len(path) - 1)

    max_x = max([x[0] for x in game_map])
    min_x = min([x[0] for x in game_map])
    max_y = max([x[1] for x in game_map])
    min_y = min([x[1] for x in game_map])

    longest_minimum = 0

    for y in range(min_y, max_y + 1):
        for x in range(min_x, max_x + 1):
            if (x, y) in graph:
                longest_minimum = max(
                    longest_minimum,
                    len(find_shortest_path(graph, (x, y), oxygen)) - 1)
    print(longest_minimum)
Esempio n. 21
0
def test_part1():
    comp = IntCodeComputer('input.txt', [])
    bot = PaintBot(comp)
    bot.build_panels(debug=False)
    # print(bot.render())
    assert len(bot.panels) == 1686
Esempio n. 22
0
                ymax = y
        return [xmin, xmax], [ymin, ymax]


class AI:
    # LOL "AI"
    def __init__(self):
        self.map = Map()

    def move(self, result=None):
        return random.randint(1, 4)


if __name__ == '__main__':

    pc = IntCodeComputer(source='input', buffered=True)
    i_robot = AI()

    result = None

    # LOL total garbage:
    for _ in range(1000000):

        move = i_robot.move(result)
        ic_out = pc.run(move)
        result = ic_out[0][0]
        update = i_robot.map.update(move, result)
        if update != 0:
            print(update)
            # break
        # print()
Esempio n. 23
0
from functools import lru_cache
import numpy as np
from intcode import IntCodeComputer, IntCodeStatus

program = list(map(int, open('data/input19').read().strip().split(',')))
computer = IntCodeComputer(program, resume=False)

coords = {}
for x in range(50):
    for y in range(50):
        _, prints, status = computer.run(input_values=[x, y])
        assert status == IntCodeStatus.TERMINATED
        coords[x + 1j * y] = prints[0]

beam = np.empty((50, 50))
for c, value in coords.items():
    r, c = int(c.imag), int(c.real)
    beam[r, c] = value

print(f"solution for part1: {int(beam.sum())}")

@lru_cache()
def get_beam_value(r, c):
    x, y = c, r
    _, beam_value, status = computer.run(input_values=[x, y])
    assert status == IntCodeStatus.TERMINATED
    assert len(beam_value) == 1
    return beam_value[0]


@lru_cache()
Esempio n. 24
0

reverse = {NORTH: SOUTH, SOUTH: NORTH, WEST: EAST, EAST: WEST}

pos = (0, 0)
target = None

grid = defaultdict(lambda: " ")
gridnet = nx.Graph()

grid[pos] = "."
gridnet.add_node((0, 0))
breadcrumbs = []
complete = False

droid = IntCodeComputer(code)

droid.run([])
while not complete and not droid.halted:
    print(pos)
    if grid[move(pos, NORTH)] == " ":
        # print(f"attempting to move north from {pos}")
        output = droid.run([NORTH])[-1]
        # print(output)
        if output == 0:
            grid[move(pos, NORTH)] = "#"
        elif output > 0:
            breadcrumbs.append((reverse[NORTH], pos))
            gridnet.add_node(move(pos, NORTH))
            gridnet.add_edge(pos, move(pos, NORTH))
            pos = move(pos, NORTH)
Esempio n. 25
0
from collections import defaultdict
import time

np.set_printoptions(linewidth=220, threshold=10000)


def coords_to_mem(x, y):
    return x * 38 + y


if __name__ == '__main__':
    inputs = open('inputs.txt').read()
    program = [int(i) for i in inputs.split(',')]

    outputs = []
    computer = IntCodeComputer(inputs, interactive=True)
    mem = computer.program
    mem[0] = 2
    for i in range(1286 - 38, 1322 - 38):
        mem[i] = 1
    # mem[1398] = 2
    # mem[639] = 2
    x, y = None, None
    pixels = np.zeros((20, 38)).astype(np.object)
    x_candidates = None
    y_candidates = None
    step = 0
    while not computer.done:
        while not computer.done:
            outputs.append(computer.run())
            if outputs[-1] == '_':
Esempio n. 26
0
 def c(self, program):
     return IntCodeComputer(program)
Esempio n. 27
0
def run_robot_run(core):

    panel = {}
    pr = PaintingRobot()

    computer = IntCodeComputer()
    computer.load_core(core)
    computer.state = ProgramState.running
    while computer.state == ProgramState.running:
        computer.set_input_buffer([pr.camera(panel)])

        inst = [None, None]
        while len(computer.output_buffer) == 0:
            computer.step()
            if computer.state != ProgramState.running:
                return len(pr._painted_panels)

        inst[0] = computer.output_buffer.pop()

        while len(computer.output_buffer) == 0:
            computer.step()
        inst[1] = computer.output_buffer.pop()

        pr.paint(inst[0], panel)
        pr.turn(inst[1])
Esempio n. 28
0
from intcode import IntCodeComputer

prog = open("input.txt", "r").readline().split(",")
state = [int(x) for x in prog]

compy = IntCodeComputer(state)
compy.run()
from intcode import IntCodeComputer

code = [int(x) for x in open("input.txt", "r").readline().split(",")]
game = IntCodeComputer(code)


def asciify(chars):
    return "".join(chr(x) for x in chars)


def charify(text):
    return [ord(x) for x in text] + [10]


line = ""
while not game.halted:
    output = game.run(charify(line))
    print(asciify(output))
    line = input(">").strip()

print("game halted")
Esempio n. 30
0
    709052072804, 1, 21102, 1, 481, 0, 1106, 0, 482, 99, 109, 2, 21202, -1, 1,
    1, 21101, 0, 40, 2, 21101, 0, 513, 3, 21101, 503, 0, 0, 1106, 0, 546, 109,
    -2, 2105, 1, 0, 0, 1, 0, 0, 1, 109, 2, 3, 10, 204, -1, 1001, 508, 509, 524,
    4, 0, 1001, 508, 1, 508, 108, 4, 508, 10, 1006, 10, 540, 1101, 0, 0, 508,
    109, -2, 2105, 1, 0, 0, 109, 4, 1202, -1, 1, 545, 1207, -3, 0, 10, 1006,
    10, 563, 21102, 0, 1, -3, 21202, -3, 1, 1, 22101, 0, -2, 2, 21102, 1, 1, 3,
    21101, 582, 0, 0, 1105, 1, 587, 109, -4, 2106, 0, 0, 109, 5, 1207, -3, 1,
    10, 1006, 10, 610, 2207, -4, -2, 10, 1006, 10, 610, 21202, -4, 1, -4, 1106,
    0, 678, 22102, 1, -4, 1, 21201, -3, -1, 2, 21202, -2, 2, 3, 21102, 629, 1,
    0, 1106, 0, 587, 22102, 1, 1, -4, 21101, 0, 1, -1, 2207, -4, -2, 10, 1006,
    10, 648, 21102, 0, 1, -1, 22202, -2, -1, -2, 2107, 0, -3, 10, 1006, 10,
    670, 21202, -1, 1, 1, 21101, 670, 0, 0, 105, 1, 545, 21202, -2, -1, -2,
    22201, -4, -2, -4, 109, -5, 2106, 0, 0
]

brain = IntCodeComputer(code)

painted = set()
hull = defaultdict(int)
hull[(0, 0)] = 1

direction = 0  # 0 up, 1 right, 2 down, 3 left
x = 0
y = 0
while not brain.halted:
    result = brain.run([hull[(x, y)]])
    color = result[-2]
    turn = result[-1]

    hull[(x, y)] = color
    painted.add((x, y))