Esempio n. 1
0
    def __init__(self, game_number, file_name=None):
        self.winner = 0  # The winner
        self.board_size = 3  # The board size
        self.game_number = game_number  # The game number
        self.game_board = GameBoard(self.board_size)  # Board creation
        self.file_name = file_name

        # Computer Player move - easy bot
        if game_number == 1:
            self.computer_player = ComputerPlayer()  # The Computer Player
        # Computer Player move - strong bot
        elif game_number == 2:
            self.player_list = []
            self.player_list.append(PlayerQRL(1, 0.1, 0.9, 0.7, game_number,
                                              1))  # The QRL Computer Player

            # Load saved players data:
            load_players_stats(self.player_list, file_name)

        elif game_number == 3:
            self.player_list = []

            # Add 1st Player:
            self.player_list.append(ComputerPlayer())

            # Add 2nd Player:
            self.player_list.append(ComputerPlayer())

            # Load saved players data:
            load_players_stats(self.player_list, file_name)

        elif game_number == 4:
            self.player_list = []

            # Add 1st Player:
            # Parameters: mark, learning rate, discount, exploration rate
            self.player_list.append(PlayerQRL(1, 0.1, 0.9, 0.7, game_number,
                                              1))

            # Add 2nd Player:
            self.player_list.append(ComputerPlayer())

            # Load saved players data:
            load_players_stats(self.player_list, file_name)

        elif game_number == 5:
            self.player_list = []

            # Add 1st Player:
            # Parameters: mark, learning rate, discount, exploration rate
            self.player_list.append(
                PlayerQRL(-1, 0.1, 0.9, 0.7, game_number, 1))

            # Add 2nd Player:
            self.player_list.append(PlayerQRL(1, 0.1, 0.9, 0.7, game_number,
                                              1))

            # Load saved players data:
            load_players_stats(self.player_list, file_name)
    def __init__(self, game):
        super().__init__()
        self.game_done = False
        self.grid = QGridLayout()
        self.buttons = [['' for x in range(3)] for y in range(3)]
        self.game = game
        self.computer = ComputerPlayer(game, 'O')
        self.initUI()

        game.set_game_changed_callback(
            lambda current_position: self.update_ui(current_position))
        game.set_game_won_callback(lambda winner: self.announce_winner(winner))
Esempio n. 3
0
    def __create_menu(self):
        play_menu = gtk.Menu()

        play_menu_item = gtk.MenuItem("Play")
        play_menu_item.set_submenu(play_menu)

        single_player_menu_item = gtk.MenuItem("Single-player (PvC)")
        multiplayer_menu_item = gtk.MenuItem("Multiplayer (PvP)")
        duel_menu_item = gtk.MenuItem("Duel (CvC)")
        options_menu_item = gtk.MenuItem("Options")
        exit_menu_item = gtk.MenuItem("Exit")

        single_player_menu_item.connect('activate', self.play, Player(),
                                        ComputerPlayer())
        multiplayer_menu_item.connect('activate', self.play, Player(),
                                      Player())
        duel_menu_item.connect('activate', self.play, ComputerPlayer(),
                               ComputerPlayer())
        options_menu_item.connect('activate', self.options_dialog)
        exit_menu_item.connect('activate', self.quit, self)

        # Unfinished
        single_player_menu_item.set_sensitive(False)
        duel_menu_item.set_sensitive(False)

        play_menu.append(single_player_menu_item)
        play_menu.append(multiplayer_menu_item)
        play_menu.append(duel_menu_item)
        play_menu.append(gtk.SeparatorMenuItem())
        play_menu.append(options_menu_item)
        play_menu.append(gtk.SeparatorMenuItem())
        play_menu.append(exit_menu_item)

        actions_menu = gtk.Menu()

        actions_menu_item = gtk.MenuItem("Actions")
        actions_menu_item.set_submenu(actions_menu)

        load_menu_item = gtk.MenuItem("Load")
        load_menu_item.connect('activate', self.file_dialog, "Load your game",
                               'load')

        load_menu_item.set_sensitive(False)  # Unfinished

        actions_menu.append(load_menu_item)

        menu_bar = gtk.MenuBar()

        menu_bar.append(play_menu_item)
        menu_bar.append(actions_menu_item)

        return menu_bar
