コード例 #1
0
 def RunDay9(self):
     c1 = Computer(DataFixture.mainDay9, True, [1])
     val1 = c1.Run()
     print(f"Run of Day 9-1 with input 1 produces {val1}")  #3533056970
     c2 = Computer(DataFixture.mainDay9, True, [2])
     val2 = c2.Run()
     print(f"Run of Day 9-2 with input 2 produces {val2}")  #72852
コード例 #2
0
 def createPlayer(self, symbol, playerNum):
     while True:
         p1 = input(
             'Please choose player {} ({}): \n1. Human \n2. Computer Player \nYour choice is: '
             .format(playerNum, symbol))
         try:
             p1 = int(p1)
             if p1 == 1:
                 if playerNum == 1:
                     print('Player O is Human.')
                     return Human(symbol)
                 elif playerNum == 2:
                     print('Player X is Human.')
                     return Human(symbol)
                 else:
                     print('Invalid Input.')
             elif p1 == 2:
                 if playerNum == 1:
                     print('Player O is Computer.')
                     return Computer(symbol)
                 elif playerNum == 2:
                     print('Player X is Computer.')
                     return Computer(symbol)
                 else:
                     print('Invalid Input.')
             else:
                 print('Invalid Input.')
         except ValueError:
             print('Invalid Input.')
コード例 #3
0
 def __init__(self):
     super().__init__()
     self.font = pygame.font.SysFont("Arial", 32)
     self.small_font = pygame.font.SysFont("Arial", 14)
     self.title = self.font.render("Trivial Purfuit", True, (0, 128, 0))
     self.company = self.small_font.render(
         "Brought to you by Code Monkey's", True, (0, 128, 0))
     self.subtitle = self.font.render("Freedom Edition", True, (0, 128, 0))
     self.action = self.small_font.render(
         "Press <RETURN> To Start", True, (0, 128, 0))
     self.width, self.height = pygame.display.get_surface().get_size()
     self.title_rect = self.title.get_rect(
         center=(self.width/2, self.height/3))
     self.subtitle_rect = self.subtitle.get_rect(
         center=(self.width/2, self.height/2))
     self.action_rect = self.action.get_rect(
         center=(self.width/2, self.height*2/3))
     self.company_rect = self.company.get_rect(
         center=(self.width/2, self.height - self.company.get_height()/2))
     self.players = [
         Human("1", "assets/laughing.png", 0, 0),
         Computer("2", "assets/neutral.png", 0, 50, 50),
         Computer("3", "assets/shy.png", 50, 0, 90),
         Computer("4", "assets/smile.png", 50, 50, 100)
     ]
     self.direction = 1
     self.current = 0
コード例 #4
0
    def createComputers(self):
        """
        Método de clase
        Se crean las computadoras y sus respectivos procesadores
        """
        # Se crea la computadora 1 y se inicializa su distribución de arribos en None y su identificador en 1
        self.computer_1 = Computer(1, None)
        # Se crea el procesador con identificador 0 y distribución de salida D6
        self.computer_1.add_processor(0, self.distribution_list["D6"])
        # Se agrega el procesador a la lista de procesadores
        self.processor_list.append(self.computer_1.processors_list[0])

        # Se crea la computadora 2 y se inicializa su distribución de arribos en D1 y su identificador en 2
        self.computer_2 = Computer(2, self.distribution_list["D1"])
        # Se crea el procesador con identificador 1 y distribución de salida D2
        self.computer_2.add_processor(1, self.distribution_list["D2"])
        # Se crea el procesador con identificador 2 y distribución de salida D3
        self.computer_2.add_processor(2, self.distribution_list["D3"])
        # Se agrega el procesador a la lista de procesadores
        self.processor_list.append(self.computer_2.processors_list[0])
        # Se agrega el procesador a la lista de procesadores
        self.processor_list.append(self.computer_2.processors_list[1])

        # Se crea la computadora 3 y se inicializa su distribución de arribos en D4 y su identificador en 3
        self.computer_3 = Computer(3, self.distribution_list["D4"])
        # Se crea el procesador con identificador 3 y distribución de salida D5
        self.computer_3.add_processor(3, self.distribution_list["D5"])
        # Se agrega el procesador a la lista de procesadores
        self.processor_list.append(self.computer_3.processors_list[0])
