def setUp(self):
     self.board = Board()
     self.validate = Validate()
     self.board_helper = BoardHelper(self.board.all_ships)
     self.human_board = Board()
     self.ui = TerminalUi()
     self.ai = Ai(self.validate)
class TestBoard(unittest.TestCase):
    def setUp(self):
        self.terrains = {"my_terrain_0": (1, 1), "my_terrain_1": (2, 2)}
        self.board = Board(self.terrains)

    def test_create_board(self):
        self.assertEqual(self.board.terrains, self.terrains)

    def test_board_contain_terrains(self):
        for terrain in self.terrains:
            self.assertTrue(self.board.contain_terrain(terrain))

    def test_board_contain_equal_terrains(self):
        for terrain in self.terrains:
            self.assertEqual(self.board.retrieve_terrain_info(terrain),
                             self.terrains[terrain])

    def test_retrieve_terrain_info(self):
        for terrain in self.terrains:
            info = self.board.retrieve_terrain_info(terrain)
            self.assertIsNotNone(info)

    def test_retrieve_inexistent_terrain_info(self):
        terrain = "my_inexistent_terrain"
        self.assertIsNone(self.board.retrieve_terrain_info(terrain))

    def test_retrieve_terrain_info_equals_instance(self):
        instance_of = tuple
        for terrain in self.terrains:
            info = self.board.retrieve_terrain_info(terrain)
            self.assertIsInstance(info, instance_of)
Exemple #3
0
 def test_board_is_path(self):
     board = Board([], 0)
     assert board.is_path(I(1, 1), I(0, 1)) is True
     assert board.is_path(I(1, 1), I(0, 1), I(0, 0)) is True
     assert board.is_path(I(1, 1), I(0, 1), I(0, 0), I(2, 1)) is False
     assert board.is_path(I(1, 1), I(0, 0)) is False
     assert board.is_path(I(2, 2), I(0, 0)) is False
Exemple #4
0
    def get(self, board_string):
        try:
            print('\n\n')
            self.board = Board(board_string)

            self.graphic = Graphic(self.board)
            self.estimation = Estimation(self.board)

            self.act = Act.none
            self.get_me()

            self.logic()
            self.act_logic()

            self.act = self.me.act_analyzer(self.act, self.next_point,
                                            self.board)
            self.direction = self.point_to_direction(self.next_point)
            self.me.move(self.direction, self.board)
            self.die_check()

            self.graphic.global_text = self.me.str()
            self.graphic.save()

            command = self.create_answer()
            print(f'Sending Command {command}')
            return command
        except Exception as e:
            print(e)
            return 'STOP'
Exemple #5
0
 def testBoardGetGrid(self):
     board = Board(50, 50)
     board_grid = board.get_grid()
     self.assertTrue(len(board.grid[0]) == len(board_grid[0]))
     self.assertTrue(len(board.grid) == len(board_grid))
     for lig in range(50):
         for col in range(50):
             self.assertTrue(board.grid[lig][col] == board_grid[lig][col])
Exemple #6
0
 def testBoardGetCell(self):
     board = Board(50, 50)
     for lig in range(50):
         for col in range(50):
             cell = board.get_cell(lig, col)
             self.assertTrue(isinstance(cell, Cell))
             self.assertTrue(cell.lig == lig)
             self.assertTrue(cell.col == col)
Exemple #7
0
 def test_board_find_molecule_in_board(self):
     board = Board([BoardItem(O, I(0, 0)), BoardItem(H2, I(0, 1)),
                    BoardItem(O, I(0, 2)),
                    BoardItem(Na, I(1, 0)), BoardItem(H2, I(1, 1)),
                    BoardItem(H2, I(1, 2)),
                    BoardItem(O, I(2, 0)), BoardItem(Na, I(2, 1)),
                    BoardItem(H2, I(2, 2))], 3)
     assert board.find_molecule_in_board((I(0, 1), I(0, 2))) == "H2O"
Exemple #8
0
 def test_identifier(self):
     board = Board.from_identifier("8-2190948053667986713720276813968-N:NO:")
     # Note how we can handle parsing old-style identfiiers, but we prefer new ones:
     self.assertEqual(board.identifier(), "8-0622931ecfe9993de30355dae4")
     # Make sure that parsing new-style identifiers does not raise.
     self.assertTrue(Board.from_identifier("8-0622931ecfe9993de30355dae4"))
     self.assertEqual(board.number, 8)
     self.assertEqual(board.call_history.dealer, NORTH)
     self.assertEqual(board.call_history.vulnerability.name, "None")
     # FIXME: We shouldn't really be using pretty_one_line here since it's likely to change.
     deal_string = "N: AQ8632.6.AKQT4.A (hcp: 19 lp: 22 sp: 25) E: J4.AQ2.73.K86543 (hcp: 10 lp: 12 sp: 11) S: T975.KJT4.92.QT9 (hcp: 6 lp: 6 sp: 7) W: K.98753.J865.J72 (hcp: 5 lp: 6 sp: 5)"
     self.assertEqual(board.deal.pretty_one_line(), deal_string)