Esempio n. 4
0
def begin_game():
    # Determine opponent type
    opponent_type = determine_opponent()
    # Instantiate players
    player_one = HumanPlayer()
    if opponent_type == '1':
        player_two = HumanPlayer('', 2)
    else:
        player_two = ComputerPlayer()
    # Setup Tracking variables
    counter = 1  # 5 turns
    winner_exists = False
    max_counter = 5
    # Process game turns
    while counter <= max_counter and not winner_exists:
        print(f'===== Turn {counter} =====')
        player_one_choice = player_one.method_of_play(
            game_gestures.gesture_name_list)
        player_two_choice = player_two.method_of_play(
            game_gestures.gesture_name_list)
        turn_winner = check_turn_winner(player_one_choice, player_two_choice)
        if turn_winner == 1:
            player_one.wins += 1
        elif turn_winner == 2:
            player_two.wins += 1
        else:
            # increment max counter to accommodate for tie rounds
            max_counter += 1
        # Check for end of game
        if player_one.wins == 3 or player_two.wins == 3:
            winner_exists = True
        # increment counter
        counter += 1
    # Declare/show winner
    declare_winner(player_one, player_two, opponent_type)
Esempio n. 5
0
 def main(self):
     """Main game loop."""
     while True:
         mode = self.menu()
         if mode == 's':
             self.play(player1=Player(), player2=ComputerPlayer())
         elif mode == 'm':
             self.play(player1=Player(), player2=Player())
         elif mode == 'd':
             self.play(player1=ComputerPlayer(), player2=ComputerPlayer())
         elif mode == 'l':
             self.load_game()
         elif mode == 'i':
             self.instructions()
         elif mode == 'o':
             self.options()
         elif mode == 'q':
             self.quit()
Esempio n. 6
0
def computer_player_game():
    computer_points = 0
    player_points = 0
    cp = ComputerPlayer(ComputerPlayer.ALGORITHM_GREEDY_CODE)
    counter = 0
    print(board)

    while counter < board_dimension * board_dimension:
        if counter % 2 != 0:
            inp = input(menu).split(" ")
            (x, y) = (int(inp[0]), int(inp[1]))
            if board.get_position(x, y) == 1:
                print(
                    "This position is already taken! Choose something different. "
                )
                continue
            points = board.insert_pos(int(x), int(y))
            print("player gets: " + str(points))
            player_points += points
            board.player_points = player_points
        else:
            print("Please wait. The computer is calculating next move...")
            (x, y) = cp.get_move(board)
            print("computer chooses: (" + str(x) + "," + str(y) + ")")
            points = board.insert_pos(x, y)
            computer_points += points
            board.computer_points = computer_points
            print("computer gets: " + str(points))

        av_pos = board.get_available_positions()
        print("available positions: ")
        print(str(av_pos))
        counter += 1
        print(board)
        print("P: " + str(player_points))
        print("C: " + str(computer_points))

    finish_game(computer_points, player_points)
Esempio n. 7
0
def minmax_greedy_game():
    greedy_points = 0
    minmax_points = 0
    greedy_player = ComputerPlayer(ComputerPlayer.ALGORITHM_GREEDY_CODE)
    minmax_player = ComputerPlayer(ComputerPlayer.ALGORITHM_MINMAX_CODE)
    counter = 0
    print(board)

    while counter < board_dimension * board_dimension:
        if counter % 2 != 0:
            # greedy_move
            print("GREEDY MOVE:")
            (x, y) = greedy_player.get_move(board)
            print("greedy chooses: (" + str(x) + "," + str(y) + ")")
            points = board.insert_pos(x, y)
            greedy_points += points
            print("greedy gets: " + str(points))
        else:
            print("MINMAX MOVE:")
            (x, y) = minmax_player.get_move(board)
            print("minmax chooses: (" + str(x) + "," + str(y) + ")")
            points = board.insert_pos(x, y)
            minmax_points += points
            print("minmax gets: " + str(points))

        counter += 1
        print(board)
        print("GREEDY: " + str(greedy_points))
        print("MINMAX: " + str(minmax_points))

    print("GAME OVER!")
    print("GREEDY POINTS: " + str(greedy_points))
    print("MINMAX POINTS: " + str(minmax_points))
    if minmax_points > greedy_points:
        print("MINMAX WINS!")
    else:
        print("GREEDY WINS!")