コード例 #5
0
ファイル: SixMensMorris.py プロジェクト: Soapony/csci3180
    def start_game(self):
        # Choose the player type for both players
        print('Please choose Player 1:')
        print('1. Human Player')
        print('2. Computer Player')
        x = input('Your choice is: ')
        if x == '1':
            self.players.append(Human(1, self.board))
            print('Player 1 is a human.')
        elif x == '2':
            self.players.append(Computer(1, self.board))
            print('Player 1 is a computer.')

        ### TODO (Choose the type for player 2)
        print('Please choose Player 2:')
        print('1. Human Player')
        print('2. Computer Player')
        x = input("Your choice is: ")
        if x == '1':
            self.players.append(Human(2, self.board))
            print("Player 2 is a human.")
        elif x == '2':
            self.players.append(Computer(2, self.board))
            print("Player 2 is a computer.")
        # Start the game
        self.board.print_board()
        end = False
        while not end:
            player = self.next_player()

            if self.num_play <= 12:
                # Phase 1
                x = player.next_put()
            else:
                # Phase 2
                x = player.next_move()
            self.board.print_board()

            if self.num_play == 12:  ### TODO:
                if self.check_win(player):
                    end = True
                else:
                    player = self.next_player()
                    if self.check_win(player):
                        end = True
                    player = self.next_player()
            else:
                if self.board.form_mill(x, player):
                    print('You form a mill!')

                    ### TODO
                    player.next_remove(self.opponent(player))

                    self.board.print_board()

                if self.num_play > 12:  ### TODO:
                    if self.check_win(player):
                        ### print("less than 2")
                        end = True
コード例 #6
0
 def createPlayer(self, symbol, playerNum):
     if symbol == 'O':
         if playerNum == '1':
             return Human(symbol)
         else:
             return Computer(symbol)
     else:
         if playerNum == '1':
             return Human(symbol)
         else:
             return Computer(symbol)
コード例 #7
0
ファイル: SixMensMorris.py プロジェクト: yytlee/CSCI3180
    def start_game(self):
        # Choose the player type for both players
        print('Please choose Player 1:')
        print('1. Human Player')
        print('2. Computer Player')
        x = input('Your choice is: ')
        if x == '1':
            self.players.append(Human(1, self.board))
            print('Player 1 is a human.')
        elif x == '2':
            self.players.append(Computer(1, self.board))
            print('Player 1 is a computer.')

        ### TODO (Choose the type for player 2)
        print('Please choose Player 2:')
        print('1. Human Player')
        print('2. Computer Player')
        x = input('Your choice is: ')
        if x == '1':
            self.players.append(Human(2, self.board))
            print('Player 2 is a human.')
        elif x == '2':
            self.players.append(Computer(2, self.board))
            print('Player 2 is a computer.')

        # Start the game
        self.board.print_board()
        end = False
        while not end:
            player = self.next_player()

            if self.num_play <= 12:
                # Phase 1
                x = player.next_put()
            else:
                # Phase 2
                x = player.next_move()
            self.board.print_board()

            if self.num_play >= 12 and self.check_win(
                    player
            ):  ### TODO: allow game end immediatily after put movment
                end = True
            else:
                if self.board.form_mill(x, player):
                    print('You form a mill!')

                    ### TODO
                    player.next_remove(player)

                    self.board.print_board()

                if self.num_play >= 12 and self.check_win(player):  ### TODO:
                    end = True
