Esempio n. 1
0
    def __game_loop(self):
        """Player moves are handled by this function."""

        current_player = self.__player_one
        other_player = self.__player_two

        while True:
            print(self.__board.draw_board(self.__board.board))
            player_col_choice = input(f"{current_player.name}, choose a move: ")
            move_coordinates = self.__board.player_move(current_player, player_col_choice)
            if not move_coordinates:
                continue
            else:
                win = self.__has_won(current_player, move_coordinates)
                draw = (not win) and self.__have_drawn()
                if win or draw:
                    print(self.__board.draw_board(self.__board.board))
                    if win:
                        print(f"{current_player.name} has won!")
                        current_player.wins = 1
                    elif draw:
                        print("Game drawn!")

                    if not self.__continue_playing():
                        print(self.__statistics())
                        return
                    else:
                        self.__board = Board()

                else:
                    current_player, other_player = other_player, current_player
Esempio n. 2
0
    def setUp(self, text=None):
        random.seed(0)
        self.board = Board(size=9, batch=5, colsize=None, scrub_length=5, axes=None, logfile=None
                      , drawing_callbacks=dict())

        if text:
            self.board.init_test_graph(text)
Esempio n. 3
0
    def play(self, tetromino_seq):
        self.tetromino_spawner = TetrominoSpawner(tetromino_seq)

        for i in range(
                1
        ):  # this range changes the number of times single game is played (more games are better in case of random spawning)
            self.is_game_over = False  # TODO
            self.board = Board()

            while not self.is_game_over:
                # get situation of top two rows
                situation = self.board.get_situation()

                # get new tetromino
                tetromino: Tetromino = self.tetromino_spawner.spawn()
                rotations_num = self.gene.get_rotation(situation,
                                                       tetromino.shape_num)
                tetromino.rotate(times=rotations_num)

                # check if last row is empty and end if not
                if not self.board.can_place_next_tetromino(tetromino):
                    self.is_game_over = True
                    break

                # place tetromino
                position = self.gene.get_position(situation,
                                                  tetromino.shape_num)
                self.board.add_tetromino(tetromino, position)

                # remove full rows and add score
                removed_count = self.board.remove_full_rows_and_return_count()
                self.score += removed_count * 10000  # give 1000 pts for each row
                self.score += 1  # give score for each dropped tetromino 30 pieces > 1 row
Esempio n. 4
0
 def print(self):
     print(f"num q_values = {len(self.cache.boards)}")
     for cells_bytes, value in self.cache.boards.items():
         cells = np.frombuffer(cells_bytes, dtype=int)
         board = Board(cells)
         board.print()
         print(f"qvalue = {value}")
 def __init__(self):
     super(GraphicsBoard, self).__init__()
     self.rows = 3
     self.cols = 8
     self.info_label = Label(text='Welcome!')
     self.board = Board()
     self._initialize_board()
Esempio n. 6
0
def main():
    b = Board()
    b.generate_tile_row(3, 0)
    b.generate_tile_row(4, 1)
    b.generate_tile_row(5, 2)
    b.generate_tile_row(4, 3)
    b.generate_tile_row(3, 4)
    print('Done')
Esempio n. 7
0
def test_second_turn_center_opening(player_mark):
    other_mark = Game.FIRST_PLAYER_MARK
    ai = AI(player_mark)
    board = Board()
    board._rows = [[' ', ' ', ' '], [' ', other_mark, ' '], [' ', ' ', ' ']]
    for _ in range(100):
        assert ai._second_turn(board.representation()) in product((0, 2),
                                                                  (0, 2))
Esempio n. 8
0
    def __init__(self):
        self.whose_turn = 'red'

        self.board = Board()
        self.setup_board(self.board)
        print(self.board)

        self.artificial_players = {'red': None, 'black': None}
Esempio n. 9
0
def test_row(mark):
    board = Board()
    board._rows = [[' ', ' ', ' '], [' ', mark, mark], [' ', mark, ' ']]

    for _ in range(100):
        player = RandomComputer(mark)
        row, column = player.turn(board)
        assert board.is_cell_empty(row, column)
Esempio n. 10
0
    def __init__(self, upper_player, lower_player):
        """Instantiate a Mancala game."""
        self.board = Board()

        self._upper_player = upper_player
        self._lower_player = lower_player

        self._current_player = self._upper_player
