예제 #1
0
def _kwargs_to_players(**kwargs):
    """Convert a game type string (e.g., 'computer-human') to actual players."""
    player_strings = kwargs['game_type'].split('-')

    players = []
    for idx, string in enumerate(player_strings):
        if string == 'human':
            player = HumanPlayer(_id=idx + 1)
        elif idx == 0 or not kwargs.get('difficulty2'):
            # If only one difficulty is specified, use it for all computer players.
            player = ComputerPlayer(
                _id=idx + 1,
                itermax=DIFFICULTY_TO_ITERMAX_MAP[kwargs['difficulty']],
                is_omniscient=(kwargs['difficulty'] == 'insane')
            )
        else:
            # If multiple difficulties are specified, use the second for the second computer player.
            player = ComputerPlayer(
                _id=idx + 1,
                itermax=DIFFICULTY_TO_ITERMAX_MAP[kwargs['difficulty2']],
                is_omniscient=(kwargs['difficulty2'] == 'insane')
            )
        players.append(player)

    return {idx + 1: player for idx, player in enumerate(players)}
예제 #2
0
    def __init__(self):

        self.mw = tkinter.Tk()
        self._board = []

        self.default_image = tkinter.PhotoImage(file="empty2.gif")

        self.default_image_r = tkinter.PhotoImage(file="Red2.gif")
        self.default_image_y = tkinter.PhotoImage(file="Yellow2.gif")

        self.size = 7
        self.buttons_2d_list = []
        for i in range(self.size):
            self.row = [' '] * self.size
            self.buttons_2d_list.append(self.row)

        self.gboard = GameBoard(6)

        p1 = ComputerPlayer(
            "Y", self.buttons_2d_list
        )  #no input required from user, p1 and p2 are computer players, with given colours
        p2 = ComputerPlayer("R", self.buttons_2d_list)

        print("\tCLCIK ON ANY BUTTON ON THE GRID TO START"
              )  #the user must click on any button to start the sim

        self.players_lst = (p1, p2)
        self.currnt_player_index = 0
        self.winner = False
예제 #3
0
파일: test.py 프로젝트: cbw36/Tic-Tac-Toe
    def test_alternate_letters(self):
        # Test that alternate from X to O correctly
        letter = ComputerPlayer.alternate_letters("X")
        self.assertEqual(letter, "O", "X did not alternate to O")

        # Test that alternate from O to X correctly
        letter = ComputerPlayer.alternate_letters("O")
        self.assertEqual(letter, "X", "O did not alternate to X")
예제 #4
0
    def __init__(self):

        self.mw = tkinter.Tk(
        )  #assigning the GUI method Tk to variable self.mw

        # default image = black hole/empty space
        self.default_image = tkinter.PhotoImage(
            file="empty2.gif"
        )  #all buttons will start with this deafult image when game starts and need to make instance so tkinter does keeps image
        # red and yellow represent the disc colours
        self.default_image_r = tkinter.PhotoImage(
            file="Red2.gif"
        )  #IMPORTANT TO MAKE INSTANCE OF ALL IMAGES IN __INIT__ METHOD TO PREVENT IMAGES FROM DISAPPAERING
        self.default_image_y = tkinter.PhotoImage(file="Yellow2.gif")

        self.size = 7
        self.buttons_2d_list = []
        for i in range(self.size):
            self.row = [' '] * self.size
            self.buttons_2d_list.append(
                self.row
            )  #creating a button list in order to configure mechanics of the game nad game GUI

        self.gboard = GameBoard(6)  #gameboard reference

        print("\tYELLOW or RED")
        colour = input("Please Select Your Colour(y/r): "
                       )  #giving user option to select colour
        colour = colour.lower()
        if colour == "y":
            p1 = HumanPlayer("Y")  #assigning colours to variables p1 and p2
            p2 = ComputerPlayer("R", self.buttons_2d_list)
            opnt = input("\t Do you want to play against a computer(y/n)? ")
            if opnt == "y":
                p2 = ComputerPlayer("R", self.buttons_2d_list)

            else:
                p2 = HumanPlayer("R")

        else:
            p1 = HumanPlayer("R")
            p2 = ComputerPlayer("Y", self.buttons_2d_list)
            opnt = input("\t Do you want to play against a computer(y/n)? ")
            if opnt == "y":
                p2 = ComputerPlayer("Y", self.buttons_2d_list)

            else:
                p2 = HumanPlayer("Y")

        self.players_lst = (p1, p2)  # creating a list of the players
        self.currnt_player_index = 0  #initilise the current player to zero
        self.winner = False  #initilise winner to false