コード例 #8
0
def visualise():
    memory = load_game(playForFree=True)

    pygame.init()
    size = (50 * CELLSIZE), (50 * CELLSIZE)
    screen = pygame.display.set_mode(size)

    runner = DisplayGame(pygame, screen)
    com = Computer(memory)
    com.run_program(runner.capture)

    next_move_event = pygame.USEREVENT + 1
    pygame.time.set_timer(next_move_event, 100)

    while (True):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

            elif event.type == next_move_event:
                if runner.paddle < runner.ball:
                    com.input_and_continue(1)
                elif runner.paddle > runner.ball:
                    com.input_and_continue(-1)
                else:
                    com.input_and_continue(0)
コード例 #9
0
def part_one():
    memory = load_game(playForFree=False)

    runner = BlockCounter()
    com = Computer(memory)
    com.run_program(runner.capture)
    print(runner.BlockCount)
コード例 #10
0
 def __init__(self, mem, stdscr):
   self.c = Computer(mem)
   self.screen = defaultdict(lambda: 0)
   self.stdscr = stdscr
   self.score = 0
   self.paddle = 0
   self.ball = 0
コード例 #11
0
def part1(code: List[int]) -> int:
    grid = defaultdict(int)
    position = 0
    direction = -1j

    read_color = True

    computer = Computer(code)
    while not computer.done:
        try:
            computer.run()
        except InputInterrupt:
            # send in the color at the current spot
            computer.inputs.append(grid[position])
        except OutputInterrupt:
            value = computer.outputs[-1]
            if read_color:
                # get the color to paint - and paint
                grid[position] = value
            else:
                # read direction - change direction - and move forward 1 step
                direction = direction * -1j if value == 0 else direction * 1j
                position += direction
            read_color = not read_color

    # return the visited squares
    return len(grid)
コード例 #12
0
ファイル: Day11.py プロジェクト: AlexGirardDev/AdventOfPython
def day11_1():
    dir = False
    x = 100
    y = 100
    painted = {(x,y): 0}
    direction = 0 

    f = og.copy()
    comp = Computer(f,1,100000)
    while not comp.done:
        output = comp.iterate(painted[(x, y)])
        if dir:
            direction = set_direction(direction, output)
            if direction == 0:
                y -= 1
            elif direction == 1:
                x += 1
            elif direction == 2:
                y += 1
            elif direction == 3:
                x -= 1
            painted[(x, y)] = painted[(x,y)] if painted.get((x,y)) is not None else 0
        else:
            painted[(x, y)] = output
        dir = not dir
    print(len(painted))
    for x in range(200):
        output = ""
        for y in range(200):
            if painted.get((x, y)):
                output += "#" if painted[(x, y)] == 1 else "."
            else:
                output += "."
        print(output)
コード例 #13
0
ファイル: Game.py プロジェクト: bug-er404/GoStop
    def startNewGame(self):
        """ Method to start a new round of Go Stop.

        Start a new round of Go stop. Initializes the frame and players for the game.
        Determine first player by calling determineFirstPlayer method and by checking the scores of each player.
        Then initiates the round according to who the first player is.

        Args:

        Returns:
            NA

        Raises:
            NA
        """
        # Open game window
        self.__mainWindow.openGameWindow()
        # Initializing user and computer players
        tPlayers = [
            User(i) for i in range(0, int(self.__mainWindow.getUserPlayers()))
        ]
        for i in range(0, int(self.__mainWindow.getCompPlayers())):
            tPlayers.append(Computer(i))
        self.__mPlayers = tuple(tPlayers)

        # TESTING
        t_round = Round.Round(self, self.__mainWindow)
コード例 #14
0
ファイル: 13.py プロジェクト: ajcarvajal/advent2019
def game():
    cpu = Computer(DATA, 0)

    def controls():
        x = input()
        if x == 'h':
            return -1
        if x == 'l':
            return 1
        return 0

    cpu.set_input_func(controls)
    cpu.memory[0] = 2
    output = None
    screen = defaultdict(int)
    while cpu.running:
        xpos = cpu.run()
        ypos = cpu.run()
        tile = cpu.run()

        if xpos is None or ypos is None:
            break
        screen[(xpos, ypos)] = tile
        subprocess.run('clear')
        draw(screen)