Exemple #9
0
 def test_board_generate(self):
     with mock.patch('random.choice',
                     side_effect=[O, H2, O, Na, H2, H2, O, Na, H2]):
         board = Board([], 0)
         board.generate(3, (H2, O, Na))
         assert board.iterable == \
             [BoardItem(O, I(0, 0)), BoardItem(H2, I(0, 1)),
              BoardItem(O, I(0, 2)),
              BoardItem(Na, I(1, 0)), BoardItem(H2, I(1, 1)),
              BoardItem(H2, I(1, 2)),
              BoardItem(O, I(2, 0)), BoardItem(Na, I(2, 1)),
              BoardItem(H2, I(2, 2))]
Exemple #10
0
class TestBoard(unittest.TestCase):
    def setUp(self):
        self.board = Board()

    def test_empty_watering_hole_error(self):
        self.assertRaises(ValueError,
                          self.board.remove_food_from_watering_hole)

    def test_add_food_to_watering_hole(self):
        amount = 10
        self.board.add_food_to_watering_hole(amount)

        self.assertEqual(amount, self.board.watering_hole)
Exemple #11
0
 def setUp(self):
     self.ui = TerminalUi()
     self.board = Board()
     self.board_helper = BoardHelper(self.board.all_ships)
     self.missed_marker = consts.MISS_MARKER
     self.hit_marker = consts.HIT_MARKER
     self.sunk_marker = consts.SUNK_MARKER
Exemple #12
0
 def test_board_mark_molecules_in_board(self):
     board = Board([BoardItem(O, I(0, 0)), BoardItem(H2, I(0, 1)),
                    BoardItem(O, I(0, 2)),
                    BoardItem(Na, I(1, 0)), BoardItem(H2, I(1, 1)),
                    BoardItem(H2, I(1, 2)),
                    BoardItem(O, I(2, 0)), BoardItem(Na, I(2, 1)),
                    BoardItem(H2, I(2, 2))], 3)
     board.mark_molecules_in_board((I(0, 1), I(0, 2)))
     assert board.iterable == \
         [BoardItem(O, I(0, 0)),
          BoardItem(H2, I(0, 1), BoardItemStatus.CHECKED),
          BoardItem(O, I(0, 2), BoardItemStatus.CHECKED),
          BoardItem(Na, I(1, 0)), BoardItem(H2, I(1, 1)),
          BoardItem(H2, I(1, 2)),
          BoardItem(O, I(2, 0)), BoardItem(Na, I(2, 1)),
          BoardItem(H2, I(2, 2))]
Exemple #13
0
    def testBoardDisplayerDecorator(self):

        board = Board(50, 50)

        player = Player(50, 1)

        self.assertTrue(issubclass(BoardDisplayer, Board))

        decorated_board = BoardDisplayer(board, player)
        self.assertTrue(board.get_grid() == decorated_board.get_grid())
        self.assertTrue(board.get_height() == decorated_board.get_height())
        self.assertTrue(board.get_width() == decorated_board.get_width())
        self.assertTrue(hasattr(decorated_board, "display"))
        self.assertTrue(inspect.ismethod(decorated_board.display))
        self.assertTrue(hasattr(decorated_board, "wait_move"))
        self.assertTrue(inspect.ismethod(decorated_board.wait_move))
Exemple #14
0
 def move(self, direction: Direction, board: Board):
     self.last_direction = direction
     _, dx, dy = direction._dir
     nx = self.x + dx
     ny = self.y + dy
     next_element = board.get_at((nx, ny))
     self.set_perk(next_element)
Exemple #15
0
 def board(self):
     if not self.board_identifier:
         return None
     try:
         return Board.from_identifier(self.board_identifier)
     except ValueError, e:
         pass
 def create_game(self, adversary_id, board_size, target):
     try:
         if self.online:
             self.game_id = con.create_game(my_team, adversary_id,
                                            board_size, target)
         else:
             self.game_id = 0
         self.m = target
         self.n = board_size
         self.team2 = adversary_id
         self.game_ready = True
         self.board = Board(self.m, self.n)
         return True
     except Exception as e:
         print('Exception: ', e)
         print('Failed to join the game')
         return False
Exemple #17
0
 def testBoardInitialisation(self):
     board = Board(50, 50)
     self.assertTrue(len(board.grid) == 50)
     for lig in range(50):
         self.assertTrue(len(board.grid[lig]) == 50)
         for col in range(50):
             cell = board.grid[lig][col]
             self.assertListEqual(cell, [])
Exemple #18
0
 def testBoardInitialisation(self):
     board = Board(50, 50)
     self.assertTrue(len(board.grid) == 50)
     for lig in range(50):
         self.assertTrue(len(board.grid[lig]) == 50)
         for col in range(50):
             cell = board.grid[lig][col]
             self.assertTrue(isinstance(cell, Cell))
Exemple #19
0
    def testDisplay(self):
        board = Board(20, 20)

        expected_display = "- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n"
        self.assertEqual(board.display(), expected_display)

        w = Wizard("Plop")
        board.move(w, 0, 0)
        expected_display = "X - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n"
        self.assertEqual(board.display(), expected_display)

        board.move(w, 2, 4)
        expected_display = "- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - X - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n- - - - - - - - - - - - - - - - - - - - \n"
        self.assertEqual(board.display(), expected_display)