Esempio n. 11
0
def start_ui():
    board = Board(6, 6)
    strategy = Strategy()
    p1 = Human('x', board)
    p2 = Computer("0", board, strategy)
    minimax = Minimax()
    game = Game(p1, p2, board, minimax)
    game.start()
Esempio n. 12
0
def test_column(mark):
    board = Board()
    board._rows = [[' ', mark, ' '], [' ', mark, ' '], [' ', mark, ' ']]

    for row in range(3):
        assert board._has_win_occurred(row, 1)
    assert not board._has_win_occurred(0, 2)
    assert not board._has_win_occurred(2, 0)
    assert not board._has_win_occurred(2, 2)
Esempio n. 13
0
def test_main_diagonal(mark):
    board = Board()
    board._rows = [[mark, ' ', ' '], [' ', mark, ' '], [' ', ' ', mark]]

    for row in range(3):
        assert board._has_win_occurred(row, row)
    assert not board._has_win_occurred(0, 2)
    assert not board._has_win_occurred(2, 0)
    assert not board._has_win_occurred(2, 1)
Esempio n. 14
0
def test_secondary_diagonal(mark):
    board = Board()
    board._rows = [[' ', ' ', mark], [' ', mark, ' '], [mark, ' ', ' ']]

    for row in range(3):
        assert board._has_win_occurred(row, 2 - row)
    assert not board._has_win_occurred(0, 0)
    assert not board._has_win_occurred(2, 2)
    assert not board._has_win_occurred(1, 0)
Esempio n. 15
0
def test_row(mark):
    board = Board()
    board._rows = [[' ', ' ', ' '], [mark, mark, mark], [' ', ' ', ' ']]

    for column in range(3):
        assert board._has_win_occurred(1, column)
    assert not board._has_win_occurred(2, 0)
    assert not board._has_win_occurred(2, 1)
    assert not board._has_win_occurred(2, 2)
Esempio n. 16
0
def game():
    global MAP_TYPE
    board = Board(MAP_TYPE)
    screen = board.display_board_hide()

    width_pressed, height_pressed = 0, 0
    posX_pressed, posY_pressed = 0, 0
    running, r_pressed, escape_pressed = True, False, False
    while running:
        try:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                    pygame.quit()
                    quit()

                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_r:
                        r_pressed = True
                        running = False

                    elif event.key == pygame.K_ESCAPE:
                        escape_pressed = True
                        running = False
                        main()

                if not board.visible:
                    if event.type == pygame.MOUSEBUTTONUP:
                        button_pressed = board.matrix[posY_pressed][
                            posX_pressed]
                        board.action(button_pressed, event, screen)

                    elif event.type == pygame.MOUSEBUTTONDOWN:
                        width_pressed = event.pos[0]
                        height_pressed = event.pos[1]

                        posX_pressed = int(width_pressed / 40)
                        posY_pressed = int(height_pressed / 40)

                        button_pressed = board.matrix[posY_pressed][
                            posX_pressed]

                        if button_pressed.content.status_celd() == "Invisible":
                            pic = picture.get_picture(0)
                            pic = pygame.transform.scale(
                                pic,
                                (button_pressed.width, button_pressed.height))
                            screen.blit(pic,
                                        (button_pressed.x, button_pressed.y))
                            pygame.display.flip()
        except pygame.error:
            pass

    if r_pressed:
        game()
    if escape_pressed:
        main()
Esempio n. 17
0
def main():
    white = Human(Color.WHITE)
    black = Human(Color.BLACK)
    board = Board(white, black)

    print(board)

    print(board.board[Coordinate.d8].is_on_board)
    print(board.board[Coordinate.e8].is_on_board)
Esempio n. 18
0
    def test_winRow(self):
        board = Board()
        board.getBoard()[0] = [1, 1, 1, 1, 1, 0]
        b = board.checkWinRow()
        self.assertTrue(b, "Not true")

        board.getBoard()[0] = [0, 1, 1, 1, 1, 1]
        b = board.checkWinRow()
        self.assertTrue(b, "Not true")
Esempio n. 19
0
 def restart(self):
     global root
     self.gui_board.container.destroy()
     self.gui_board = GuiBoard(Board(3, 3), root)
     self.gui_board.draw()
     self.initialize_buttons()
     # self.init_two_players_game()
     self.two_players_button.grid()
     self.init_two_players_game()
Esempio n. 20
0
 def __init__(self, host, port):
     self.HANDLER = Handler
     self.board = Board(7, 7)
     asyncore.dispatcher.__init__(self)
     self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
     self.bind((host, port))
     self.listen(5)
     print('Waiting for connection...')
     self.connections = []