コード例 #15
0
def part2(code: List[int]) -> int:
    code[0] = 2
    computer = Computer(code)
    dust = 0

    main_routine = 'A,B,A,B,C,C,B,A,B,C\n'
    a_routine = 'L,8,R,12,R,12,R,10\n'
    b_routine = 'R,10,R,12,R,10\n'
    c_routine = 'L,10,R,10,L,6\n'
    complete_routine = main_routine + a_routine + b_routine + c_routine + 'n\n'

    ascii_routine = [ord(ch) for ch in complete_routine]
    i = 0
    while not computer.done:
        try:
            computer.run()
        except InputInterrupt:
            computer.inputs.append(ascii_routine[i])
            i += 1
        except OutputInterrupt:
            result = computer.outputs[-1]
            if result > 1000:
                return result
            print(chr(result), end='')
    return dust
コード例 #16
0
ファイル: Game.py プロジェクト: isaac-kuhlmann/battleship
 def __init__(self,
              board_size=25,
              cell_size=20,
              margin=15):  #constructor of the display, dimensions
     '''
     Display Constructor
     Parameters: N/A
     Returns: N/A
     Preconditions: N/A
     Postconditions: Creates a valid screen, computer, player board, fleet for both computer and player
     '''
     #*****Initializes screen*****#
     self.board_size = board_size
     self.cell_size = cell_size
     self.margin = margin
     SCREEN_WIDTH = 470
     self.SCREEN_WIDTH = SCREEN_WIDTH
     SCREEN_HEIGHT = 900
     self.SCREEN_HEIGHT = SCREEN_HEIGHT
     screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
     self.screen = screen
     pygame.init()
     pygame.font.init()
     self.font = pygame.font.SysFont("ComicSans", 15)  # sets font
     pygame.display.set_caption("Battleship!")  #name of window
     self.buffer = math.floor(
         self.margin / 30 + self.board_size *
         self.cell_size)  #buffer between top and bottom grid
     #****************#
     #*****Member Variables of game*****#
     self.playerBoard = Board()
     self.playerFleet = []
     self.computerFleet = []
     self.computer = Computer()  #contains it's own board
コード例 #17
0
 def test_makeMoveMedium(self):
     game_board = Board()
     game_player = Computer(game_board, "X", 2)
     game_board.board = ["X", "O", "X", "X", "4", "5", "O", "7", "8"]
     game_player.make_move()
     self.assertEqual(game_player.board.getBoard(),
                      ["X", "O", "X", "X", "X", "5", "O", "7", "8"])
コード例 #18
0
 def test_eval_board(self):
     game_board = Board()
     game_player = Computer(game_board, "X", 2)
     game_board.board = ["X", "O", "X", "X", "4", "5", "O", "7", "8"]
     game_player.eval_board()
     self.assertEqual(game_player.board.getBoard(),
                      ["X", "O", "X", "X", "X", "5", "O", "7", "8"])
コード例 #19
0
    def __init__(self, code: List[int]):
        # set origin to value found from previous runs
        # - to avoid grid shaking
        self.origin = (21, 21)
        self.position = self.origin
        self.found_oxygen = False
        self.world = {self.position: WALKABLE}
        self.path = [self.position]
        self.walkable = set()
        self.droid = Computer(code)
        self.dir_i = 0
        self.x_min = 0
        self.y_min = 0
        self.fully_explored = False
        self.contains_oxygen = set()
        self.check_neighbors = set()
        self.oxygen_minutes = 0

        # set up the game board
        pygame.init()
        self.display = pygame.display.set_mode((615, 615))
        self.colors = {
            WALL: pygame.Color('grey10'),
            WALKABLE: pygame.Color('white'),
            DROID: pygame.Color('firebrick'),
            ORIGIN: pygame.Color('orange'),
            PATH: pygame.Color('lightgreen'),
            OXYGEN: pygame.Color('deepskyblue'),
            BACKGROUND: pygame.Color('grey50')
        }
        self.display.fill(self.colors[BACKGROUND])
