Ejemplo n.º 1
0
def get_map(sequence):

    intcode = IntcodeProgram(sequence)
    intcode.run_intcode_program_in_other_program()

    for i, x in enumerate(intcode.output):
        if x == 10:
            w = i+1
            break
    h = len(intcode.output) // w
    print(h,w)

    character_output = [chr(x) for x in intcode.output]
    feed = [character_output[i*w:w*(i+1)-1] for i in range(h)]
    w -= 1

    alignment = 0
    for x in range(1, w-1):
        for y in range(1, h-1):
            if feed[y][x] == '#' and feed[y+1][x] == '#' and feed[y-1][x] == '#' and feed[y][x+1] == '#' and feed[y][x-1] == '#':
                alignment += x*y
                feed[y][x] = 'O'

    print_map(feed)
    print('Part 1:', alignment, '\n')
Ejemplo n.º 2
0
 def __init__(self, address):
     self.intcode = IntcodeProgram(initial_sequence)
     # self.intcode.debug = True
     self.intcode.add_input(address)
     self.address = address
     self.count_empty_queue = 0
     self.idle = None
Ejemplo n.º 3
0
class Computer:
    def __init__(self, address):
        self.intcode = IntcodeProgram(initial_sequence)
        # self.intcode.debug = True
        self.intcode.add_input(address)
        self.address = address
        self.count_empty_queue = 0
        self.idle = None

    def send(self):
        self.idle = False
        return self.intcode.get_output(size=3, extract=True)

    def receive(self, x, y):
        self.idle = False
        self.intcode.add_input((x, y))

    def run(self):
        if self.intcode.sequence[
                self.intcode.idx] == 3 and self.intcode.input == []:
            self.intcode.add_input(-1)
            self.count_empty_queue += 1
            self.idle = True
            # print(f'Computer {self.address} asked for input but queue is empty')
        self.intcode.process_opcode()
Ejemplo n.º 4
0
    def __init__(self):
        self.forbidden_items = ["molten lava", "giant electromagnet", "escape pod", "infinite loop"]
        self.locations = {}
        self.queue = queue.Queue()

        self.intcode = IntcodeProgram(initial_sequence)
        self.intcode.run_intcode_program_in_other_program()
        ascii_output = self.intcode.get_output(extract=True)
        string_output = ''.join([chr(x) for x in ascii_output])
        string_output, location, directions, items = self.read_output(string_output)

        for direction in directions:
            pass
Ejemplo n.º 5
0
class Droid:
    def __init__(self):
        self.intcode = IntcodeProgram(initial_sequence)
        self.location = None

    def run_in_command_line(self):
        while not self.intcode.finished:
            self.intcode.run_intcode_program_in_other_program()
            ascii_output = self.intcode.get_output(extract=True)
            string_output = ''.join([chr(x) for x in ascii_output])
            print(string_output)

            string_input = input("")
            ascii_input = [ord(x) for x in string_input] + [ord('\n')]
            self.intcode.add_input(ascii_input)
Ejemplo n.º 6
0
class SimpleGame:
    tile_dict = {0: ' ', 1: '*', 2: '#', 3: '=', 4: 'o'}

    def __init__(self, sequence):
        from Intcode import IntcodeProgram
        self.intcode = IntcodeProgram(sequence)
        self.screen = []

    def count_blocks(self):
        count = 0
        for row in self.screen:
            count += row.count('#')

        return count

    def draw_screen(self):
        self.screen = [[
            '.' for _ in range(
                max([
                    x for i, x in enumerate(self.intcode.output) if i % 3 == 0
                ]) + 1)
        ] for _ in range(
            max([x for i, x in enumerate(self.intcode.output) if i % 3 == 1]) +
            1)]
        score = 0
        for i in range(0, len(self.intcode.output), 3):
            tile_id = self.intcode.output[i + 2]
            # tile_dict = {0: ' ', 1: '*', 2: '#', 3: '-', 4: 'o'}
            if self.intcode.output[i] == -1:
                score = tile_id
            else:
                self.screen[self.intcode.output[i + 1]][
                    self.intcode.output[i]] = self.tile_dict[tile_id]

        count = self.count_blocks()
        print('Blocks left: ', count, '   Score: ', score)
        for row in self.screen:
            print(''.join(row))

        return count

    def play_game(self):
        import msvcrt

        number_of_blocks = self.draw_screen()
        while number_of_blocks > 0 and self.intcode.finished is False:
            user_input = msvcrt.getch().decode("utf-8")
            if user_input == 'a':
                self.intcode.add_input(-1)
            elif user_input == 'd':
                self.intcode.add_input(1)
            else:
                self.intcode.add_input(0)
            self.intcode.run_intcode_program_in_other_program()
            number_of_blocks = self.draw_screen()