예제 #5
0
    def __init__(self):

        self.mw = tkinter.Tk()
        self._board = []

        self.default_image = tkinter.PhotoImage(file="empty2.gif")
        self.default_image_2 = tkinter.PhotoImage(
            file="empty3.gif"
        )  #instead of using the same images, as used in the standard board.
        #I had to reduce the size of the images in order to fit the window of the larger

        self.default_image_r = tkinter.PhotoImage(
            file="Red2.gif")  # I created another set of images
        self.default_image_r_2 = tkinter.PhotoImage(file="Red3.gif")
        self.default_image_y_2 = tkinter.PhotoImage(file="Yellow3.gif")
        self.default_image_y = tkinter.PhotoImage(file="Yellow2.gif")

        self.size = 7 + 2
        self.buttons_2d_list = []
        for i in range(self.size):
            self.row = [' '] * self.size
            self.buttons_2d_list.append(self.row)

        self.gboard = Large_gameboard(6 + 2)  #calling the largest gameboard

        print("\tYELLOW or RED")
        colour = input("Please Select Your Colour(y/r): ")
        colour = colour.lower()
        if colour == "y":
            p1 = HumanPlayer("Y")
            p2 = ComputerPlayer("R", self.buttons_2d_list)
            opnt = input("\t Do you want to play against a computer(y/n)? ")
            if opnt == "y":
                p2 = ComputerPlayer("R", self.buttons_2d_list)

            else:
                p2 = HumanPlayer("R")

        else:
            p1 = HumanPlayer("R")
            p2 = ComputerPlayer("Y", self.buttons_2d_list)
            opnt = input("\t Do you want to play against a computer(y/n)? ")
            if opnt == "y":
                p2 = ComputerPlayer("R", self.buttons_2d_list)

            else:
                p2 = HumanPlayer("Y")

        self.players_lst = (p1, p2)
        self.currnt_player_index = 0
        self.winner = False
예제 #6
0
def human_vs_computer_mode(difficulty):
    """
    To start the game in which a human plays against the computer.

    Paramters:
    difficulty(int) -  0 if the level of difficulty should be easy, and 1 if the level should be hard.

    Returns:
    string - The value returned by the play() method.

    """
    game = TicTacToe()
    x_player = HumanPlayer("X")
    o_player = ComputerPlayer("O") if difficulty == 0 else ComputerPlayer(
        "O", smart=True)

    return play(game, x_player, o_player)
예제 #7
0
    def test_computer_player(self):
        game_board = GameBoard()
        computerplayer = ComputerPlayer("Computer",game_board,1)
        name = computerplayer.name

        # Set first two cells and should return last cell
        game_board.set_cell(1,4)
        game_board.set_cell(2,4)

        cell_list = [1,2,3]

        cell = computerplayer.get_best_empty_cell(cell_list)
        self.assertEquals(cell,3)

        # Set last two cells and should return first cell
        game_board.set_cell(5,4)
        game_board.set_cell(6,4)

        cell_list = [4,5,6]

        cell = computerplayer.get_best_empty_cell(cell_list)
        self.assertEquals(cell,4)
