Beispiel #1
0
    def start(self):
        # start the int computer
        self._computer = IntComputer.IntComputer(self._program,
                                                 self._input_queue,
                                                 self._output_queue)
        thread = threading.Thread(target=self._computer.run)
        thread.daemon = True  # allows thread to exit when main program exits
        thread.start()

        positions = {(0, 0)}
        visited = set()

        while positions:
            target, value = positions.pop(), 1
            visited.add(target)
            for next_pos, direction in self.path(self.pos, target, self.free):
                self._input_queue.put(direction)
                value = self._output_queue.get()
                if value == 0:
                    break
                self.pos = next_pos
                if value == 2:
                    self.oxygen_pos = self.pos
            if value:
                self.free.add(self.pos)

            positions.update(next_pos
                             for next_pos, _ in self.neighbors(*self.pos)
                             if next_pos not in visited)
Beispiel #2
0
    def start(self, script):
        # start the int computer
        self._computer = IntComputer.IntComputer(self._program,
                                                 self._input_queue,
                                                 self._output_queue)

        thread = threading.Thread(target=self._computer.run)
        thread.daemon = True  # allows thread to exit when main program exits
        thread.start()

        # convert the list of commands to a list of ascii codes
        input_values = list(map(ord, list('\n'.join(script) + '\n')))
        for val in input_values:
            self._input_queue.put(val)

        while self._computer.is_running == True:
            pass

        while True:
            try:
                output = self._output_queue.get_nowait()
                if output > 128:
                    return output
                print("{:c}".format(output), end='')
            except queue.Empty:
                return 0
Beispiel #3
0
class RepairDroid:

    def __init__(self):

    self.input = 0 
    self.output = 0
    self.position = (0,0)
    self.map = {self.position: None}
    self.status_code = 0
    self.oxygen_found = False
    self.delta_position = {1: [0, 1], 2: [0, -1], 3: [-1, 0], 4: [1, 0]}

    # TODO: is the remote control or the droid an intcomputer?
    self.droid = IntComputer()
    self.doird.connect_with_next_intcomputer(self)

    self.droid.connect_input_receiver(self)
    
    def set_input(self):
        
    def search_oxygen(self):

        while self.exygen == False:
            



    def move(self):

        # Move with respect to status code 
        if self.status_code == 0:
            # Wall: Don't move

        elif self.status.code == 1: 
            # Free space: Move 
            self.position = self.position + self.delta_position[self.input]

        elif self.status_code == 2:
            # Free space and oxygen found: Move 
            self.position = self.position + self.delta_position[self.input]
            self.oxygen_found = True
    
    def update_map(self):

        self.map[self.position] = self.status_code
Beispiel #4
0
 def __init__(self):
     
     self.DIR             = {0: [0,1], 1: [-1,0], 2: [0,-1], 3: [1,0]}  # Directions on 2D plane: up,left,down,right   
     self.NUM_ROBOT_INSTR = 2
     self.orientation     = 0                                                   
     self.position        = (0,0)
     self.color           = 0
     self.panels          = {self.position: self.color}
     self.min_x           = 0
     self.min_y           = 0 
     self.max_x           = 0
     self.max_y           = 0
     self.instruction     = queue.Queue(self.NUM_ROBOT_INSTR)                   
     self.brain           = IntComputer(False, 11) # composition
     
     # Connect the brain with the robot in order to obtain the inputs
     self.brain.connect_with_next_intcomputer(self)
     f = open("advent_11_input.txt", "r")
     self.robot_programm = f.read()
