Exemplo n.º 1
0
class GameTest(unittest.TestCase):
    def setUp(self):
        self.board = Board()
        self.player = Player("X", self.board, "Sys")
        self.computer = ComputerPlayer("O",self.board)
    def test_one_game(self):
        sys_moves = []
        print "Testing Player First"
        while self.board.winner == None:
            choice_made = False
            while not choice_made:
                choice = random.randrange(0, 9, 1)
                if choice not in sys_moves and self.board.get_cell(choice) == None:
                    sys_moves.append(choice)
                    choice_made = True
                    self.player.place_marker(choice)
                    if self.board.winner == None:
                        self.computer.place_marker()
        print "\n{0} is the winner with moves of {1} on board {2}\n".format(self.board.winner, sys_moves, self.board.grid )
        
    def test_one_game_computer_first(self):
        sys_moves = []
        print "Testing computer First"
        while self.board.winner == None:
            choice_made = False
            self.computer.place_marker()
            while not choice_made:
                choice = random.randrange(0, 9, 1)
                if choice not in sys_moves and self.board.get_cell(choice) == None:
                    sys_moves.append(choice)
                    choice_made = True
                    self.player.place_marker(choice)
                    #if self.board.winner == None:
                        
        print "\n{0} is the winner with moves of {1} on board {2}\n".format(self.board.winner, sys_moves, self.board.grid )
Exemplo n.º 2
0
 def test_EmptyBoard(self):
     # Niguem joga nenhuma posicao.
     # Todas as posicoes sao livres.
     board = Board()
     for row in range(3):
         for col in range(3):
             self.assertTrue(board.IsFree(row, col))
Exemplo n.º 3
0
def test_minimax():
    new_game = Game()
    new_board = Board()
    new_board.board = [["O", "O", "X"], ["X", "?", "O"], ["?", "?", "X"]]
    new_game.board = new_board
    new_game.player1 = Player(1, "Human", "O")
    new_game.player2 = Player(2, "Computer", "X")
    assert new_game.expert_ai(new_game.board, -math.inf, math.inf,
                              "X") == (1, 2, 1)
Exemplo n.º 4
0
def test_minimax_2():
    new_game = Game()
    new_board = Board()
    new_board.board = [["?", "O", "?"], ["X", "O", "?"], ["O", "X", "X"]]
    new_game.board = copy.deepcopy(new_board)
    new_game.player1 = Player(1, "Human", "O")
    new_game.player2 = Player(2, "Computer", "X")
    assert new_game.expert_ai(new_game.board, -math.inf, math.inf,
                              "X") == (0, 0, 2)
Exemplo n.º 5
0
 def test_PlayedPosition(self):
     # Um jogador vai jogar uma posicao... Teste se a mudansa foi feita no
     # tabuleiro. Repare que a valor do "player_id" nao importa.
     board = Board()
     player_id = "x"
     row = 2
     col = 1
     board.PlayPosition(row, col, player_id)
     self.assertTrue(board.HasPosition(row, col, player_id))
     self.assertFalse(board.IsFree(row, col))
Exemplo n.º 6
0
def test_minimax_3():
    new_game = Game()
    new_board = Board()
    new_board.board = [["?", "?", "?"], ["?", "O", "?"], ["X", "O", "X"]]
    new_game.board = new_board
    new_game.player1 = Player(1, "Human", "O")
    new_game.player2 = Player(2, "Computer", "X")
    new_game.current_turn = new_game.player2
    result = new_game.expert_ai(new_game.board, -math.inf, math.inf, "X")
    assert result[1] == 0
    assert result[2] == 1
Exemplo n.º 7
0
 def test_EscolheParaGanharComLinha(self):
     board = Board()
     player_id = "x"
     computer_player = ComputerPlayer(computer_id=player_id, human_id="o")
     # Set pattern:
     #  * | x | x       Expect (0, 0)
     # ---+---+---
     #    |   |
     # ---+---+---
     #    |   |
     board.PlayPosition(0, 1, player_id)
     board.PlayPosition(0, 2, player_id)
     computer_player.Play(board)
     self.assertTrue(board.HasPosition(0, 0, player_id))
     self.assertTrue(board.PlayerWon(player_id))
 def test_simple_draw(self):
     board = Board()
     board.reset_board()
     self.assertEqual(0, board.player_move(2,2,2))
     self.assertEqual(0, board.player_move(0,0,1))
     self.assertEqual(0, board.player_move(0,1,2))
     self.assertEqual(0, board.player_move(0,2,1))
     self.assertEqual(0, board.player_move(1,0,2))
     self.assertEqual(0, board.player_move(1,1,1))
     self.assertEqual(0, board.player_move(1,2,2))
     self.assertEqual(0, board.player_move(2,1,1))
     self.assertEqual(-1, board.player_move(2,0,2))