Esempio n. 8
0
    def addComputer(gs):
        name = gs.getComputerName()
        c = ComputerPlayer(name)
        gs.addPlayer(c)

        return gs
    def __init__(self, screen, maze):
        self.maze = Maze(maze)
        self.mazeColumns = 0
        self.mazeRows = 0
        self.mazeSpaces = 0
        self.playerID = 0
        self.computerIDs = []
        self.players = []
        self.threads = []
        self.lock = threading.RLock()
        self.isComplete = False
        self.usingScreen = False
        self.screen = screen
        self.player = Player(0)
        self.computer = ComputerPlayer(1)

        curses.curs_set(0)
        curses.start_color()
        ### No Backgrounds ###
        curses.init_pair(1, 15, curses.COLOR_BLACK)  # white
        curses.init_pair(2, 7, curses.COLOR_BLACK)  # gray
        curses.init_pair(3, 8, curses.COLOR_BLACK)  # dark gray
        curses.init_pair(4, 9, curses.COLOR_BLACK)  # red
        curses.init_pair(5, 11, curses.COLOR_BLACK)  # yellow
        curses.init_pair(6, 10, curses.COLOR_BLACK)  # green
        curses.init_pair(7, 12, curses.COLOR_BLACK)  # blue
        curses.init_pair(8, 14, curses.COLOR_BLACK)  # cyan
        curses.init_pair(9, 13, curses.COLOR_BLACK)  # purple
        ### Blue ###
        curses.init_pair(10, 15, curses.COLOR_BLUE)  # white
        curses.init_pair(11, 10, curses.COLOR_BLUE)  # green
        curses.init_pair(12, 9, curses.COLOR_BLUE)  # red
        curses.init_pair(13, 11, curses.COLOR_BLUE)  # yellow

        self.CURSES_COLOR_DICT = {
            'white': {
                None: curses.color_pair(1),
                'blue': curses.color_pair(10)
            },
            'gray': {
                None: curses.color_pair(2)
            },
            'dark gray': {
                None: curses.color_pair(3)
            },
            'red': {
                None: curses.color_pair(4),
                'blue': curses.color_pair(12)
            },
            'yellow': {
                None: curses.color_pair(5),
                'blue': curses.color_pair(13)
            },
            'green': {
                None: curses.color_pair(6),
                'blue': curses.color_pair(11)
            },
            'blue': {
                None: curses.color_pair(7)
            },
            'cyan': {
                None: curses.color_pair(8)
            },
            'purple': {
                None: curses.color_pair(9)
            },
            None: {
                'blue': curses.color_pair(10)
            },
        }
Esempio n. 10
0
class Main(QWidget):
    def __init__(self, game):
        super().__init__()
        self.game_done = False
        self.grid = QGridLayout()
        self.buttons = [['' for x in range(3)] for y in range(3)]
        self.game = game
        self.computer = ComputerPlayer(game, 'O')
        self.initUI()

        game.set_game_changed_callback(
            lambda current_position: self.update_ui(current_position))
        game.set_game_won_callback(lambda winner: self.announce_winner(winner))

    def initUI(self):
        self.setLayout(self.grid)

        self.add_button(0, 0)
        self.add_button(0, 1)
        self.add_button(0, 2)
        self.add_button(1, 0)
        self.add_button(1, 1)
        self.add_button(1, 2)
        self.add_button(2, 0)
        self.add_button(2, 1)
        self.add_button(2, 2)

        restart_button = QPushButton("Restart Game")
        restart_button.clicked.connect(lambda: self.restart_game())
        self.grid.addWidget(restart_button, 3, 0, 1, 3)

        self.move(300, 150)
        self.setWindowTitle('Py Tic Tac Toe')
        self.show()

    def update_ui(self, current_position):
        for x in range(len(current_position)):
            for y in range(len(current_position[x])):
                self.buttons[x][y].setText(current_position[x][y])

    def add_button(self, x, y):
        button = self.create_button(x, y)
        self.buttons[x][y] = button
        self.grid.addWidget(button, x, y)

    def create_button(self, x, y):
        button = QPushButton("")
        button.setFixedSize(QSize(100, 100))
        button.clicked.connect(lambda: self.make_player_move(x, y))

        return button

    def make_player_move(self, x, y):
        if self.buttons[x][y].text() == '':
            self.game.play(x, y)
            if not self.game_done:
                self.computer.make_play()

    def restart_game(self):
        self.game.restart()
        self.game_done = False

    def announce_winner(self, winner):
        self.game_done = True
        msg = QMessageBox(self)
        msg.setStandardButtons(QMessageBox.Ok)
        msg.setWindowTitle("Game Done!")

        if winner == '':
            msg.setText("It was a Draw!")
        else:
            msg.setText("The winner was " + winner + "!")

        msg.exec_()