Beispiel #5
0
    def start(self, input_data=None):
        # start the int computer
        self._computer = IntComputer.IntComputer(self._program,
                                                 self._input_queue,
                                                 self._output_queue)
        thread = threading.Thread(target=self._computer.run)
        thread.daemon = True  # allows thread to exit when main program exits
        thread.start()

        # if we have input, stick it on the input queue
        if input_data is not None:
            for i in input_data:
                self._input_queue.put(ord(i))

        x, y = 0, 0
        num_output = ''
        while self._computer.is_running is True:
            pass

        while self._output_queue.empty() is False:
            output = self._output_queue.get()

            # when there is no input data, we should get putting together
            # the grid for the robot
            if input_data is None:
                output = chr(output)
                if output in ['\n', '#', '.', '^', '<', '>', 'v', 'X']:
                    if output == '\n':
                        y += 1
                        x = 0
                    else:
                        # see if this is the start of the robot
                        # and then save it so that we can then use it
                        # as starting pos for finding crossings
                        if output == '^':
                            self.start_pos = Point(x, y)
                        self.tiles[Point(x, y)] = output
                        x += 1
                else:
                    print(output)
            else:
                if output < 255:
                    print(chr(output), end='')
                else:
                    print(output)

        if self._show_display:
            print('{:c}[2J'.format(27))
            for point, char in self.tiles.items():
                print('{:c}[{};{}f{}'.format(27, point.y + 1, point.x + 1,
                                             char))
Beispiel #6
0
    def start(self, x, y):
        # start the int computer
        self._computer = IntComputer.IntComputer(self._program,
                                                 self._input_queue,
                                                 self._output_queue)
        self._input_queue.put(x)
        self._input_queue.put(y)
        thread = threading.Thread(target=self._computer.run)
        thread.start()
        while self._computer.is_running == True:
            pass

        output = self._output_queue.get()
        return output
Beispiel #7
0
    def __init__(self):
        
        self.tiles     = {}
        #NOTE: I assume there exist only one ball and one paddle  
        self.ball      = {"x": -1, "y": -1}  
        self.paddle    = {"x": -1, "y": -1}  
        self.instruction = queue.Queue(3)
        self.block_tile_counter  = 0 
        self.joystick_position = 0  # 0=neutral, -1=left, +1=right
        self.score    = 0  

        self.NUM_ARCADE_INSTR = 3
        self.instruction     = queue.Queue(self.NUM_ARCADE_INSTR)  
        self.brain =  IntComputer(False, 13)
        f = open("advent_13_input.txt", "r")
        puzzle_input = f.read()
        self.brain.parse_instruction(puzzle_input)
        self.brain.set_memory(0, 2)# set mem(0)=2 to play for free
        self.brain.connect_with_next_intcomputer(self)
        
        # NOTE: ist das der richtige Datentyp usw für die Input Verbindung?
        self.brain.connect_input_receiver(self)
        self.game_mode = "AI"
Beispiel #8
0
    def start(self):
        # start the int computer
        self._computer = IntComputer.IntComputer(self._program,
                                                 self._input_queue,
                                                 self._output_queue)
        threading.Thread(target=self._computer.run).start()

        # keep track of paddle and ball
        paddle_x = -1
        ball_x = -1

        while self._computer.is_running is True:
            outputs = []
            for _ in range(3):
                outputs.append(self._output_queue.get())

            # deal with the output
            x = outputs.pop(0)
            y = outputs.pop(0)
            tile = outputs.pop(0)
            # remove empty tiles from the grid
            if tile == 0:
                self.tiles.pop((x, y), None)
            elif tile == 3:
                paddle_x = x
            elif tile == 4:
                ball_x = x

                # I think that this works based on the way
                # the program works.  Trial and error
                # worked here :)
                self._input_queue.put(ball_x - paddle_x)

            if x == -1 and y == 0:
                self.score = tile
            else:
                self.tiles[(x, y)] = tile
                self._print_display(x, y)
 def runAmplifier(self, phase, inputSignal):
     outputs = IntComputer("day07/input.txt").calculateOutputValues(
         [phase, inputSignal])
     return outputs[-1]
Beispiel #10
0
        elif (opcode == 2):
            num3 = num1 * num2
        elif (opcode == 99):
            break
        else:
            assert ("bad juju")

        opcodes[dest] = num3
        ip += 4


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

    machine = IntComputer.IntComputer(program)
    machine.memory.set(1, 12)
    machine.run()
    print(machine.memory.get(0))

    ip = 0
    values = range(0, 99)
    for x in values:
        for y in values:
            machine = IntComputer.IntComputer(program)
            machine.memory.set(1, x)
            machine.memory.set(2, y)
            machine.run()
            if (machine.memory.get(0) == 19690720):
                print(100 * machine.memory.get(1) + machine.memory.get(2))
                sys.exit(0)