Ejemplo n.º 7
0
class Solver:
    moves = ('south', 'east', 'north', 'west')

    def __init__(self):
        self.forbidden_items = ["molten lava", "giant electromagnet", "escape pod", "infinite loop"]
        self.locations = {}
        self.queue = queue.Queue()

        self.intcode = IntcodeProgram(initial_sequence)
        self.intcode.run_intcode_program_in_other_program()
        ascii_output = self.intcode.get_output(extract=True)
        string_output = ''.join([chr(x) for x in ascii_output])
        string_output, location, directions, items = self.read_output(string_output)

        for direction in directions:
            pass

    def solve(self):
        pass

    def process(self, node):
        string_input = input("")
        ascii_input = [ord(x) for x in string_input] + [ord('\n')]
        self.intcode.add_input(ascii_input)
        self.intcode.run_intcode_program_in_other_program()
        ascii_output = self.intcode.get_output(extract=True)
        string_output = ''.join([chr(x) for x in ascii_output])

    @staticmethod
    def read_output(string_output):
        re_location = "== [a-zA-Z ]+ =="
        re_directions = "Doors here lead:\n[\w\s-]*\n\n"
        re_items = "Items here:\n[\w\s-]*\n\n"

        try:
            location = re.search(re_location, string_output).group()[3:-3]
        except AttributeError:
            location = None

        try:
            directions = re.search(re_directions, string_output).group()
            directions = directions.strip().split('\n- ')[1:]
        except AttributeError:
            directions = []

        try:
            items = re.search(re_items, string_output).group()
            items = items.strip().split('\n- ')[1:]
        except AttributeError:
            items = []

        return location, directions, items