Esempio n. 21
0
 def __init__(self):
     self._players = [
         Player(self, 0),
         Player(self, 1),
         Player(self, 2),
         Player(self, 3)
     ]
     self._board = Board(self._players)
     self._viewer = FourCornersViewer(moveEvent=self.makeMove)
     self._updateViewer()
Esempio n. 22
0
 def test_board(self):
     board = Board("data")
     board.move_player(1, 1, 'X')
     board.move_player(1, 2, 'X')
     board.move_player(1, 3, 'X')
     board.move_player(1, 4, 'X')
     board.move_computer()
     assert board.is_game_won() == False
     assert board.is_board_full() == False
     assert board.get_slot(1, 5) != 'O'
Esempio n. 23
0
 def __init__(self, player_one: Player = None, player_two: Player = None, verbose: bool = True) -> None:
     self._move_counter = 0
     self._board = Board(MAX_ROWS, MAX_COLUMNS)
     self._players = (
         player_one if player_one is not None else Player(
             SIGN_PLAYER_ONE, 'magenta'),
         player_two if player_two is not None else Player(
             SIGN_PLAYER_TWO, 'cyan')
     )
     self._verbose = verbose
Esempio n. 24
0
def main():
    root = Tk()
    root.title("Othello")
    root.geometry("800x800")
    b = Board()
    b.init_board('init.csv')
    g = GuiBoard(board=b, master=root)
    g.display_gui_board()

    root.mainloop()
Esempio n. 25
0
def test_block_fork(player_mark):
    other_mark = other_player(player_mark)
    ai = AI(player_mark)
    board = Board()
    board._rows = [[other_mark, ' ', ' '], [' ', player_mark, ' '],
                   [' ', ' ', other_mark]]
    assert ai.turn(board.representation()) in ((0, 2), (2, 0))

    board._rows = [[player_mark, ' ', ' '], [' ', other_mark, ' '],
                   [' ', ' ', other_mark]]
    assert ai.turn(board.representation()) in ((0, 2), (2, 0))
Esempio n. 26
0
def test_center(player_mark):
    other_mark = other_player(player_mark)
    ai = AI(player_mark)
    board = Board()
    board._rows = [[other_mark, ' ', ' '], [' ', player_mark, ' '],
                   [' ', ' ', other_mark]]
    assert ai._center(board.representation()) is None

    board._rows = [[player_mark, ' ', ' '], [' ', ' ', ' '],
                   [other_mark, ' ', other_mark]]
    assert ai._center(board.representation()) == (1, 1)
Esempio n. 27
0
    def __init__(self, player_x_type, player_o_type):
        """Instantiate a tic-tac-toe game.

        :param player_x_type: type of the first player (player x)
        :type player_x_type: Player
        :param player_o_type: type of the second player (player o)
        :type player_o_type: Player
        """
        self.board = Board()
        self.player_x = player_x_type(self.FIRST_PLAYER_MARK)
        self.player_o = player_o_type(self.SECOND_PLAYER_MARK)
Esempio n. 28
0
def test_create_fork(player_mark):
    other_mark = other_player(player_mark)
    ai = AI(player_mark)
    board = Board()
    board._rows = [[player_mark, ' ', ' '], [' ', other_mark, ' '],
                   [' ', ' ', player_mark]]
    assert ai.turn(board.representation()) in ((2, 0), (0, 2))

    board._rows = [[player_mark, ' ', ' '], [player_mark, ' ', ' '],
                   [' ', ' ', ' ']]
    assert ai._fork(board.representation()) == (1, 1)
Esempio n. 29
0
    def __init__(self, parent):
        self.parent = parent  # parent is root
        global root
        self.gui_board = GuiBoard(Board(3, 3), root)
        self.gui_board.draw()
        self.initialize_buttons()

        self.player1 = Player("AI", "#446CB3")
        self.player2 = Player("PLAYER", "#F4D03F")

        self.two_players_button.grid()
Esempio n. 30
0
 def __init__(self, fn = 'games.json'):
     try:
         with open(fn) as fh:
             self._games = json.load(fh)
     except FileNotFoundError:
         self._games = []
     self._logger = Console()         
     self._board = Board()
     self._user = User(self._board)
     self._computer = Computer(self._board, self._user )
     self._first = None
     self._game_over = False
     self._games_file = fn