Beispiel #11
0
def main():
	computer = IntComputer([int(_) for _ in open("input.txt", "r").read().split(",")])	
	computer.run()
Beispiel #12
0
class PaintRobot:

    def __init__(self):
        
        self.DIR             = {0: [0,1], 1: [-1,0], 2: [0,-1], 3: [1,0]}  # Directions on 2D plane: up,left,down,right   
        self.NUM_ROBOT_INSTR = 2
        self.orientation     = 0                                                   
        self.position        = (0,0)
        self.color           = 0
        self.panels          = {self.position: self.color}
        self.min_x           = 0
        self.min_y           = 0 
        self.max_x           = 0
        self.max_y           = 0
        self.instruction     = queue.Queue(self.NUM_ROBOT_INSTR)                   
        self.brain           = IntComputer(False, 11) # composition
        
        # Connect the brain with the robot in order to obtain the inputs
        self.brain.connect_with_next_intcomputer(self)
        f = open("advent_11_input.txt", "r")
        self.robot_programm = f.read()


    # Start painting by providing the programm and then using the robots intcomputer to process the programm    
    def start_painting(self):
        
        # Feed the robot programm to its brain (intcomputer)
        self.brain.parse_instruction(self.robot_programm)
        
        # Give initial color of the robot to the intcomputer  
        self.brain.set_input(self.get_color())
        
        # Execute the program using the braint (intcomputer)
        self.brain.execute_programm()


    # Process the input coming from the outputting device (intcomputer)
    def set_input(self, input):
        
        self.instruction.put(input)
        
        # 2 inputs = 1 instruction
        if self.instruction.full():
            self.paint_and_move()


    # Turn is either 0=left 1 = right
    def update_orientation(self, turn):

        self.orientation = (self.orientation + 2*turn-1)%4


    # Paint the current panel with a given color
    def update_color(self, color):

        self.panels[self.position] = color
        #self.color_grid2D[self.position] = color


    # Paint current panel and go forward in current direction (we asume a full queue with 2 instructions)
    def paint_and_move(self):
        
        # get instructions for (new color, turn)
        color = self.instruction.get()
        turn  = self.instruction.get() 

        # Update color of panel and orientation of robot
        self.update_color(color)
        self.update_orientation(turn)

        # Go to next panel
        new_x         = self.position[0] + self.DIR[self.orientation][0]
        new_y         = self.position[1] + self.DIR[self.orientation][1]
        self.position = (new_x, new_y)

        # Add current (x,y) coordinate to the set of painted coordinates
        #self.panels_painted.add(self.position) 
        if (self.position in self.panels) == False:
            self.panels[self.position] = 0 # every new panel is black
        
        # Pass current color to the robots brain (intcomputer) as an input 
        self.brain.set_input(self.get_color())

        # update min values
        self.update_min_max(new_x, new_y)


    # Getter function for the color of the current position
    def get_color(self):

        return self.panels[self.position]
        #return self.color_grid2D[self.position]

    # Update min and max x,y coordinates 
    def update_min_max(self, x, y):

        if x < self.min_x:
            self.min_x = x
        elif x > self.max_x:
            self.max_x = x

        if y < self.min_y:
            self.min_y = y
        elif y > self.max_y:
            self.max_y = y

    # Convert the dictionary into a map 
    def build_map(self):

        x_dim = (self.max_x - self.min_x) + 1
        y_dim = (self.max_y - self.min_y) + 1
        color_grid2D = np.zeros((x_dim, y_dim))

        # Loop through all seen panels and plot them on a grid
        for item in self.panels.items(): 

            # Shift data to have only positive values
            x = item[0][0] - self.min_x
            y = item[0][1] - self.min_y 
            position = (x,y)
            color    = item[1]
            color_grid2D[position] = color 
        
        return color_grid2D