Esempio n. 11
0
class TicTacToe:

    # The game initialization
    def __init__(self, game_number, file_name=None):
        self.winner = 0  # The winner
        self.board_size = 3  # The board size
        self.game_number = game_number  # The game number
        self.game_board = GameBoard(self.board_size)  # Board creation
        self.file_name = file_name

        # Computer Player move - easy bot
        if game_number == 1:
            self.computer_player = ComputerPlayer()  # The Computer Player
        # Computer Player move - strong bot
        elif game_number == 2:
            self.player_list = []
            self.player_list.append(PlayerQRL(1, 0.1, 0.9, 0.7, game_number,
                                              1))  # The QRL Computer Player

            # Load saved players data:
            load_players_stats(self.player_list, file_name)

        elif game_number == 3:
            self.player_list = []

            # Add 1st Player:
            self.player_list.append(ComputerPlayer())

            # Add 2nd Player:
            self.player_list.append(ComputerPlayer())

            # Load saved players data:
            load_players_stats(self.player_list, file_name)

        elif game_number == 4:
            self.player_list = []

            # Add 1st Player:
            # Parameters: mark, learning rate, discount, exploration rate
            self.player_list.append(PlayerQRL(1, 0.1, 0.9, 0.7, game_number,
                                              1))

            # Add 2nd Player:
            self.player_list.append(ComputerPlayer())

            # Load saved players data:
            load_players_stats(self.player_list, file_name)

        elif game_number == 5:
            self.player_list = []

            # Add 1st Player:
            # Parameters: mark, learning rate, discount, exploration rate
            self.player_list.append(
                PlayerQRL(-1, 0.1, 0.9, 0.7, game_number, 1))

            # Add 2nd Player:
            self.player_list.append(PlayerQRL(1, 0.1, 0.9, 0.7, game_number,
                                              1))

            # Load saved players data:
            load_players_stats(self.player_list, file_name)

    # The game running
    def run_game(self):
        while True:
            if self.game_number == 1 or self.game_number == 2:
                print("(Input format: '11')")
                print("Your move:")
                move_input_raw = input()
                print(move_input_raw)

                if self.game_number == 1 or 2:
                    if self.check_input_format(move_input_raw):
                        human_move = (int(move_input_raw[0]),
                                      int(move_input_raw[1]))

                        if self.check_input_range(human_move):
                            if self.check_next_move(human_move):
                                self.game_board.set_pawn(
                                    human_move[0], human_move[1], 1)

                                # Check if winner
                                if self.validate(-1, 1):
                                    if self.winner == 3:
                                        print("It is a Tie!")
                                    else:
                                        print("The winner is: {}".format(
                                            self.winner))

                                    if self.game_number == 2:
                                        # Update Player Q-Table
                                        self.player_list[0].update(self.winner)
                                        # Print player statistics
                                        # print_game_stats(board, player_list, game_number)

                                        # Save players statistics into separate '.txt' file
                                        save_players_stats(
                                            [self.player_list[0]], 'training')

                                        # Export data to text file
                                        export_data_to_text_file(
                                            [self.player_list[0]], 'training')
                                    break

                                #  Check if tie
                                if not self.check_if_board_is_full:
                                    if self.validate(-1, 1):
                                        print("The winner is: {}".format(
                                            self.winner))
                                    break

                                # Computer Player move
                                if self.game_number == 1:
                                    while True:
                                        computer_move = self.computer_player.set_pawn(
                                            self.game_board)
                                        if self.check_next_move(computer_move):
                                            self.game_board.set_pawn(
                                                computer_move[0],
                                                computer_move[1], -1)
                                            break

                                if self.game_number == 2:
                                    computer_move = self.player_list[
                                        0].set_pawn(self.game_board)

                                    if self.check_next_move(computer_move):
                                        self.game_board.set_pawn(
                                            computer_move[0], computer_move[1],
                                            -1)

                                # Check if winner
                                if self.validate(-1, 1):
                                    print(self.game_board.get())
                                    if self.winner == 3:
                                        print("It is a Tie!")
                                    else:
                                        print("The winner is: {}".format(
                                            self.winner))
                                    break
                            else:
                                print(
                                    "Position taken! Please choose empty field."
                                )
                        else:
                            print("Wrong move. Try again.")
                            continue

                        print(self.game_board)
                    else:
                        print("Wrong move. Try again.")

            elif self.game_number == 3:
                while True:
                    easy_bot_move = self.player_list[1].set_pawn(
                        self.game_board)
                    if self.check_next_move(easy_bot_move):
                        self.game_board.set_pawn(easy_bot_move[0],
                                                 easy_bot_move[1], -1)
                        break

                # Check if winner
                if self.validate(-1, 1):

                    # Save players statistics into separate '.txt' file
                    save_players_stats(self.player_list, self.file_name)

                    # Export data to text file
                    export_data_to_text_file(self.player_list, self.file_name)

                    return self.winner

                while True:
                    easy_bot_2_move = self.player_list[0].set_pawn(
                        self.game_board)
                    if self.check_next_move(easy_bot_2_move):
                        self.game_board.set_pawn(easy_bot_2_move[0],
                                                 easy_bot_2_move[1], 1)
                        break

                # Check if winner
                if self.validate(-1, 1):

                    # Save players statistics into separate '.txt' file
                    save_players_stats(self.player_list, self.file_name)

                    # Export data to text file
                    export_data_to_text_file(self.player_list, self.file_name)

                    return self.winner

            elif self.game_number == 4:
                while True:
                    easy_bot_move = self.player_list[1].set_pawn(
                        self.game_board)
                    if self.check_next_move(easy_bot_move):
                        self.game_board.set_pawn(easy_bot_move[0],
                                                 easy_bot_move[1], -1)
                        break

                # Check if winner
                if self.validate(-1, 1):
                    #print(self.game_board.get())
                    #print("The winner is: {}".format(self.winner))

                    # Update QRLPlayer Q-Table
                    self.player_list[0].update(self.winner)

                    # Save players statistics into separate '.txt' file
                    save_players_stats(self.player_list, self.file_name)

                    # Export data to text file
                    export_data_to_text_file(self.player_list, self.file_name)

                    return self.winner

                learning_bot_move = self.player_list[0].set_pawn(
                    self.game_board)
                #print(learning_bot_move)
                if self.check_next_move(learning_bot_move):
                    self.game_board.set_pawn(learning_bot_move[0],
                                             learning_bot_move[1], 1)

                # Check if winner
                if self.validate(-1, 1):
                    #print(self.game_board.get())
                    #print("The winner is: {}".format(self.winner))

                    # Update QRLPlayer Q-Table
                    self.player_list[0].update(self.winner)

                    # Save players statistics into separate '.txt' file
                    save_players_stats(self.player_list, self.file_name)

                    # Export data to text file
                    export_data_to_text_file(self.player_list, self.file_name)

                    return self.winner

            elif self.game_number == 5:
                learning_bot_move = self.player_list[0].set_pawn(
                    self.game_board)
                # print(learning_bot_move)
                if self.check_next_move(learning_bot_move):
                    self.game_board.set_pawn(learning_bot_move[0],
                                             learning_bot_move[1], -1)

                # Check if winner
                if self.validate(-1, 1):
                    #print(self.game_board.get())
                    #print("The winner is: {}".format(self.winner))

                    # Update QRLPlayer Q-Table
                    self.player_list[0].update(self.winner)
                    self.player_list[1].update(self.winner)

                    # Save players statistics into separate '.txt' file
                    save_players_stats(self.player_list, self.file_name)

                    # Export data to text file
                    export_data_to_text_file(self.player_list, self.file_name)

                    return self.winner

                learning_bot_1_move = self.player_list[1].set_pawn(
                    self.game_board)
                #print(learning_bot_move)
                if self.check_next_move(learning_bot_1_move):
                    self.game_board.set_pawn(learning_bot_1_move[0],
                                             learning_bot_1_move[1], 1)

                # Check if winner
                if self.validate(-1, 1):
                    #print(self.game_board.get())
                    #print("The winner is: {}".format(self.winner))

                    # Update QRLPlayer Q-Table
                    self.player_list[0].update(self.winner)
                    self.player_list[1].update(self.winner)

                    # Save players statistics into separate '.txt' file
                    save_players_stats(self.player_list, self.file_name)

                    # Export data to text file
                    export_data_to_text_file(self.player_list, self.file_name)

                    return self.winner

    # Checking input format
    def check_input_format(self, input_data):
        return True if len(input_data) == 2 else False

    # Checking move range
    def check_input_range(self, move):
        return True if self.board_size > move[
            0] >= 0 and self.board_size > move[1] >= 0 else False

    # Checking game board field status for the next move
    def check_next_move(self, move):
        return True if self.game_board.get_value(move[0],
                                                 move[1]) == 0 else False

    # Checking if board is full
    def check_if_board_is_full(self):
        return True if 0 in self.game_board.get() else False

    def check_columns(self, player):
        # Column are rows in the transposed list
        for column in zip(*self.game_board.get()):
            if abs(self.count_character(player, column)) == 3:
                return player
            if abs(self.count_character(player, column)) == 3:
                return player

        return False

    def check_rows(self, player):
        for row in self.game_board.get():
            if abs(self.count_character(player, row)) == 3:
                return player
            if abs(self.count_character(player, row)) == 3:
                return player

        return False

    def check_diagonals(self, player):
        # Wins if there is only one type of value in the first diagonal
        # (Numpy diag returns values on diagonal of the array).
        if abs(self.count_character(player,
                                    np.diag(self.game_board.get()))) == 3:
            return player
        if abs(self.count_character(player,
                                    np.diag(self.game_board.get()))) == 3:
            return player

        # Wins if there is only one type of value in the second diagonal (Numpy diag returns values of diagonal
        # - Numpy fliplr changes values from left to right of the array).
        if abs(
                self.count_character(player,
                                     np.diag(np.fliplr(
                                         self.game_board.get())))) == 3:
            return player
        if abs(
                self.count_character(player,
                                     np.diag(np.fliplr(
                                         self.game_board.get())))) == 3:
            return player

        return False

    # Winner finding
    def validate(self, player_1, player_2):

        if self.check_columns(player_1):
            self.winner = player_1
            return True

        if self.check_columns(player_2):
            self.winner = player_2
            return True

        if self.check_rows(player_1):
            self.winner = player_1
            return True

        if self.check_rows(player_2):
            self.winner = player_2
            return True

        if self.check_diagonals(player_1):
            self.winner = player_1
            return True

        if self.check_diagonals(player_2):
            self.winner = player_2
            return True

        counter = 0
        for row in self.game_board.get():
            for value in row:
                if value == 0:
                    counter = counter + 1
        if counter == 0:
            self.winner = 3
            return True

    # Count character in the word
    def count_character(self, character, word):
        return sum(character for word_character in word
                   if character == word_character)

    def set_pawn(self, position_x, position_y, pawn):
        if not self.is_valid_move(position_x, position_y):
            raise Exception("Pawn not valid position.")
        self.game_board.get()[position_x][position_y] = pawn

    def is_valid_move(self, position_x, position_y):
        return False if int(
            self.game_board.get()[position_x][position_y]) == 1 or int(
                self.game_board.get()[position_x][position_y]) == 2 else True

    def has_next_move(self):
        return np.any(self.game_board.get())