Exemplo n.º 9
0
def test_board():
    board = Board()
    board_length = len(board)
    
    assert board_length == 3
    for cell in board_length:
        assertEqual(len(cell),3)
Exemplo n.º 10
0
def next_move_and_result(player, board_string):
    new_board = Board()
    flat_board = board_string.split()
    board_array = [flat_board[0:3], flat_board[3:6], flat_board[6:9]]
    new_board.board = board_array
    new_game = Game()
    new_game.board = new_board
    new_game.player1 = Player(1, "Human", "O")
    new_game.player2 = Player(2, "Computer", "X")
    result, best_row, best_column = new_game.expert_ai(new_game.board, player)
    board_array[best_row][best_column] = "*"
    new_board_string = "\n    ".join(" ".join(row) for row in board_array)
    return """
    Position score: {}
    {}
    """.format(result, new_board_string)
Exemplo n.º 11
0
 def test_NaoDeixaOutroJogadorVencerComLinha(self):
     board = Board()
     player_id = "x"
     other_player_id = "o"
     computer_player = ComputerPlayer(computer_id=player_id,
                                      human_id=other_player_id)
     # Set pattern:
     #  * | o | o       Expect (0, 0) to be "x"
     # ---+---+---
     #    |   |
     # ---+---+---
     #    |   |
     board.PlayPosition(0, 1, other_player_id)
     board.PlayPosition(0, 2, other_player_id)
     computer_player.Play(board)
     self.assertTrue(board.HasPosition(0, 0, player_id))
Exemplo n.º 12
0
class GameLoadTestComputerFirst(unittest.TestCase):
    GAME_COUNT = 1000
    def setUp(self):
        self.board = Board()
        self.player = Player("X", self.board, "Sys")
        self.computer = ComputerPlayer("O",self.board)
        self.winners = {}
        self.moves = {}
        
    def play_game(self):
        sys_moves = []
        while self.board.winner == None:
            self.computer.place_marker()
            #print "Computer places Marker at {0}".format(self.board.last_cell)
            choice_made = False
            while not choice_made:
                choice = random.randrange(0, 9, 1)
                if choice not in sys_moves and self.board.get_cell(choice) == None:
                    sys_moves.append(choice)
                    choice_made = True
                    self.player.place_marker(choice)
                    #if self.board.winner == None:
                if self.board.full:
                    self.board.declare_cat()
                    choice_made = True
                    
            #print "Player places Marker at {0}".format(self.board.last_cell)
        
        winner = self.board.winner
        if winner in self.winners.keys():
            self.winners[winner] = self.winners[winner] + 1
        else:
            self.winners[winner] = 1
        if winner == "X":
            move = sys_moves.__str__()
            if move in self.moves.keys():
                self.moves[move] = self.moves[move] + 1
            else:
                self.moves[move] = 1
            
    def test_game_computer_first(self):
        print "Computer Will go first"
        for count in range(self.GAME_COUNT):
            self.play_game()
            self.board.clear()
        print "\n{0}".format(self.winners)
        print "\n{0}".format(self.moves)
Exemplo n.º 13
0
 def test_win_row1(self):
     board = Board()
     board.reset_board()
     self.assertEqual(0, board.player_move(0,0,1))
     self.assertEqual(0, board.player_move(1,0,2))
     self.assertEqual(0, board.player_move(0,1,1))
     self.assertEqual(0, board.player_move(1,1,2))
     self.assertEqual(1, board.player_move(0,2,1))
Exemplo n.º 14
0
 def test_StopsAfterNine(self):
     board = Board()
     player_one = MockCountingPlayer("x")
     player_two = MockCountingPlayer("o")
     game = GamePlay()
     game.TheGame(player_one, player_two)
     # In total, the players should take 9 turns.
     self.assertEqual(player_one.counter + player_two.counter, 9)
     # One player should have 4 turns and the other should have 5 turns.
     self.assertEqual(abs(player_one.counter - player_two.counter), 1)