Exemple #20
0
 def __init__(self, player_names: list):
     self.board = Board()
     self.players = self.__generate_players(player_names)
     self.round = 1
     self.draw_pile = [
         TraitCard(name=f'Trait{i}')
         for i in range(self.__total_trait_cards)
     ]  # Todo: Replace self.draw_pile with real traits.
     self.phase = Phase.DEAL
Exemple #21
0
    def __init__(self, players=None):

        if players is None:
            players = {
                'White': {
                    'name': 'Anon',
                    'ELO': None
                },
                'Black': {
                    'name': 'Anon',
                    'ELO': None
                }
            }
        else:
            self.players = players
        self.board = Board()

        self.board.setup()
 def join_game(self, game_id, adversary_id, board_size, target):
     self.m = target
     self.n = board_size
     self.game_id = game_id
     self.team2 = adversary_id
     if self.online:
         board_map, status = con.get_board_map(self.game_id)
     else:
         status = 'OK'
     if status == 'OK':
         self.game_ready = True
         self.board = Board(self.m, self.n)
         if self.online:
             self.board.read_board_string(board_map)
         return True
     else:
         print('Failed to join the game')
         return False
Exemple #23
0
    def main(self, args):
        self.configure_logging(True)
        bidder = KnowledgeBasedBidder()

        if "-v" in args:
            args.remove("-v")
            self.verbose = True

        if args:
            for identifier in args:
                self._bid_board(Board.from_identifier(identifier), bidder)
            return 0

        try:
            while True:
                self._bid_board(Board.random(), bidder)
        except KeyboardInterrupt:
            print
            print "User interrupted."
            return 0
Exemple #24
0
class BoardTests(unittest.TestCase):
    def setUp(self):
        self.board = Board()

    def print_test(self, s):
        print("{0:#^50}".format(s))

    def test_board_of_table(self):
        self.print_test(" starting test_board_of_table ")
        expected_table = '   0  1  2  3  4  5  6  7  8  9  10 11 12 13 14\n' \
                         '0  .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '1  .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '2  .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '3  .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '4  .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '5  .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '6  .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '7  .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '8  .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '9  .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '10 .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '11 .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '12 .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '13 .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '14 .  .  .  .  .  .  .  .  .  .  .  .  .  .  . '
        print(self.board)
        print()
        self.assertEqual(expected_table, str(self.board))

    def test_get_piece(self):
        self.print_test(" starting test_get_piece ")
        piece = self.board.get_piece(Square(1, 1))
        print()
        self.assertEqual(Piece.NONE, piece)

    def test_play_piece(self):
        self.print_test(" starting test_play_piece ")
        square = Square(1, 1)
        piece = self.board.get_piece(square)
        self.assertEqual(Piece.NONE, piece)
        self.board.take_up_space(Piece.BLACK, square)
        piece = self.board.get_piece(square)
        self.assertEqual(Piece.BLACK, piece)
        square = Square(0, 2)
        self.board.take_up_space(Piece.WHITE, square)
        piece = self.board.get_piece(square)
        self.assertEqual(Piece.WHITE, piece)
        print(self.board)
        print()
Exemple #25
0
    def status(self):
        # rows
        for i in range(constants.BOARD_SIZE):
            if self.board[i][0] != constants.EMPTY and self.board[i][1] != constants.EMPTY\
                and self.board[i][2] != constants.EMPTY and self.board[i][0] == self.board[i][1]\
                    and self.board[i][1] == self.board[i][2]:
                return self.board[i][0]

        # cols
        transposed = Board()

        for i in range(constants.BOARD_SIZE):
            for j in range(constants.BOARD_SIZE):
                transposed.board[i][j] = self.board[j][i]

        for i in range(constants.BOARD_SIZE):
            if transposed.board[i][0] != constants.EMPTY and transposed.board[i][1] != constants.EMPTY\
                and transposed.board[i][2] != constants.EMPTY and transposed.board[i][0] == transposed.board[i][1]\
                    and transposed.board[i][1] == transposed.board[i][2]:
                return transposed.board[i][0]

        # prim diag
        if self.board[0][0] != constants.EMPTY and self.board[1][1] != constants.EMPTY\
            and self.board[2][2] != constants.EMPTY and self.board[0][0] == self.board[1][1]\
                and self.board[1][1] == self.board[2][2]:
            return self.board[0][0]

        # secondary diag
        if self.board[0][2] != constants.EMPTY and self.board[1][1] != constants.EMPTY\
            and self.board[2][0] != constants.EMPTY and self.board[0][2] == self.board[1][1]\
                and self.board[2][0] == self.board[1][1]:
            return self.board[0][2]

        # draw
        if self.full():
            return constants.DRAW

        # in progress
        return constants.IN_PROGRESS