예제 #8
0
    def __init__(self):

        self.mw = tkinter.Tk()

        self.default_image = tkinter.PhotoImage(file="empty2.gif")

        self.default_image_r = tkinter.PhotoImage(file="Red2.gif")
        self.default_image_y = tkinter.PhotoImage(file="Yellow2.gif")

        self.size = 7
        self.buttons_2d_list = []
        for i in range(self.size):
            self.row = [' '] * self.size
            self.buttons_2d_list.append(self.row)

        self.gboard = GameBoard(6)
        d = input(
            "\nSelect Difficulty: Easy(e) - Medium (default)(m) - Advanced (a) > "
        )  # giving the user the option to slect between 3 difficulties
        d = d.lower()

        print("\tYELLOW or RED")
        colour = input(
            "Please Select Your Colour(y/r) : "
        )  #no need to ask user if they want to play aginst computer
        colour = colour.lower()
        if colour == "y":
            p1 = HumanPlayer("Y")
            p2 = ComputerPlayer("R", self.buttons_2d_list)

        else:

            p1 = HumanPlayer("R")
            p2 = ComputerPlayer("Y", self.buttons_2d_list)

        self.difficulty = d  #assigning the input given to the variable 'd' to self.difficulty
        self.players_lst = (p1, p2)
        self.currnt_player_index = 0
        self.winner = False
예제 #9
0
    def get_players(name_1=None, name_2=None):
        """
        Create the two players as Player instances.
        Players are either HumanPlayer or ComputerPlayer depending on their name
        """
        if name_1 is None:
            name_1 = input(
                "Please enter the name of player 1. For a computer player, enter cpu: "
            )
        if name_1 == "cpu":
            player_1 = ComputerPlayer(0, name_1, "X")
        else:
            player_1 = HumanPlayer(0, name_1, "X")

        if name_2 is None:
            name_2 = input(
                "Please enter the name of player 2. For a computer player, enter cpu: "
            )
        if name_2 == "cpu":
            player_2 = ComputerPlayer(1, name_2, "O")
        else:
            player_2 = HumanPlayer(1, name_2, "O")

        return [player_1, player_2]
 def set_players(self, line_info, is_human=True):
     player_type = 'human' if is_human else 'computer'
     info_items = line_info.split('|')
     # First item is number of players, remaining items are player names
     num_players = int(info_items[0].strip())
     i = 1
     try:
         while i < num_players + 1:
             if info_items[i]:
                 player_name = info_items[i].strip()
                 if is_human:
                     self.players.append(HumanPlayer(player_name))
                 else:
                     self.players.append(ComputerPlayer(player_name))
                 # Track player color for visualization
                 if self.COLOR_COUNTER >= len(self.COLORS):
                     raise Exception(
                         'too many {} players have been declared'.format(
                             player_type))
                 self.player_colors[player_name] = self.COLORS[
                     self.COLOR_COUNTER]
                 self.COLOR_COUNTER += 1
                 i += 1
             else:
                 raise Exception(
                     'a {} player with no name has been declared'.format(
                         player_type))
     except IndexError:
         # Number of players indicated > number of names given
         raise Exception(
             '{} {} players were declared but only {} names were provided'.
             format(
                 num_players,
                 player_type,
                 i - 1,
             ))
     if i < len(info_items):
         # Number of players indicated < number of names given
         raise Exception(
             'only {} {} players were declared but {} names were provided'.
             format(
                 num_players,
                 player_type,
                 len(info_items) - 1,
             ))
예제 #11
0
파일: test.py 프로젝트: cbw36/Tic-Tac-Toe
    def test_evaluate_board(self):
        player = ComputerPlayer(0, "cpu", "X")

        # Check a win state
        win_board = [["X", "O", "-"], ["O", "X", "O"], ["-", "X", "X"]]
        value = player.evaluate_board(win_board, 2)
        self.assertEqual(value, WINNER,
                         "Didnt recognize a won board configuration")

        # Check a win state with a full board
        win_board = [["X", "O", "X"], ["O", "X", "O"], ["O", "X", "X"]]
        value = player.evaluate_board(win_board, 0)
        self.assertEqual(value, WINNER,
                         "Didnt recognize a won board configuration")

        # Check a loss state
        loss_board = [["-", "X", "O"], ["-", "O", "X"], ["O", "X", "-"]]
        value = player.evaluate_board(loss_board, 3)
        self.assertEqual(value, LOSER,
                         "Didnt recognize a lost board configuration")

        # Check a loss state with full board
        loss_board = [["X", "X", "O"], ["O", "O", "X"], ["O", "X", "X"]]
        value = player.evaluate_board(loss_board, 0)
        self.assertEqual(value, LOSER,
                         "Didnt recognize a lost board configuration")

        # Check a tie state
        tie_board = [["X", "X", "O"], ["O", "O", "X"], ["X", "O", "X"]]
        value = player.evaluate_board(tie_board, 0)
        self.assertEqual(value, TIED,
                         "Didnt recognize a tied board configuration")

        # Check an in progress state
        in_progress_board = [["X", "X", "O"], ["O", "X", "X"], ["X", "O", "-"]]
        value = player.evaluate_board(in_progress_board, 1)
        self.assertEqual(value, IN_PROGRESS,
                         "Didnt recognize an in progress board configuration")