Exemplo n.º 15
0
 def test_StopsEarlyIfWinner(self):
     board = Board()
     # One player doesn't do anything (except count turns).
     player_one = MockCountingPlayer("x")
     player_two = MockAdvancingPlayer("o")
     # Other player plays one position at a time (and counts turns).
     # Once one row is full, game play should stop early.
     # Verify that it took less than 9 turns.
     game = GamePlay()
     game.TheGame(player_one, player_two)
     self.assertLess(player_one.counter + player_two.counter, 9)
Exemplo n.º 16
0
    def test_PlayerWinsWithOtherDiagonal(self):
        # Um jogador vai jogar 3 posicoes na transversal. Teste que assim vai
        # vencer com diagonal, e nao com linha ou coluna.
        board = Board()
        player_id = "x"
        board.PlayPosition(2, 0, player_id)
        board.PlayPosition(1, 1, player_id)
        board.PlayPosition(0, 2, player_id)

        self.assertTrue(board.WonWithTransversal(player_id))
        self.assertFalse(board.WonWithRow(player_id))
        self.assertFalse(board.WonWithCol(player_id))
Exemplo n.º 17
0
 def test_VaiJogarParaVencerEmVezDeBloquar(self):
     board = Board()
     player_id = "x"
     other_player_id = "o"
     computer_player = ComputerPlayer(computer_id=player_id,
                                      human_id=other_player_id)
     # Set pattern:
     #    | o | o       Expect (2, 2) to be "x"
     # ---+---+---
     #    |   |
     # ---+---+---
     #  x | x | *
     board.PlayPosition(0, 1, other_player_id)
     board.PlayPosition(0, 2, other_player_id)
     board.PlayPosition(2, 0, player_id)
     board.PlayPosition(2, 1, player_id)
     computer_player.Play(board)
     self.assertTrue(board.HasPosition(2, 2, player_id))
     self.assertTrue(board.PlayerWon(player_id))
Exemplo n.º 18
0
 def test_EscolheParaGanharComLinha(self):
     board = Board()
     player_id = "x"
     computer_player = ComputerPlayer(computer_id=player_id, human_id="o")
Exemplo n.º 19
0
 def test_NaoDeixaOutroJogadorVencerComOutroTraversal(self):
     board = Board()
     player_id = "x"
     other_player_id = "o"
     computer_player = ComputerPlayer(computer_id=player_id,
                                      human_id=other_player_id)
Exemplo n.º 20
0
 def test_IsValidForDigit(self):
     # Verifique que IsValid() retorne true se e um int >=0, <9.
     board = Board()
     human_player = HumanPlayer(player_id="x")
     for val in range(9):
         self.assertTrue(board, human_player.IsValid(board, chr(val)))
Exemplo n.º 21
0
 def test_IsValidForBadInput(self):
     # Verifique que IsValid() retorne false se nao e int >=0, <9.
     board = Board()
     human_player = HumanPlayer(player_id="x")
     self.assertFalse(human_player.IsValid(board, "a"))
Exemplo n.º 22
0
 def setUp(self):
     self.board = Board()