Exemple #26
0
class MainExec:
    def __init__(self, players=None):

        if players is None:
            players = {
                'White': {
                    'name': 'Anon',
                    'ELO': None
                },
                'Black': {
                    'name': 'Anon',
                    'ELO': None
                }
            }
        else:
            self.players = players
        self.board = Board()

        self.board.setup()

    def ply(self, turn):
        """
        Processes a move of a player. After the move is made, it assesses if its legal (when in check).
        If the move is legal, it updates the board position. The function does not return until a valid move is made.
        Resigning counts as a valid move.
        :param turn:
        :return:
        """
        legal_move = False
        while not legal_move:
            legal_move = self.move(turn=turn)
        self.board.update()

    def move(self, turn):
        old_position = self.board.board

        player_move = input()
Exemple #27
0
 def __init__(self, ):
     self.board = Board()
     self.players = [Player('0'), Player('1')]
     self.turn = 0
     self.songs = {
         1: 'Birth',
         2: 'Death',
         3: 'Resistance',
         4: 'Reign',
         5: 'Ascent',
         6: 'Tirany',
         7: 'the Mysteries'
     }
     self.buildings = {
         'Birth': ['Garden', 'House'],
         'Death': [],
         'Resistance': ['Thorn wall', 'Barracks'],
         'Reign': ['Bridge'],
         'Ascent': ['Harbor', 'Library', 'Statue'],
         'Tirany': ['Prison', 'Rebel camp'],
         'the Mysteries': ['Shrine']
     }
     self.setupFigures()
     self.loosers = None
Exemple #28
0
class BoardTests(unittest.TestCase):
    def setUp(self):
        self.board = Board()

    def test_board_of_table(self):
        expected_table = '   0  1  2  3  4  5  6  7  8  9  10 11 12 13 14\n' \
                         '0  .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '1  .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '2  .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '3  .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '4  .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '5  .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '6  .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '7  .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '8  .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '9  .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '10 .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '11 .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '12 .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '13 .  .  .  .  .  .  .  .  .  .  .  .  .  .  . \n' \
                         '14 .  .  .  .  .  .  .  .  .  .  .  .  .  .  . '
        print(self.board)
        print()
        self.assertEqual(expected_table, str(self.board))

    def test_get_piece(self):
        piece = self.board.get_piece(Square(1, 1))
        print()
        self.assertEqual(Piece.NONE, piece)

    def test_play_piece(self):
        square = Square(1, 1)
        piece = self.board.get_piece(square)
        self.assertEqual(Piece.NONE, piece)
        self.board.take_up_space(Piece.BLACK, square)
        piece = self.board.get_piece(square)
        self.assertEqual(Piece.BLACK, piece)
        square = Square(0, 2)
        self.board.take_up_space(Piece.WHITE, square)
        piece = self.board.get_piece(square)
        self.assertEqual(Piece.WHITE, piece)
        print(self.board)
        print()
Exemple #29
0
    def test_board_neigbours(self):
        with mock.patch('random.choice',
                        side_effect=[O2, H2, O, Na, Cl, H2, O, Na, H2]):
            board = Board([], 0)
            board.generate(3, (H2, O, Na))
            assert board.neighbours(I(1, 1), I(0, 1)) is True
            assert board.neighbours(I(1, 0), I(1, 1)) is True
            assert board.neighbours(I(1, 1), I(2, 1)) is True
            assert board.neighbours(I(1, 2), I(1, 1)) is True

            assert board.neighbours(I(1, 0), I(0, 1)) is False
            assert board.neighbours(I(0, 1), I(0, 1)) is False
Exemple #30
0
 def __init__(self,):
     self.board = Board()
     self.players = [Player('0'), Player('1')]
     self.turn = 0
     self.songs = {1: 'Birth',
                   2: 'Death',
                   3: 'Resistance',
                   4: 'Reign',
                   5: 'Ascent',
                   6: 'Tirany',
                   7: 'the Mysteries'}
     self.buildings = {'Birth': ['Garden', 'House'],
                       'Death': [],
                       'Resistance': ['Thorn wall', 'Barracks'],
                       'Reign': ['Bridge'],
                       'Ascent': ['Harbor', 'Library', 'Statue'],
                       'Tirany': ['Prison', 'Rebel camp'],
                       'the Mysteries': ['Shrine']}
     self.setupFigures()
     self.loosers = None
Exemple #31
0
class PlayerTests(unittest.TestCase):
    def setUp(self):
        self.board = Board()

    def test_playing(self):
        player = HumanPlayer(self.board, Piece.WHITE)
        square = Square(row=7, col=7)
        player.play(square)
        piece = self.board.get_piece(square)
        self.assertEqual(Piece.WHITE, piece)

    def test_minimax(self):
        player = MachinePlayer(self.board, Piece.BLACK)
        self.board._table[1, 5:8] = Piece.BLACK

        expected_board = cp.deepcopy(self.board)
        expected_score = 2000000
        expected_movement = Square(1, 4)

        current_score, current_movement = player.minimax(2)

        self.assertEqual(expected_score, current_score)
        self.assertEqual(expected_movement, current_movement)
        self.assertEqual(expected_board, self.board)

    def test_minimax_pruning(self):
        player = MachinePlayer(self.board, Piece.BLACK)
        self.board._table[1, 5:8] = Piece.BLACK

        print(self.board)

        expected_board = cp.deepcopy(self.board)
        expected_score = 2000000
        expected_movement = Square(1, 4)

        current_score, current_movement = player.minimax_pruning(2)

        self.assertEqual(expected_score, current_score)
        self.assertEqual(expected_movement, current_movement)
        self.assertEqual(expected_board, self.board)