class Game():
    HUMAN = 0
    COMPUTER = 1
    LEGAL_INPUT = (ord('k'), ord(' '), ord('q'), ord('w'), ord('a'), ord('s'),
                   ord('d'), curses.KEY_UP, curses.KEY_RIGHT, curses.KEY_DOWN,
                   curses.KEY_LEFT)

    def __init__(self, screen, maze):
        self.maze = Maze(maze)
        self.mazeColumns = 0
        self.mazeRows = 0
        self.mazeSpaces = 0
        self.playerID = 0
        self.computerIDs = []
        self.players = []
        self.threads = []
        self.lock = threading.RLock()
        self.isComplete = False
        self.usingScreen = False
        self.screen = screen
        self.player = Player(0)
        self.computer = ComputerPlayer(1)

        curses.curs_set(0)
        curses.start_color()
        ### No Backgrounds ###
        curses.init_pair(1, 15, curses.COLOR_BLACK)  # white
        curses.init_pair(2, 7, curses.COLOR_BLACK)  # gray
        curses.init_pair(3, 8, curses.COLOR_BLACK)  # dark gray
        curses.init_pair(4, 9, curses.COLOR_BLACK)  # red
        curses.init_pair(5, 11, curses.COLOR_BLACK)  # yellow
        curses.init_pair(6, 10, curses.COLOR_BLACK)  # green
        curses.init_pair(7, 12, curses.COLOR_BLACK)  # blue
        curses.init_pair(8, 14, curses.COLOR_BLACK)  # cyan
        curses.init_pair(9, 13, curses.COLOR_BLACK)  # purple
        ### Blue ###
        curses.init_pair(10, 15, curses.COLOR_BLUE)  # white
        curses.init_pair(11, 10, curses.COLOR_BLUE)  # green
        curses.init_pair(12, 9, curses.COLOR_BLUE)  # red
        curses.init_pair(13, 11, curses.COLOR_BLUE)  # yellow

        self.CURSES_COLOR_DICT = {
            'white': {
                None: curses.color_pair(1),
                'blue': curses.color_pair(10)
            },
            'gray': {
                None: curses.color_pair(2)
            },
            'dark gray': {
                None: curses.color_pair(3)
            },
            'red': {
                None: curses.color_pair(4),
                'blue': curses.color_pair(12)
            },
            'yellow': {
                None: curses.color_pair(5),
                'blue': curses.color_pair(13)
            },
            'green': {
                None: curses.color_pair(6),
                'blue': curses.color_pair(11)
            },
            'blue': {
                None: curses.color_pair(7)
            },
            'cyan': {
                None: curses.color_pair(8)
            },
            'purple': {
                None: curses.color_pair(9)
            },
            None: {
                'blue': curses.color_pair(10)
            },
        }

    def waitForInput(self, pType):
        while not self.isComplete:
            if pType == Game.COMPUTER:
                idList = list(self.computer.getActiveSpriteIDs())
                for idNum in idList:
                    if not self.isComplete:
                        command = self.computer.think(idNum, self.maze)
                        if command is None:
                            continue
                        else:
                            self.makeRequest(idNum, command)

            elif pType == Game.HUMAN:
                command = self.recievePlayerInput()
                if command in Game.LEGAL_INPUT:
                    if command == ord('q'):
                        self.isComplete = True
                        return
                    self.makeRequest(self.player.getSpriteID(), command)

    def makeRequest(self, idNum, command):
        self.lock.acquire()

        changes = self.maze.request(idNum, command)

        if changes is not None:

            if 'update' in changes.keys():
                self.updateScreen(changes['update'])
            if 'computer sprite' in changes.keys():
                self.computer.setActiveSpriteIDs(
                    list(self.maze.getComputerActiveSprites()))
            if 'gameover' in changes.keys():
                self.isComplete = True

        self.lock.release()

    def recievePlayerInput(self):
        while not self.isComplete:
            k = self.screen.getch()
            return k

    def updateScreen(self, changes):
        self.lock.acquire()
        for change in changes:
            if change is not None:
                spriteInformation = self.maze.getSpace(change)
                self.screen.addstr(
                    change // self.mazeColumns, change % self.mazeColumns,
                    spriteInformation[0], self.CURSES_COLOR_DICT[
                        spriteInformation[1]][spriteInformation[2]])
        self.screen.move(self.mazeRows, 0)
        self.screen.clrtobot()
        self.screen.addstr(
            self.mazeRows, 0, "Comp Sprite IDs: {}".format(
                str(self.computer.getActiveSpriteIDs())))
        self.screen.addstr(
            self.mazeRows + 1, 0,
            "Player Sprite ID: {}".format(str(self.player.getSpriteID())))
        self.screen.refresh()
        self.lock.release()

    def drawEntireMaze(self):
        for i in range(self.mazeSpaces):
            spriteInformation = self.maze.getSpace(i)
            self.screen.addstr(
                i // self.mazeColumns, i % self.mazeColumns,
                spriteInformation[0], self.CURSES_COLOR_DICT[
                    spriteInformation[1]][spriteInformation[2]])
        self.screen.refresh()

    def initializeMaze(self):
        self.mazeColumns = self.maze.getColumns()
        self.mazeRows = self.maze.getRows()
        self.mazeSpaces = self.maze.getTotalSpaces()

        playerID = self.maze.getPlayerSpriteID()
        computerIDs = list(self.maze.getComputerActiveSprites())

        self.player.setSpriteID(playerID)
        self.computer.setActiveSpriteIDs(computerIDs)

    def createThreads(self):
        self.threads = []
        humanThread = threading.Thread(target=self.waitForInput,
                                       args=(Game.HUMAN, ))
        computerThread = threading.Thread(target=self.waitForInput,
                                          args=(Game.COMPUTER, ))
        self.threads.append(humanThread)
        self.threads.append(computerThread)

    def play(self):
        self.screen.clear()
        self.screen.refresh()
        self.initializeMaze()
        self.createThreads()
        self.drawEntireMaze()
        for t in self.threads:
            t.start()
        for t in self.threads:
            t.join()