Ejemplo n.º 8
0
    def __init__(self, sequence, map_maker=False):
        from Intcode import IntcodeProgram
        self.intcode = IntcodeProgram(sequence)

        self.screen_size = (1000, 750)
        self.block_size = 10
        self.offset = [(x // 20) * 10 for x in self.screen_size]

        self.loc = (0, 0)
        self.map = {self.loc: 3}
        self.idx = 0
        self.map_maker = map_maker

        pygame.init()
        self.screen = pygame.display.set_mode(self.screen_size)
        self.draw_initial_screen()
        pygame.display.set_caption("My First Game")
        self.clock = pygame.time.Clock()
        self.carry_on = True

        self.move = None
        self.status = None
Ejemplo n.º 9
0
def is_beam(x, y):
    robot = IntcodeProgram(sequence)
    robot.add_input([x, y])
    robot.run_intcode_program_in_other_program()
    if robot.output[-1]:
        return True
    else:
        return False
Ejemplo n.º 10
0
def part_1():
    print('Part 1:')

    with open("day21_input_part1.txt") as f:
        program = [ord(x) for x in f.read()]

    robot = IntcodeProgram(sequence)
    robot.add_input(program)
    robot.run_intcode_program_in_other_program()
    print(''.join([chr(x) if x < 256 else str(x) for x in robot.output]))
Ejemplo n.º 11
0
    print('Part 1:', alignment, '\n')


def print_map(feed):
    for m in feed:
        print(' '.join(m))


if __name__ == '__main__':
    with open("day17.txt") as f:
        sequence = [int(x) for x in f.read().strip().split(',')]

    get_map(sequence)

    sequence[0] = 2
    robot = IntcodeProgram(sequence)

    routine = [ord(char) for char in 'A,B,B,A,C,A,C,A,C,B\n']
    A = [ord(char) for char in 'L,6,R,12,R,8\n']
    B = [ord(char) for char in 'R,8,R,12,L,12\n']
    C = [ord(char) for char in 'R,12,L,12,L,4,L,4\n']
    video = [ord(char) for char in 'n\n']

    robot.add_input(routine + A + B + C + video)
    robot.run_intcode_program_in_other_program()

    print(robot.output)



Ejemplo n.º 12
0
if __name__ == '__main__':
    import sys
    from Intcode import IntcodeProgram

    f = open(sys.argv[1], 'r')
    file_content = f.read().split(',')
    f.close()

    intcode = IntcodeProgram([int(number) for number in file_content])
    intcode.run_intcode_program()
Ejemplo n.º 13
0
 def __init__(self, sequence):
     from Intcode import IntcodeProgram
     self.intcode = IntcodeProgram(sequence)
     self.screen = []
Ejemplo n.º 14
0
 def __init__(self):
     self.intcode = IntcodeProgram(initial_sequence)
     self.location = None
Ejemplo n.º 15
0
                self.extend_footprint(self.robot_direction)
                self.robot_location = [
                    max(0, self.robot_location[0]),
                    max(0, self.robot_location[1])
                ]

    def print_surface(self):
        for row in self.surface:
            print(''.join(row))

    def print_footprint(self):
        n = 0
        for row in self.footprint:
            print(''.join(row))
            n += ''.join(row).count('#')
        print(n)


if __name__ == '__main__':
    from Intcode import IntcodeProgram
    import sys

    f = open(sys.argv[1])
    sequence = [int(x) for x in f.read().strip().split(',')]
    f.close()

    intcode = IntcodeProgram(sequence)
    # intcode.debug = True
    robot = Robot()
    robot.paint_surface(intcode)
Ejemplo n.º 16
0
def find_highest_signal_to_thrusters_with_loop():
    from itertools import permutations
    from Intcode import IntcodeProgram
    import sys

    f = open(sys.argv[1], 'r')
    file_content = f.read().split(',')
    f.close()

    phase_setting_candidates = permutations((5, 6, 7, 8, 9), 5)

    max_thruster_signal = 0
    for phase_setting in phase_setting_candidates:
        print(phase_setting)
        signal = 0

        amplifier_a = IntcodeProgram([int(number) for number in file_content])
        amplifier_b = IntcodeProgram([int(number) for number in file_content])
        amplifier_c = IntcodeProgram([int(number) for number in file_content])
        amplifier_d = IntcodeProgram([int(number) for number in file_content])
        amplifier_e = IntcodeProgram([int(number) for number in file_content])

        amplifier_a.run_intcode_program_until_next_input(phase_setting[0])
        signal = amplifier_a.run_intcode_program_until_next_input(signal)
        amplifier_b.run_intcode_program_until_next_input(phase_setting[1])
        signal = amplifier_b.run_intcode_program_until_next_input(signal)
        amplifier_c.run_intcode_program_until_next_input(phase_setting[2])
        signal = amplifier_c.run_intcode_program_until_next_input(signal)
        amplifier_d.run_intcode_program_until_next_input(phase_setting[3])
        signal = amplifier_d.run_intcode_program_until_next_input(signal)
        amplifier_e.run_intcode_program_until_next_input(phase_setting[4])
        signal = amplifier_e.run_intcode_program_until_next_input(signal)

        while amplifier_e.sequence[amplifier_e.idx] != 99:
            signal = amplifier_a.run_intcode_program_until_next_input(signal)
            signal = amplifier_b.run_intcode_program_until_next_input(signal)
            signal = amplifier_c.run_intcode_program_until_next_input(signal)
            signal = amplifier_d.run_intcode_program_until_next_input(signal)
            signal = amplifier_e.run_intcode_program_until_next_input(signal)

        max_thruster_signal = max(max_thruster_signal, signal)

    return max_thruster_signal
Ejemplo n.º 17
0
class GameEngine:
    moves = {'NORTH': 1, 'SOUTH': 2, 'WEST': 3, 'EAST': 4}
    print_status = {0: 'WALL', 1: 'MOVE', 2: 'GOAL', 3: 'START'}
    direction = ['NORTH', 'WEST', 'SOUTH', 'EAST']

    def __init__(self, sequence, map_maker=False):
        from Intcode import IntcodeProgram
        self.intcode = IntcodeProgram(sequence)

        self.screen_size = (1000, 750)
        self.block_size = 10
        self.offset = [(x // 20) * 10 for x in self.screen_size]

        self.loc = (0, 0)
        self.map = {self.loc: 3}
        self.idx = 0
        self.map_maker = map_maker

        pygame.init()
        self.screen = pygame.display.set_mode(self.screen_size)
        self.draw_initial_screen()
        pygame.display.set_caption("My First Game")
        self.clock = pygame.time.Clock()
        self.carry_on = True

        self.move = None
        self.status = None

    def run_game(self):

        while self.carry_on:
            if self.map_maker:
                self.keep_right()
            else:
                self.capture_events()

            if self.move:
                self.intcode.add_input(self.moves[self.move])
                self.intcode.run_intcode_program_in_other_program()
                self.status = self.intcode.output[-1]
                # print('Movement', self.move, 'results in', self.print_status[self.status])

                self.map[self.new_location()] = self.status

                self.update_screen()

                if self.status:
                    self.loc = self.new_location()
                    self.idx = (self.idx - 1) % 4
                else:
                    self.idx = (self.idx + 1) % 4

            pygame.display.flip()

            self.clock.tick(60)
            self.move, self.status = None, None

        pygame.quit()

    def keep_right(self):
        self.move = self.direction[self.idx]

        if self.new_location() == (0, 0) and self.idx == 0:
            self.save_map()
            self.map_maker = False

    def save_map(self):
        f = open("day15_map.txt", "w")
        f.write(str(self.map))
        f.close()

    def capture_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.carry_on = False

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_DOWN:
                    self.move = 'SOUTH'
                if event.key == pygame.K_UP:
                    self.move = 'NORTH'
                if event.key == pygame.K_LEFT:
                    self.move = 'WEST'
                if event.key == pygame.K_RIGHT:
                    self.move = 'EAST'

    def draw_initial_screen(self):
        self.screen.fill(GREY)

        x, y = self.screen_size
        for i in range(1, x // self.block_size):
            pygame.draw.line(self.screen, LIGHTGREY, [i * self.block_size, 0],
                             [i * self.block_size, y], 1)
        for i in range(1, y // self.block_size):
            pygame.draw.line(self.screen, LIGHTGREY, [0, i * self.block_size],
                             [x, i * self.block_size], 1)

        for location, tile in self.map.items():
            x, y = [l + o for l, o in zip(location, self.offset)]
            self.draw_tile(x, y, tile)

        b = self.block_size
        xs, ys = [l + o for l, o in zip(self.loc, self.offset)]
        pygame.draw.rect(self.screen, YELLOW, [xs + 3, ys + 3, b - 5, b - 5])

    def draw_tile(self, x, y, tile_type):
        b = self.block_size
        if tile_type == 3:
            pygame.draw.rect(self.screen, YELLOW, [x, y, b + 1, b + 1], 1)
            pygame.draw.rect(self.screen, WHITE, [x + 1, y + 1, b - 1, b - 1])
        elif tile_type == 2:
            pygame.draw.rect(self.screen, GREEN, [x + 1, y + 1, b - 1, b - 1])
        elif tile_type == 1:
            pygame.draw.rect(self.screen, WHITE, [x + 1, y + 1, b - 1, b - 1])
        elif tile_type == 0:
            pygame.draw.rect(self.screen, BLACK, [x + 1, y + 1, b - 1, b - 1])

    def new_location(self):
        if self.move == 'NORTH':
            return self.loc[0], self.loc[1] - self.block_size
        elif self.move == 'SOUTH':
            return self.loc[0], self.loc[1] + self.block_size
        elif self.move == 'WEST':
            return self.loc[0] - self.block_size, self.loc[1]
        elif self.move == 'EAST':
            return self.loc[0] + self.block_size, self.loc[1]
        return self.loc

    def update_screen(self):
        new_x, new_y = [
            l + o for l, o in zip(self.new_location(), self.offset)
        ]
        b = self.block_size

        self.draw_tile(new_x, new_y, self.status)

        if self.status:
            x, y = [l + o for l, o in zip(self.loc, self.offset)]
            self.draw_tile(x, y, self.map[self.loc])
            pygame.draw.rect(self.screen, YELLOW,
                             [new_x + 3, new_y + 3, b - 5, b - 5])