Exemple #32
0
class PlayerTests(unittest.TestCase):
    def setUp(self):
        self.board = Board()

    def test_playing(self):
        player = HumanPlayer(self.board, Piece.WHITE)
        square = Square(row=7, col=7)
        player.play(square)
        piece = self.board.get_piece(square)
        self.assertEqual(Piece.WHITE, piece)

    def test_minimax(self):
        player = MachinePlayer(self.board, Piece.BLACK)
        self.board._table[1, 5:8] = Piece.BLACK

        expected_board = cp.deepcopy(self.board)
        expected_score = 2000000
        expected_movement = Square(1, 4)

        current_score, current_movement = player.minimax(2)

        self.assertEqual(expected_score, current_score)
        self.assertEqual(expected_movement, current_movement)
        self.assertEqual(expected_board, self.board)

    def test_minimax_pruning(self):
        player = MachinePlayer(self.board, Piece.BLACK)
        self.board._table[1, 5:8] = Piece.BLACK

        print(self.board)

        expected_board = cp.deepcopy(self.board)
        expected_score = 2000000
        expected_movement = Square(1, 4)

        current_score, current_movement = player.minimax_pruning(2)

        self.assertEqual(expected_score, current_score)
        self.assertEqual(expected_movement, current_movement)
        self.assertEqual(expected_board, self.board)
Exemple #33
0
 def act_analyzer(self, act: Act, next_point: tuple, board: Board) -> Act:
     if self.remote_act:
         d = self.explosion_radius
         points = {self.last_act}
         add_empties_around(board, self.last_act, points, dx=d, dy=d)
         if self.immune_time <= 1 and self.point in points:
             return Act.none
         for point in points:
             if board.get_at(point) in [
                     Element('OTHER_BOMBERMAN'),
                     Element('MEAT_CHOPPER'),
                     Element('OTHER_BOMB_BOMBERMAN')
             ]:
                 self.act_of_remove_act()
                 return Act.before
         if self.last_act_time > 5:
             self.act_of_remove_act()
             return Act.before
         return Act.none
     if act != Act.none:
         # can place bomb
         if self.count_time == 0:
             if self.last_act is not None:
                 return Act.none
         # remote
         if self.remote_value > 0:
             self.remote_value -= 1
             self.remote_act = True
         # setup last_act
         if act == Act.before:
             self.last_act = self.point
         if act == Act.after:
             self.last_act = next_point
         self.last_act_time = 0
         return act
     else:
         return Act.none
Exemple #34
0
    def testCharacterMove(self):
        board = Board(50, 50)
        w = Wizard("Plop")
        self.assertEqual(w.x, None)
        self.assertEqual(w.y, None)

        board.move(w, 0, 0)
        self.assertEqual(w.x, 0)
        self.assertEqual(w.y, 0)
        cell = board.grid[0][0]
        self.assertTrue(w in cell)

        cell_before_move = board.grid[w.x][w.y]
        board.move(w, 2, 4)
        self.assertEqual(w.x, 2)
        self.assertEqual(w.y, 4)
        cell = board.grid[2][4]
        self.assertTrue(w not in cell_before_move)
        self.assertTrue(w in cell)
Exemple #35
0
 def setUp(self):
     self.board = Board()
Exemple #36
0
import argparse
from utility.args_game_config import ArgsGameConfig
from core.connect_four_game import ConnectFourGame
from core.board import Board
from core.registered_player import RegisteredPlayer
from views.zelle_graphics_game_view import ZelleGraphicsGameView
from core.best_of_game import BestOfGame
from core.strategy_loader import StrategyLoader