Esempio n. 13
0
 def get_player_type(self, factory_type, name):
     if factory_type == 'human':
         return Player(name, factory_type)
     if factory_type == 'computer':
         return ComputerPlayer(name, factory_type)
Esempio n. 14
0
def create_cpu(cpu_number):
    return ComputerPlayer(f'CPU {cpu_number}')
Esempio n. 15
0
					playing_area.bounding_box.y + paddle_y_offset,
					paddle_tile.width,
					playing_area.bounding_box.height - 2 * paddle_y_offset),
				paddle_tile),
			Paddle(
				[playing_area.bounding_box.max_x - 1 - paddle_x_offset - paddle_tile.width // 2, -1],
				0,
				Box(
					playing_area.bounding_box.max_x - 1 - paddle_x_offset - paddle_tile.width,
					playing_area.bounding_box.y + paddle_y_offset,
					paddle_tile.width,
					playing_area.bounding_box.height - 2 * paddle_y_offset),
				paddle_tile)]

		players = [
			ComputerPlayer(paddles[0], max_speed = paddle_speed, difficulty = 0.1),
			SampledPlayer(
				I2cJoystickPlayer(paddles[1], usb.i2c.slave(0x52), 1, -128, paddle_speed / 128),
				interval = 0.01),
		]

		game = GameLoop(
			playing_area,
			Ball(
				playing_area.centre,
				[1.8, 0],
				playing_area.bounding_box,
				Tile(6, 6, [
					0b00110000,
					0b01111000,
					0b11111100,
Esempio n. 16
0
def main(main_menu):
    """Main function for the game."""

    pygame.init()

    # Initiate the playing board as a dictionary. Looks as follows:
    # "one" | "two" | "three"
    # ------------
    # "four" | "five" | "six"
    # ------------
    # "seven" | "eight" | "nine"
    # place_marker() sets the values as one of ["X", "O"] when a move has been
    # made.
    # the (0, 0) part in [False, (0, 0)] is the top left position of the square
    # in pixels. This is only used for placing the computer moves on the board.
    board = {
        1: [False, (0, 0)],
        2: [False, (110, 0)],
        3: [False, (210, 0)],
        4: [False, (0, 110)],
        5: [False, (110, 110)],
        6: [False, (210, 110)],
        7: [False, (0, 210)],
        8: [False, (110, 210)],
        9: [False, (210, 210)],
    }

    screen = pygame.display.set_mode((300, 300))
    pygame.display.set_caption("Tic-Tac-Toe")
    pygame.display.set_icon(
        pygame.image.load(os.path.join(IMAGES_DIR, "game_icon.png")))
    background = load_image("board_grid.png")
    screen.blit(background, (0, 0))
    pygame.display.update()

    # Loads an image of "an X" symbol
    p1 = Player("X", load_image("player1.png"))
    # Loads an image of "an O" symbol
    p2 = Player("O", load_image("player2.png"))

    # TODO: remake this so the computer player can be "X" or "O"
    # initiate the computer player
    p3 = ComputerPlayer("X", load_image("player1.png"))

    # Currently, selecting computer in the menu will give a really bad computer
    # player.
    if main_menu.mode == "computer":
        play_computer = True
    else:
        play_computer = False

    turn = 1
    running = True
    while running == True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return False

            if turn % 2 != 0 and play_computer:
                board_copy = copy.deepcopy(board)
                make_computer_move(screen, board_copy, p2, p3, turn)
                place_computer_marker(screen, board, p3)
                result = check_ended(board, p3)

                if result == True:
                    answer = game_end(p3.marker)
                    if answer:
                        return True
                    else:
                        return False
                elif result == "draw":
                    answer = game_end("draw")
                    if answer:
                        return True
                    else:
                        return False
                turn += 1

            if pygame.mouse.get_pressed() == (1, 0, 0):
                if turn % 2 != 0 and not play_computer:
                    active_player = p1
                else:
                    active_player = p2

                active_player.pos = pygame.mouse.get_pos()

                if place_marker(screen, board, active_player):
                    turn += 1
                    pygame.display.update()
                    result = check_ended(board, active_player)

                    if result == True:
                        answer = game_end(active_player.marker)
                        if answer:
                            return True
                        else:
                            return False
                    elif result == "draw":
                        answer = game_end("draw")
                        if answer:
                            return True
                        else:
                            return False

        pygame.display.update()
Esempio n. 17
0
 def create_player(player_str, player_marker, game_difficulty):
     if player_str == 'H':
         return HumanPlayer(player_marker)
     elif player_str == 'C':
         return ComputerPlayer(player_marker, game_difficulty)