Exemplo n.º 23
0
class BoardTest(unittest.TestCase):
    def setUp(self):
        self.board = Board()

    def test_size(self):
        self.assertEquals(self.board.size(), 9)

    def test_take_cell(self):
        marker = "X"
        self.assertEquals(self.board.get_cell(0), None)
        self.board.take_cell(0, marker)
        self.assertEquals(self.board.get_cell(0), marker)
        self.assertRaises(BoardError,self.board.take_cell, 9, marker)
        self.assertRaises(BoardError, self.board.take_cell, 0, "O")

    def test_check_board_incomplete(self):
        marker = "O"
        self.board.clear()
        self.board.take_cell(0,marker)
        # pdb.set_trace()
        assert self.board.check_board() == False
        assert self.board.winner != marker

    def test_check_board_horizontal(self):
        marker = "O"
        self.board.take_cell(0,marker)
        self.board.take_cell(1,marker)
        self.board.take_cell(2,marker)
        assert self.board.check_board()
        assert self.board.winner == marker
        self.board.clear()
        self.board.take_cell(3,marker)
        self.board.take_cell(4,marker)
        self.board.take_cell(5,marker)
        assert self.board.check_board()
        assert self.board.winner == marker
        self.board.clear()
        self.board.take_cell(6,marker)
        self.board.take_cell(7,marker)
        self.board.take_cell(8,marker)
        assert self.board.check_board()
        assert self.board.winner == marker

    def test_check_board_vertical(self):
        marker = "O"
        self.board.take_cell(0,marker)
        self.board.take_cell(3,marker)
        self.board.take_cell(6,marker)
        assert self.board.check_board()
        assert self.board.winner == marker
        self.board.clear()
        self.board.take_cell(1,marker)
        self.board.take_cell(4,marker)
        self.board.take_cell(7,marker)
        assert self.board.check_board()
        assert self.board.winner == marker
        self.board.clear()
        self.board.take_cell(2,marker)
        self.board.take_cell(5,marker)
        self.board.take_cell(8,marker)
        assert self.board.check_board()
        assert self.board.winner == marker

    def test_check_board_diagonal(self):
        marker = "O"
        self.board.take_cell(0,marker)
        self.board.take_cell(4,marker)
        self.board.take_cell(8,marker)
        assert self.board.check_board()
        assert self.board.winner == marker
        self.board.clear()
        self.board.take_cell(2,marker)
        self.board.take_cell(4,marker)
        self.board.take_cell(6,marker)
        assert self.board.check_board()
        assert self.board.winner == marker
Exemplo n.º 24
0
 def setUp(self):
     self.board = Board()
     self.player = Player("X", self.board, "Sys")
     self.computer = ComputerPlayer("O",self.board)
     self.winners = {}
     self.moves = {}
Exemplo n.º 25
0
 def test_state(self):
     board = Board()
     board.update((0, 0), circle=True)
     board.update((0, 1), circle=True)
     board.update((0, 2), circle=True)
     assert board.game_state == board.CIRCLE_WON
Exemplo n.º 26
0
 def setUp(self):
     self.board = Board()
     self.player = Player("X", self.board, "Sys")
     self.computer = ComputerPlayer("O",self.board)
Exemplo n.º 27
0
 def test_free(self):
     board = Board()
     board.update((0, 0), circle=True)
     assert board.is_free((0, 0)) == False
     assert board.is_free((1, 0)) == True
Exemplo n.º 28
0
class Game(object):
    def __init__(self):

        self._board = Board()
        self.state = 1
        self.turns = 0

    def _get_cell(self):

        while True:
            query = input("Please enter a cell you wish to fill(e.g. x,y): ")
            check = re.compile('[1-3]')
            cell = check.findall(query)
            try:

                if cell is None or len(cell) != 2 or any(x == None
                                                         for x in cell):

                    raise KeyError

                cell = [int(x) - 1 for x in cell]
                if self._board[cell[0]][cell[1]] != 0:

                    raise ValueError

                return cell

            except KeyError:

                print("Incorrect input, please try again")
                continue

            except ValueError:

                print("That cell is already filled, please select another one")
                continue

    def play_turn(self):

        cell = self._get_cell()
        self._board.make_move(cell)

        print(self)
        print('-' * 10)
        state = self._board.has_winner()
        if state == -1:
            self.state = 0
            print(self.victory_scenario(True))
            return True

        elif state == 2:

            return None
        board1 = copy.deepcopy(self._board)
        board1.make_random_move()
        board2 = copy.deepcopy(self._board)
        board2.make_random_move()
        best_result = max(board1, board2, key=lambda x: x.compute_score())
        self._board = best_result
        print(self)

    def victory_scenario(self, is_player=False):
        if is_player == None:
            return "Draw!"
        return "The {} wins!".format("player" if is_player ==
                                     True else "computer")

    def play_game(self):

        while self.state != 0:

            turn = self.play_turn()
            self.turns += 1
            if turn == True:

                print('-' * 10)
                return None

            if self.turns == 5:

                self.state = 0
                print(self.victory_scenario(None))
                print('-' * 10)
                return None

            if self._board.has_winner():

                self.state = 0
                print('-' * 10)
                print(self.victory_scenario())
                print('-' * 10)
                return None

    def __str__(self):

        return self._board.__str__()
Exemplo n.º 29
0
    def __init__(self):

        self._board = Board()
        self.state = 1
        self.turns = 0
Exemplo n.º 30
0
 def test_place_marker(self):
     board = Board()
     self.player = Player("X",board, "Allan")
     self.player.place_marker(4)
     assert board.get_cell(4) == "X"