config = ArgsGameConfig(argparse.ArgumentParser())
game = BestOfGame(ConnectFourGame(Board(7, 6)), config.number_of_games())
view = ZelleGraphicsGameView(delay=config.turn_delay())
strategies = StrategyLoader(strategies_dir="strategies")
game.play(RegisteredPlayer(strategies), RegisteredPlayer(strategies), view)
Exemple #37
0
def game_singleplayer(player1, player2):
    def graphics(surface, delta_t, player1, player2, entities):

        surface.fill((255, 255, 255))

        timer = render_text(
            '%.2d:%.2d' %
            (delta_t.total_seconds() // 60, delta_t.total_seconds() % 60))
        surface.blit(timer, ((config['WIDTH'] - timer.get_width()) // 2, 50))

        if current_player == player1:
            surface.blit(player1.active_name_rendered, (25, 10))
            surface.blit(player2.name_rendered,
                         ((config['WIDTH'] -
                           player2.name_rendered.get_width() - 25), 10))

        elif current_player == player2:
            surface.blit(player1.name_rendered, (25, 10))
            surface.blit(player2.active_name_rendered,
                         ((config['WIDTH'] -
                           player2.name_rendered.get_width() - 25), 10))

        player1_points = render_text(f'{player1.points}')
        surface.blit(player1_points,
                     ((25 + player1.icon_rendered.get_width() + 25), 50 +
                      (player1.icon_rendered.get_height() -
                       player1_points.get_height()) // 2))

        surface.blit(player1.icon_rendered, (25, 50))
        surface.blit(
            player2.icon_rendered,
            ((config['WIDTH'] - player2.icon_rendered.get_width() - 25), 50))

        player2_points = render_text(f'{player2.points}')
        surface.blit(player2_points,
                     (((config['WIDTH'] - player2.icon_rendered.get_width()) -
                       player2_points.get_width() - 50), 50 +
                      (player2.icon_rendered.get_height() -
                       player2_points.get_height()) // 2))

        for entity in entities:
            entity.render(surface)

    global display, clock, config

    board = Board((config['WIDTH'] - 600) // 2, 200, 600, 600)

    pause_button = ImageButton(270, 25, 'pause.png')
    resume_button = ImageButton(305, 25, 'resume.png')

    start_time = datetime.datetime.now()

    player1.update()
    player2.update()

    current_player = player1

    run = True
    pause = False

    while run:

        clock.tick(config['FPS'])
        delta_t = datetime.datetime.now() - start_time

        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                quit()

            if event.type == pygame.KEYDOWN:

                if event.key == pygame.K_ESCAPE:
                    run = False

            if event.type == pygame.MOUSEBUTTONDOWN:

                if event.button == 1:
                    mouse_pos = pygame.mouse.get_pos()

                    board.is_clicked(mouse_pos, current_player)

                    if pause_button.is_clicked(mouse_pos):
                        pause = True

                    if resume_button.is_clicked(mouse_pos):
                        pause = False

                    if current_player.move_finished:
                        current_player.move_finished = False

                        if board.check_win_condition(current_player):
                            return_option = game_over(current_player)

                            player1.reset()
                            player2.reset()

                            if return_option == 'restart':
                                current_player = player1
                                board.reset_figures()

                            elif return_option == 'quit':
                                return

                        elif current_player == player1:
                            current_player = player2

                        elif current_player == player2:
                            current_player = player1

        graphics(display, delta_t, player1, player2,
                 [board, pause_button, resume_button])
        pygame.display.update()

    return
Exemple #38
0
def ai_test():
    b = Board(5, 15)
    ai = Ai()
    # b.move(7, 7, 2)
    # print(b.get_board())
    while True:
        x, y = str.split(input('Enter move position (left up is 0 0): \"x y\"\n'), ' ')
        x = int(x)
        y = int(y)
        b.move(x, y, 1)
        if b.get_result() != 0:
            print(b.get_board())
            print(b.get_result())
            break
        # print(b.get_board())
        x, y = ai.move(b, 2)
        b.move(x, y, 2)
        if b.get_result() != 0:
            print(b.get_board())
            print(b.get_result())
            break
        print(b.get_board())
        print(x, y)
Exemple #39
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import arm.arm_controler as ac
import arm.servo_controler as sc
import threading
from core.board import Board
from arm.chess_machine import ChessMachine
from assist.assistant import Assist

if __name__ == '__main__':
    arm = ac.arm()
    board = Board()
    machine = ChessMachine(board, arm, assist=True)
    machine.human_vs_human()
Exemple #40
0
 def __init__(self, molecules_file, board_size):
     self.storage = Storage.load_molecules(molecules_file)
     atoms = self.storage.get_atoms()
     self.board = Board([], 0)
     self.board.generate(board_size, atoms)
Exemple #41
0
 def __init__(self, **kwargs):
     Board.__init__(self, [], 0)
     Widget.__init__(self, **kwargs)
     self.storage = []
     # self.atoms = []
     self.bind(pos=self.on_pos_size, size=self.on_pos_size)
Exemple #42
0
class Game:

    def __init__(self,):
        self.board = Board()
        self.players = [Player('0'), Player('1')]
        self.turn = 0
        self.songs = {1: 'Birth',
                      2: 'Death',
                      3: 'Resistance',
                      4: 'Reign',
                      5: 'Ascent',
                      6: 'Tirany',
                      7: 'the Mysteries'}
        self.buildings = {'Birth': ['Garden', 'House'],
                          'Death': [],
                          'Resistance': ['Thorn wall', 'Barracks'],
                          'Reign': ['Bridge'],
                          'Ascent': ['Harbor', 'Library', 'Statue'],
                          'Tirany': ['Prison', 'Rebel camp'],
                          'the Mysteries': ['Shrine']}
        self.setupFigures()
        self.loosers = None

    def possibleSongs(self, island):
        songsBits = self.board.possibleSongs(island, self.currentPlayer())
        songKeys = self.songs.keys()
        return [self.songs[key] for key in songKeys if key & songsBits == key]

    def possibleBuildings(self, island):
        songs = self.possibleSongs(island)
        buildings = []
        for song in songs:
            for building in self.buildings[song]:
                buildings.append(building)
        return buildings

    def build(self, building, field):
        if field.figure != None:
            return False
        building = Building(building, field)
        player = self.currentPlayer()
        if building.price <= player.resources:
            player.buildings.append(building)
            field.put(building)
            player.resources -= building.price
            return building
        return False

    def setupFigures(self):
        for player in self.players:
            island = None
            if player.color == '0':
                island = self.board.islands[-3]
            else:
                # island = self.board.islands[-2]
                island = self.board.islands[10]

            field = island.fields[0]
            field.put(King(field, player))
            player.figures.append(field.figure)
            field = island.fields[1]
            field.put(Warrior(field, player))
            player.figures.append(field.figure)
            field = island.fields[2]
            field.put(Peasant(field, player))
            player.figures.append(field.figure)
            field = island.bay
            field.put(Ship(field, player))
            player.figures.append(field.figure)

    def __unfreezeFigures(self, player):
        for figure in player.figures:
            figure.hasMoved = False

    def currentPlayer(self):
        return self.players[self.turn]

    def newBattle(self):
        black = self.players[self.turn]
        white = self.players[self.turn ^ 1]
        return Battle(black, white)

    def giveBirthToPeasant(self, field):
        player = self.currentPlayer()
        if player.resources >= PEASANT_PRICE:
            peasant = Peasant(field, player)
            field.put(peasant)
            player.resources -= PEASANT_PRICE
            player.figures.append(peasant)
            return peasant
        return False

    def giveBirthToWarrior(self, field):
        player = self.currentPlayer()
        if player.resources >= WARRIOR_PRICE:
            warrior = Warrior(field, player)
            field.put(warrior)
            player.resources -= WARRIOR_PRICE
            player.figures.append(warrior)
            return warrior
        return False

    def buildShip(self, field):
        player = self.currentPlayer()
        if player.resources >= SHIP_PRICE:
            ship = Ship(field, player)
            field.put(ship)
            player.resources -= SHIP_PRICE
            player.figures.append(ship)
            return ship
        return False

    def __harvestResources(self):
        player = self.currentPlayer()
        for building in player.buildings:
            if building.building == 'Garden':
                player.resources += GARDEN_INCOME

    def __checkForLoosers(self):
        black = False
        for figure in self.players[0].figures:
            if type(figure) == King:
                black = True
        white = False
        for figure in self.players[1].figures:
            if type(figure) == King:
                white = True
        if not black:
            self.loosers = 'black'
        if not white:
            self.loosers = 'both' if not black else 'white'

    def __onTurnStart(self):
        self.__harvestResources()
        self.__unfreezeFigures(self.currentPlayer())
        self.__checkForLoosers()

    def changeTurn(self):
        if self.turn == 1:
            self.turn = -1
        self.turn += 1
        self.__onTurnStart()
Exemple #43
0
 def setUp(self):
     self.board = Board()
Exemple #44
0
class DirectionSolver:
    def __init__(self):
        self.me = Me()
        self.board: Optional[Board] = None
        self.graphic: Optional[Graphic] = None
        self.estimation: Optional[Estimation] = None

        self.next_point: Optional[tuple] = None
        self.direction: Optional[Direction] = None
        self.act: Optional[Act] = None

    def get(self, board_string):
        try:
            print('\n\n')
            self.board = Board(board_string)

            self.graphic = Graphic(self.board)
            self.estimation = Estimation(self.board)

            self.act = Act.none
            self.get_me()

            self.logic()
            self.act_logic()

            self.act = self.me.act_analyzer(self.act, self.next_point,
                                            self.board)
            self.direction = self.point_to_direction(self.next_point)
            self.me.move(self.direction, self.board)
            self.die_check()

            self.graphic.global_text = self.me.str()
            self.graphic.save()

            command = self.create_answer()
            print(f'Sending Command {command}')
            return command
        except Exception as e:
            print(e)
            return 'STOP'

    def get_me(self):
        x, y = self.board.find_bomberman()
        self.me.tick(x, y)
        print(self.me.str())
        # p = (me.y + 3) * self.board._size + me.x
        # self.board._string = self.board._string[:p] + '1' + self.board._string[p + 1:]

    def make_np(self, lax, lay):
        npx, npy = self.me.point
        if lax > npx:
            npx -= 1
        elif lax < npx:
            npx += 1
        if lay > npy:
            npy -= 1
        elif lay < npy:
            npy += 1
        return npx, npy

    def logic(self):
        predictor = Predictor(self.board, self.me)
        predictor.run(self.me.point)
        print('\nPREDICTION:')
        predictor.print()

        proposal = predictor.proposal()
        print('\nPROPOSAL:')
        next_point_estimation = {}
        for next_point, points in proposal.items():
            estimation = self.estimation.estimate(points, next_point)
            direction = self.point_to_direction(next_point)
            if direction == Direction('STOP'):
                estimation *= DIRECTION_STOP_K
            if direction == self.me.last_direction.inverted():
                estimation *= DIRECTION_INVERTED_K
            next_point_estimation[next_point] = estimation
            print(
                f'{direction.to_string()}: {round(estimation, 5)}: {points} - {len(points)}'
            )
        self.next_point = self.me.point
        if len(next_point_estimation) > 0:
            self.next_point = max(next_point_estimation,
                                  key=next_point_estimation.get)
        self.draw(predictor, next_point_estimation)

    def act_logic(self):
        before = self.estimation.estimate_act(self.me.point,
                                              self.me.explosion_radius)
        after = self.estimation.estimate_act(self.next_point,
                                             self.me.explosion_radius)
        if before >= after and before >= ESTIMATION_ACK_MIN_SCORE:
            self.act = Act.before
        elif after >= ESTIMATION_ACK_MIN_SCORE:
            self.act = Act.after
        # act check with predictor
        if self.act != Act.none:
            act_point = self.me.point if self.act == Act.before else self.next_point
            board = self.board.copy()
            board.set_at(act_point, Element('BOMB_TIMER_4'))
            # self.graphic = Graphic(board)
            act_predictor = Predictor(board, self.me)
            act_predictor.run(self.next_point, meat_chopper_d=2)
            if len(act_predictor.tree[PREDICTOR_DEEP]) == 0:
                self.act = Act.none
            if self.act == Act.before:
                proposal = act_predictor.proposal()
                if self.next_point not in proposal.keys():
                    self.act = Act.none
                    # nx, ny = self.next_point
                    # self.graphic.set_color(nx, ny, 'violet')
                    # self.next_point = max(proposal, key=lambda key: len(proposal.get(key)))

    def draw(self, predictor: Predictor, next_point_estimation: dict):
        for deep, tree_level in enumerate(predictor.tree):
            if deep == 0:
                continue
            color = 'red' if deep == PREDICTOR_DEEP else 'orange'
            for possibility in tree_level:
                x, y = possibility.point
                self.graphic.set_color(x, y, color)
        for possibility in predictor.tree[PREDICTOR_DEEP]:
            x, y = possibility.point
            estimation = self.estimation.estimate_one(x, y)
            text = str(round(estimation, 1))
            self.graphic.set_text(x, y, text)
        for (x, y), estimation in next_point_estimation.items():
            self.graphic.set_color(x, y, 'blue')
            self.graphic.set_text(x,
                                  y,
                                  str(round(estimation, 2)),
                                  append=False)

    def die_check(self):
        state = self.board.get_at(self.me.point)
        if state == Element('DEAD_BOMBERMAN'):
            self.me = Me()

    def point_to_direction(self, next_point: tuple) -> Direction:
        nx, ny = next_point
        x, y = self.me.point
        dx = nx - x
        dy = ny - y
        if dx + dy == 0:
            return Direction('STOP')
        elif dy == -1:
            return Direction('UP')
        elif dy == 1:
            return Direction('DOWN')
        elif dx == -1:
            return Direction('LEFT')
        elif dx == 1:
            return Direction('RIGHT')

    def create_answer(self) -> str:
        command = self.direction.to_string()
        if self.act == Act.before:
            command = 'ACT, ' + command
        if self.act == Act.after:
            command = command + ', ACT'
        return command
 def setUp(self):
     self.terrains = {"my_terrain_0": (1, 1), "my_terrain_1": (2, 2)}
     self.board = Board(self.terrains)
Exemple #46
0
class Game(object):
    @logged
    def __init__(self, molecules_file, board_size):
        self.storage = Storage.load_molecules(molecules_file)
        atoms = self.storage.get_atoms()
        self.board = Board([], 0)
        self.board.generate(board_size, atoms)

    @logged
    def main(self):
        """
        Main game function.
        """
        score = 0
        partial_indeces = list()
        # Main game loop
        while not self.board.all_marked():
            print_board(self.board)
            try:
                s_user_input = input("Create molecule:")
                logging.debug("user input `%s`", s_user_input)
            except KeyboardInterrupt:
                break

            try:
                indeces = self.parse_user_input(s_user_input)
                try:
                    if not self.board.is_path(partial_indeces[-1], *indeces):
                        raise ValueError
                except IndexError:
                    pass
                partial_indeces.extend(indeces)
                user_molecule = self.board.\
                    find_molecule_in_board(partial_indeces)
            except (ValueError, IndexError):
                print("Bad coords inserted!")
                logging.warn("bad coords input `%s`", s_user_input)
                continue

            try:
                self.storage.find(user_molecule)
                self.board.mark_molecules_in_board(partial_indeces,
                                                   BoardItemStatus.CHECKED)
            except MissingError:
                possible_molecules = self.storage.\
                    get_super_molecules(user_molecule)
                if possible_molecules:
                    print("You are on the right way")
                    logging.debug("possible molecules %s", possible_molecules)
                    self.board.mark_molecules_in_board(partial_indeces,
                                                       BoardItemStatus.MARKED)
                else:
                    self.board.mark_molecules_in_board(partial_indeces,
                                                       BoardItemStatus.EMPTY)
                    partial_indeces = list()
                    score = score - 1
                print("Try it again")
            except IndexError:
                self.board.mark_molecules_in_board(partial_indeces,
                                                   BoardItemStatus.EMPTY)
                partial_indeces = list()
                score = score - 1
                print("Try it again!")
            else:
                partial_indeces = list()
                score = score + 1
                print("Found it!")
            logging.debug("score %s", score)

        else:
            print("You are finished!")
            logging.debug("Empty molecules")
        return score

    @staticmethod
    @logged
    def parse_user_input(user_input):
        return tuple(map(lambda x: I(int(x[0]), int(x[1])),
                         map(lambda x: x.split(":"),
                             user_input.strip().split(" "))))