コード例 #20
0
def part_two():
    sequence = "A,B,A,C,B,C,A,C,B,C"
    method_a = "L,8,R,10,L,10"
    method_b = "R,10,L,8,L,8,L,10"
    method_c = "L,4,L,6,L,8,L,8"
    video_feed = "N"

    computer_input = []
    for input_str in [sequence, method_a, method_b, method_c, video_feed]:
        computer_input.extend(to_ascii(input_str))

    def input_function():
        global idx
        output = computer_input[idx]
        idx += 1
        return output

    computer = Computer(input_data, input_function)
    computer.program[0] = 2

    computer_output = None
    while True:
        prev_value = computer_output
        computer_output = computer.run()
        if computer_output is None:
            print(f"Part 2: {prev_value}")
            break
コード例 #21
0
def part_two():
    memory = load_game(playForFree=True)

    runner = CaptureForBot()
    com = Computer(memory)
    com.run_program(runner.capture, runner.next_move)
    print(runner.Score)
コード例 #22
0
ファイル: Driver.py プロジェクト: dkwgit/AdventOfCode2019
    def DoTests(self):
        testInputs = [
            DataFixture.test1,
            DataFixture.test2,
            DataFixture.test3,
            DataFixture.test4,
            DataFixture.test5,
            DataFixture.test6,
            DataFixture.test7,
        ]
        for index, testTuple in enumerate(testInputs):
            print(f"Running test {index + 1}")
            testData = testTuple[0]
            testDescription = testTuple[1]
            testIO = testTuple[2]
            print(f"\t{testDescription}")
            for idx, inputOutputTuple in enumerate(testIO):
                value, output = inputOutputTuple
                print(f"\t\tRunning subtest {idx + 1}")
                c = Computer(testData, True, [value])
                result = c.Run()
                print(f"\t\t\tTest produced {result} with expected {output}")
                assert (result == output)

        self.RunAmplifierTests()
        self.RunAmplifierFeedbackTests()
コード例 #23
0
ファイル: Driver.py プロジェクト: dkwgit/AdventOfCode2019
 def RunAmplifierFeedbackSetup(self, programData, amplifierSettings):
     runningComputers = []
     computers = []
     nextValue = 0
     for index, setting in enumerate(amplifierSettings):
         inputOutputEvents = (threading.Event(), threading.Event())
         c = Computer(programData, True, [setting, nextValue],
                      inputOutputEvents)
         t = threading.Thread(target=threadStartFunc, args=(
             c,
             index,
         ))
         t.start()
         computers.append(c)
         runningComputers.append([c, t])
         nextValue = c.GetHighestOutput()
     loop = 5
     while (loop > 0):
         for index in range(len(runningComputers)):
             c, t = runningComputers[index]
             if (c is None):
                 # in theory each amplifier stops in linear succession
                 assert (0 == 1)
                 continue
             c.AddInput(nextValue)
             if (c.GetState() == 0):
                 nextValue = c.GetLastOutput()
                 runningComputers[index] = None
                 loop = loop - 1
             else:
                 nextValue = c.GetHighestOutput()
     return nextValue