예제 #12
0
    def test_computer_player(self):
        game_board = GameBoard()
        computerplayer = ComputerPlayer("Computer",game_board,1)
        name = computerplayer.name

        # Test name was set
        self.assertEqual(name,"Computer")

        # Test board is instance of GameBoard
        self.assertIsInstance(computerplayer.game_board,GameBoard)
        # Test player (id of 1) has marker value of 4
        self.assertEquals(computerplayer.marker_value, 4)
        # Make the first move
        computerplayer.make_move()
        self.assertFalse(game_board.is_cell_empty(5))
        # Make the another move
        computerplayer.make_move()
        self.assertFalse(game_board.is_cell_empty(1))
        # Make the third move
        computerplayer.make_move()
        self.assertFalse(game_board.is_cell_empty(9))
        self.assertTrue(game_board.check_for_win())
예제 #13
0
파일: test.py 프로젝트: cbw36/Tic-Tac-Toe
    def test_minimax(self):
        # Check if chooses move to win
        player = ComputerPlayer(0, "cpu", "X")
        board = [["X", "-", "O"], ["X", "-", "O"], ["-", "-", "-"]]
        depth = 5
        best_move = player.minimax(board=board,
                                   depth=depth,
                                   maximizing=True,
                                   letter=player.letter,
                                   alpha=-100,
                                   beta=100)
        self.assertEqual(best_move, [2, 0, WINNER],
                         "Doesn't chose move that will win the game")

        # Checks if chooses move to prevent loss and win
        player = ComputerPlayer(0, "cpu", "X")
        board = [["-", "-", "X"], ["-", "O", "-"], ["X", "-", "O"]]
        depth = 5
        best_move = player.minimax(board=board,
                                   depth=depth,
                                   maximizing=True,
                                   letter=player.letter,
                                   alpha=-100,
                                   beta=100)
        row, col = best_move[0], best_move[1]
        self.assertEqual([row, col], [0, 0],
                         "Doesn't chose move that prevent a loss and win")

        # Checks if chooses move to prevent loss and tie
        player = ComputerPlayer(0, "cpu", "X")
        board = [["-", "-", "-"], ["-", "O", "X"], ["-", "X", "O"]]
        depth = 5
        best_move = player.minimax(board=board,
                                   depth=depth,
                                   maximizing=True,
                                   letter=player.letter,
                                   alpha=-100,
                                   beta=100)
        row, col = best_move[0], best_move[1]
        self.assertEqual([row, col], [0, 0],
                         "Doesn't chose move that prevent a loss")

        # Check if can see a few moves ahead and prevent opponent from forcing a victory
        player = ComputerPlayer(1, "cpu", "O")
        board = [["-", "-", "X"], ["-", "O", "-"], ["X", "-", "-"]]
        depth = 5
        best_move = player.minimax(board=board,
                                   depth=depth,
                                   maximizing=True,
                                   letter=player.letter,
                                   alpha=-100,
                                   beta=100)
        row, col = best_move[0], best_move[1]
        self.assertNotEqual(
            [row, col], [0, 0],
            "Chose move that allows opponent to force a victory")
        self.assertNotEqual(
            [row, col], [2, 2],
            "Chose move that allows opponent to force a victory")