Beispiel #13
0
class Arcade:

    def __init__(self):
        
        self.tiles     = {}
        #NOTE: I assume there exist only one ball and one paddle  
        self.ball      = {"x": -1, "y": -1}  
        self.paddle    = {"x": -1, "y": -1}  
        self.instruction = queue.Queue(3)
        self.block_tile_counter  = 0 
        self.joystick_position = 0  # 0=neutral, -1=left, +1=right
        self.score    = 0  

        self.NUM_ARCADE_INSTR = 3
        self.instruction     = queue.Queue(self.NUM_ARCADE_INSTR)  
        self.brain =  IntComputer(False, 13)
        f = open("advent_13_input.txt", "r")
        puzzle_input = f.read()
        self.brain.parse_instruction(puzzle_input)
        self.brain.set_memory(0, 2)# set mem(0)=2 to play for free
        self.brain.connect_with_next_intcomputer(self)
        
        # NOTE: ist das der richtige Datentyp usw für die Input Verbindung?
        self.brain.connect_input_receiver(self)
        self.game_mode = "AI"


    def set_input(self, input):
        
        self.instruction.put(input)
        
        # 3 inputs = 1 instruction
        if self.instruction.full():
            self.parse_instructions()

    # The instructions(intcomputer -> Arcade) update the tiles on the map or display the players score 
    def parse_instructions(self):
        
        # Every 3 instructions an action is performed
        arg1 = self.instruction.get()
        arg2 = self.instruction.get()
        arg3 = self.instruction.get()
        assert(self.instruction.empty() == True)

        # Update the players score 
        if arg1 == -1  and arg2  == 0:
            self.score = arg3
            print("The players score is: ", self.score)

        # Or Update the tiles 
        else:
            tile_pos = (arg1, arg2) 
            tile_ID  = arg3
            self.tiles[tile_pos] = tile_ID

            # Update the ball and paddle copy
            if tile_ID == 4: # ball
                self.ball["x"] = arg1
                self.ball["y"] = arg2
                
            elif tile_ID == 3: # paddle   
                self.paddle["x"] = arg1
                self.paddle["y"] = arg2

            # Solution to part 1: count all block tiles
            elif tile_ID == 2: 
                self.block_tile_counter += 1
            
    # Function that controls the paddle tile
    def control_joystick(self):

        # We only apply a new input if the old one was processed 
        # -> That is taken care of because we only control after a new state 
        # of the game is observed 
        
        # We want to control the paddle directly below the ball
        pos_error = self.paddle["x"] - self.ball["x"]

        # Apply a simple proportional feedback controller
        self.joystick_position = np.sign(-pos_error)
        #print("ball: ", self.ball["x"], "paddle: ", self.paddle["x"], "-> joystick = ", self.joystick)

    def plot_arcade_status(self, multiple):

        if multiple == 0:     
            # Print the current status of the tiles
            tileID_marker = {1: "p", 2: "s", 3: "_", 4: "o"} #1=wall, 2=block, 3=paddle, 4=ball
            tileID_color  = {1: "black", 2: "black", 3: "red", 4: "red"}
            for key, value in self.tiles.items():   # {(x,y) pos: tile ID}
                if value != 0:
                    plt.scatter(*zip(*[key]), marker = tileID_marker[value], color = "black")
            
            plt.show(block=True)
            #plt.pause(1)
            #plt.close()

            # self.game_changed = False 
        else:
            pass 

    def ask_for_input(self):
        
        # Controlled by the player object
        if self.game_mode == "AI":
            
            # Control the joystick based on the position of the ball and paddle
            self.control_joystick()

        # Controlled via console by a player
        else:
            # TODO: the game has to be displayed at that point

            self.joystick_position = -1 # TODO: and user input has to be implemented

            print("User input has to be implemented")
        
        # Pass joystick position to the intcomputer
        return self.joystick_position

    def set_game_mode(self, game_mode):

        self.game_mode = game_mode

    def start_game(self):

        self.brain.execute_programm()