コード例 #24
0
    def SetupGameAndRun(self):

        computer = Computer()
        program = DataFixture.mainDay13.copy()
        program[0] = 2  #put in two quarters
        computer.LoadProgram(program)
        outputData = []

        #We do one run-through with computer to answer Day13-1 and also to get dimensions of "screen"
        continueRun = True
        inputEvent = False
        while (continueRun and inputEvent == False):
            result, continueRun, inputEvent = computer.RunToNextIO()
            if (inputEvent == False and result is not None):
                outputData.append(result)
        val = iter(outputData)
        blockCount = 0
        triplets = []
        for x, y, char in zip(val, val, val):
            if (char == 2):
                blockCount = blockCount + 1
            triplets.append(((x, y), char))
        #Day 13-1 answer
        print(f"Block count {blockCount}")

        #Get screen dimensions
        minX = min(triplets, key=lambda x: x[0][0])[0][0]
        minY = min(triplets, key=lambda x: x[0][1])[0][1]
        maxX = max(triplets, key=lambda x: x[0][0])[0][0]
        maxY = max(triplets, key=lambda x: x[0][1])[0][1]

        # Create the game with the dimensions and run it
        # Note: when the game is being played, there are two spurious bytes of input for an empty score at this point, hence the :-2: array slice
        game = Game(computer, (minX, minY), (maxX, maxY), outputData[:-2:])
        game.MainLoop()
コード例 #25
0
def does_square_fit(x, y):
    for x_1, y_1 in [(99, 0), (0, 99), (99, 99)]:
        computer = Computer(input_data, None)
        output = computer.run([x + x_1, y + y_1])
        if output == 0:
            return False

    return True
コード例 #26
0
ファイル: main.py プロジェクト: chriszhang3/checkers
def main():

    option = input("Press h to play against a human player. \nPress c to play against a computer player. \n")
    while option != "c" and option != "h":
        option = input("Invalid input. Try again: ")

    root = Tk()
    board_size = UI.window_size
    cell_size = int(board_size/8)
    window_size = board_size+cell_size
    letters = ["A","B","C","D","E","F","G","H"]

    root.geometry(str(window_size)+'x'+str(window_size))

    board = Board()
    computer = Computer(board,1)
    ui = UI.make_ui(board)
    canvas =ui.get_canvas()
    canvas.pack()
    canvas.place(x=0,y=0)
    if option == "h":
        canvas.bind('<Button-1>',
            lambda event, b=board, u = ui: UI.onclick_human(event,b,u))

    # After the human turn, you need to click for the computer's turn to start.
    elif option == "c":
        computer = Computer(board,1)
        canvas.bind('<Button-1>',
            lambda event, b=board, c= computer, u = ui: UI.onclick_computer(event,b,c,u))

    for i in range(8):
        label = Label(root,
    		 text=letters[i],
    		 font = "Helvetica %d"%int(cell_size/2))
        label.pack()
        label.place(x = cell_size*i+22, y = board_size+15)

    for number in range(8):
        label = Label(root,
             text=str(number+1),
             font = "Helvetica %d"%int(cell_size/2))
        label.pack()
        label.place(x = board_size+27, y = 14+number*cell_size)


    root.mainloop()
コード例 #27
0
 def Run(self, data=None):
     computer = Computer()
     program = DataFixture.mainDay15.copy()
     computer.LoadProgram(program)
     game = Game(computer)
     if (data is not None):
         game.LoadScreenData(data)
     game.MainLoop()
コード例 #28
0
ファイル: Game.py プロジェクト: JacquesGarre/blackjack
 def __init__(self, mode, bet, coop):
     self.deck = self.get_deck(shuffled=True)
     self.humans = []
     self.computer = Computer()
     self.mode = mode
     self.ranking = []
     self.coop = coop
     self.bet = bet
コード例 #29
0
def test_larger_input(test_input, expected):
    computer = Computer([
        3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31,
        1106, 0, 36, 98, 0, 0, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104, 999,
        1105, 1, 46, 1101, 1000, 1, 20, 4, 20, 1105, 1, 46, 98, 99
    ])

    assert computer.compute(test_input) == expected
コード例 #30
0
def part1(code: List[int]) -> int:
    code[1] = 12
    code[2] = 2

    computer = Computer(code)
    computer.run()

    return computer.code[0]