Пример #1
0
 def _init(self):
     self.selected = None
     self.human_player = False
     self.board = Board()
     self.turn = RED
     self.valid_moves = {}
     self.display_buttons()
Пример #2
0
 def _init(self):
     self.selected = None  # which piece is selected
     self.board = Board(
     )  # the game will happen on the board so we initialize it inside the Game class
     self.turn = YELLOW  # which player's turn
     self.valid_moves = {
     }  # what the current valid moves are for whatever player is playing
Пример #3
0
 def __init__(self, win):
     self._init()
     self.selected = None
     self.board = Board()
     self.turn = RED
     self.valid_moves = {}
     self.win = win
    def _init(self):
        self.selected = None
        self.board = Board()
        self.turn = RED

        # dictionary of valid possible moves that can be taken from a position
        self.valid_moves = {}
Пример #5
0
    def simulate(self,
                 bot_white,
                 bot_black,
                 print_game=False,
                 starting_player=Player.white):
        """Simulates a number of games by two agents.

        Parameters
        -----------
        bot_white : Bot
            Bot that will play for the white side.
        bot_black : Bot
            Bot that will play for the black side.
        print_game : boolean (Default = False)
            If it's True it will print the board at each move.
            If it is not, then no board would be printed.
        starting_player : Player
            The player who would make the first move.

        """
        for _ in range(self.num_of_games):
            board = Board()
            self.display.assign_board(board)

            current_turn = starting_player
            winner = None
            while winner is None:
                choice = []
                if current_turn == Player.white:
                    choice = bot_white.select_move(board)
                else:
                    choice = bot_black.select_move(board)
                board.make_move(choice)

                winner = board.has_winner()

                if print_game:
                    self.display.print_board()
                    # Uncomment to see the number of pieces left
                    # self.display.print_pieces_left()

                current_turn = current_turn.other

            if winner is Player.white:
                self.white_wins += 1
                print("White WIN")
            elif winner is Player.black:
                self.black_wins += 1
                print("Black WIN")
            elif winner == "Tie":
                self.ties += 1
                print("TIE")

        print("White wins: " + str(self.white_wins))
        print("Black wins: " + str(self.black_wins))
        print("Ties: " + str(self.ties))
Пример #6
0
 def __init__(self, black_player, white_player):
     self._width = 3
     self._board = Board(self._width)
     self._black_player = black_player
     self._white_player = white_player
     self._current_player = self._black_player
     self._moves = []
     self._steps = 0
     self._state = Game.BEGIN
     self._winner = None
Пример #7
0
def main():
    clock = pygame.time.Clock()
    run = True
    board = Board()
    while (run):
        clock.tick(fps)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                pass

        board.draw(win)
        pygame.display.update()
    pygame.quit()
Пример #8
0
 def _init(self):
     '''
     de facto funkcja inicjalizująca wywoływana w __init__(), było to potrzebne aby łatwo robić resety
     mamy takie parametry jak selected - zaznaczony item (typu zwykła bierka/król)
     stworzenie obiektu Board (nasza plansza)
     aktualna tura
     dostępne ruchy do funkcji valid_moves
     pola dla wyjątków do obsługi nieco zawiłej procedury printowania wyjątków na ekranie gry pygame
     '''
     self.selected = None
     self.board = Board(self.win)
     self.turn = RED
     self.valid_moves = {}
     self.bad_move_exce = False
     self.outside_board_exce = False
Пример #9
0
def main():
    run = True
    clock = pygame.time.Clock()
    board = Board()

    while run:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.MOUSEBUTTONDOWN:
                pass
        board.draw(WIN)
        pygame.display.update()

    pygame.quit()
Пример #10
0
def main():
    run = True
    clock = pygame.time.Clock() 
    board = Board() #New Object

    #piece = board.get_piece(0,1)
    

    while run:
        clock.tick(FPS)
        
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                row, col = get_row_col_from_mouse(pos)
                piece = board.get_piece(row, col)
                board.move(piece, 4, 3)
        
        
        board.draw(WIN)
        pygame.display.update()

        
    pygame.quit()
Пример #11
0
def test_board_sets_up_tiles_correctly():
    """Trickier than it looks, row 1 is white ... row 2 is black... and that pattern repeats 4 times"""
    colors = 4 * (4 * [Color.WHITE, Color.BLACK] +
                  4 * [Color.BLACK, Color.WHITE])

    board = Board()

    for i in range(64):
        assert board.squares[i].color == colors[i]
Пример #12
0
def main():
    """
    run this function to run the game.
    event loop. 
    will run every x time per second and check if the player pressed on something and update the display
    """
    run = True  #boolean variable - remains true as long as there's no winner.
    clock = pygame.time.Clock()
    game = Game(WIN)  #is for game window
    board = Board()
    difficultyLevel = get_level()

    while run:
        clock.tick(FPS)

        if game.turn == WHITE:  #there are two palyers: White and Red
            value, new_board = minimax(game.get_board(), difficultyLevel + 1,
                                       WHITE, game)
            game.ai_move(new_board)

        if game.winner() != None:
            run = False

        for event in pygame.event.get():
            #check if events have happened at the current time
            if event.type == pygame.QUIT:
                run = False

            if event.type == pygame.MOUSEBUTTONDOWN:  #player press on mouse
                pos = pygame.mouse.get_pos()
                row, col = get_row_col_from_mouse(pos)
                game.select(row, col)

            pos = pygame.mouse.get_pos()
            row, col = get_row_col_from_mouse(pos)
        if (difficultyLevel < 3):
            game.update_board(row, col)
        else:
            game.update3(row, col)

    if game.winner() == WHITE:
        messagebox.showinfo("Game Over", "White is Winner")
    elif game.winner() == RED:
        messagebox.showinfo("Game Over", "RED is Winner")
    elif game.winner() == BLACK:
        messagebox.showinfo("Game Over",
                            "Too many moves with no change\n Result: Draw")
    elif game.winner() == PITCH:
        messagebox.showinfo("Game Over",
                            "Red has no more valid moves\nWhite is Winner\n")
    elif game.winner() == GRAY:
        messagebox.showinfo("Game Over",
                            "White has no more valid moves\nRed is Winner\n")
    pygame.quit()  #close board window
Пример #13
0
def main():
    run = True
    clock = pygame.time.Clock()
    board = Board()
    game = Game(WIN)

    piece = board.get_piece(0, 1)

    while run:
        clock.tick(FPS)

        if game.winner() != None:
            print(game.winner())
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if event.type == pygame.MOUSEBUTTONDOWN:
                pos = pygame.mouse.get_pos()
                row, col = get_row_col_from_mouse(pos)
                game.select(row, col)
        game.update()
    pygame.quit()
Пример #14
0
class Game(object):
    """Playing a game"""
    BEGIN = 0
    END = 1
    PROGRESS = 2

    def __init__(self, black_player, white_player):
        self._width = 3
        self._board = Board(self._width)
        self._black_player = black_player
        self._white_player = white_player
        self._current_player = self._black_player
        self._moves = []
        self._steps = 0
        self._state = Game.BEGIN
        self._winner = None

    @property
    def moves(self):
        return self._moves

    @property
    def steps(self):
        return self._steps

    def play(self):
        while self._state != Game.END:
            i, j = self._current_player.next_move(self._board)
            if self._current_player == self._black_player:
                self._board.move(i, j, Board.BLACK)
                self._current_player = self._white_player
                self._moves.append((i, j, Board.BLACK))
            else:
                self._board.move(i, j, Board.WHITE)
                self._current_player = self._black_player
                self._moves.append((i, j, Board.WHITE))
            if self._state == Game.BEGIN:
                self._state = Game.PROGRESS
            self._steps += 1

            if self._board.check_state() == Board.WHITE:
                self._winner = self._white_player
                self._state = Game.END

            if self._board.check_state() == Board.BLACK:
                self._winner = self._black_player
                self._state = Game.END

    @property
    def winner(self):
        if self._winner == self._white_player:
            return 'WHITE'
        elif self._winner == self._black_player:
            return 'BLACK'
        else:
            return 'Nobody'
    def get_board_position_2d(self, player):
        if self._player_1_board_position_2d is None:
            result = np.tile(
                0, [self.state.board_height(),
                    self.state.board_width()])

            for piece in self.state.get_uncaptured_pieces():
                x = int((piece.position - 1) / 4)
                y = (piece.position - 1) % 4

                value = (3 if piece.king else 1) * (1 if piece.player == 1 else
                                                    -1)
                result[x, y] = value
            self._player_1_board_position_2d = result

        return self._player_1_board_position_2d if player == 1 else (
            Board.flip_2d(self._player_1_board_position_2d) * -1)
Пример #16
0
class Game:
    def __init__(self, window):
        self._init()
        self.window = window  # the Game window on your device

    def update(self):
        self.board.draw(self.window)
        self.draw_valid_moves(self.valid_moves)
        pygame.display.update()

    def _init(self):
        self.selected = None  # which piece is selected
        self.board = Board(
        )  # the game will happen on the board so we initialize it inside the Game class
        self.turn = YELLOW  # which player's turn
        self.valid_moves = {
        }  # what the current valid moves are for whatever player is playing

    # to reinitialize the game
    def reset(self):
        self._init()

    def winner(self):
        return self.board.winner()

    def select(self, row, col):  # this is a recursive method
        if self.selected:  # in case user pressed on some piece
            result = self._move(row, col)
            # move the selected piece from row and col of the select method to row and col of the move method
            if not result:  # if the result is not valid (an empty square selected for example)
                self.selected = None  # nothing is selected
                self.select(
                    row, col
                )  # user has to select a new piece (so this is to call the method again)

        piece = self.board.get_piece(
            row, col)  # define the piece correspond to selected row and col
        if piece != 0 and piece.color == self.turn:
            # if the selected piece exists and corresponds to the player's color:
            self.selected = piece  # the piece is selected
            self.valid_moves = self.board.get_valid_moves(piece)
            return True  # the selection is valid

        return False  # the selected piece is not valid, try again

    def _move(self, row, col):
        piece = self.board.get_piece(row, col)
        if self.selected and piece == 0 and (row, col) in self.valid_moves:
            #(piece == 0 to make sure that where we are going to move the piece is an empty square with no piece on it already!)
            self.board.move(self.selected, row,
                            col)  # move the valid selected piece
            skipped = self.valid_moves[(row, col)]
            if skipped:
                self.board.remove(
                    skipped)  # remove the eaten pieces from the board
            self.change_turn()  # change turn so the second player can play
        else:
            return False

        return True

    def draw_valid_moves(self, moves):
        for move in moves:
            row, col = move
            # since moves is a dictionary of tuples (row, col)
            pygame.draw.circle(self.window,
                               BLUE, (col * SQUARE_SIZE + SQUARE_SIZE // 2,
                                      row * SQUARE_SIZE + SQUARE_SIZE // 2),
                               radius=15)

    def change_turn(self):
        self.valid_moves = {}
        if self.turn == WHITE:
            self.turn = YELLOW
        else:
            self.turn = WHITE
Пример #17
0
class Game:
    def __init__(self, win):
        self._init()
        self.win = win
        self.removed_counter = 0
        self.valid_moves = {}

    def winner(self):
        return self.board.winner()

    def _is_stuck(self, matchWinner):
        return matchWinner

    def update_board(self, row, col):
        self.board.draw1(self.win, row, col)
        self.draw_valid_moves(self.valid_moves)
        pygame.display.update()

    def update3(self, row3, col3):
        self.board.draw3(self.win, row3, col3)

        self.board.draw_selected(self.win, row3, col3)
        pygame.display.update()

    def _init(self):
        self.selected = None
        self.board = Board()
        self.turn = RED
        self.valid_moves = {}  #a dictionary of current vallid moves

    def reset(self):
        self._init()

    def select(self, row, col):
        """
        get here when the player press on piece
        if selected is vallid move piece if not (=not result) try again
        """
        if self.selected:
            rectOne = (100, 100, 100, 100)
            pygame.draw.circle(self.win, BLUE,
                               (col * SQUARE_SIZE + SQUARE_SIZE // 2,
                                row * SQUARE_SIZE + SQUARE_SIZE // 2), 8)
            pygame.draw.circle(self.win, GRAY,
                               (col * SQUARE_SIZE, row * SQUARE_SIZE), 14)
            result = self.move(row, col)  #try to move
            if not result:
                self.selected = None  #delete invalid selected
                self.select(row, col)  #reselect

        piece = self.board.get_piece(row, col)

        self.board.draw_selected(self.win, row, col)
        if piece != 0 and piece.color == self.turn:
            self.selected = piece
            self.valid_moves = self.board.get_valid_moves(piece)
            if not self.valid_moves:
                self._is_stuck("WHITE")
            return True

        return False

    def move(self, row, col):
        piece = self.board.get_piece(row, col)

        pygame.draw.circle(self.win, YELLOW,
                           (col * SQUARE_SIZE + SQUARE_SIZE // 2,
                            row * SQUARE_SIZE + SQUARE_SIZE // 2), 8)
        #if the player selected an empty square and it's valid move
        if self.selected and piece == 0 and (row, col) in self.valid_moves:
            pygame.draw.circle(self.win, BLUE,
                               (col * SQUARE_SIZE + SQUARE_SIZE // 2,
                                row * SQUARE_SIZE + SQUARE_SIZE // 2), 8)
            self.board.move(self.selected, row, col)
            skipped = self.valid_moves[(row, col)]
            if skipped:
                self.removed_counter = 0
                self.board.remove(skipped)
            else:
                self.removed_counter = self.removed_counter + 1
            self.change_turn()
        else:
            return False
        return True

    def draw_valid_moves(self, moves):
        for move in moves:
            row, col = move
            pygame.draw.circle(self.win, BLUE,
                               (col * SQUARE_SIZE + SQUARE_SIZE // 2,
                                row * SQUARE_SIZE + SQUARE_SIZE // 2), 8)

    def change_turn(self):
        self.valid_moves = {}
        if self.turn == RED:
            self.turn = WHITE
        else:
            self.turn = RED

    def get_board(self):
        return self.board

    def ai_move(
        self, board
    ):  #Since Game is a Controller class, it connects between the Board class (The View)
        # and  the Model- the Minimax Algorithm Class.
        self.board = board
        self.change_turn()
Пример #18
0
 def _init(self):
     self.selected = None
     self.board = Board()
     self.turn = RED
     self.valid_moves = {}  #a dictionary of current vallid moves
Пример #19
0
def h_peices_num(board: Board, player_num):
    return board.count_movable_player_pieces(player_num)
Пример #20
0
 def _init(self):
     self.selected = None
     self.board = Board()
     self.turn = creamWhite
     self.validMoves = {}
Пример #21
0
class Game:
    def __init__(self, win):
        '''
        de facto wywolanie _init() przypisanie zmiennej win która jest naszym oknem
        '''
        self.win = win
        self._init()

    def update(self):
        '''
        funkcja update uruchamiana w każdym obiegu głównej funkcji main,
        rysuje ustawienie szachownicy jak i samą szachownicę
        dozwolone ruchy o ile istnieją
        po części obłsuguje wyjątki poprzez printowanie tekstów "wywoływanych" przez wyjątki  za pomocą zmiany stanów zmiennych
        kontrolowanie czy któryś z graczy nie wygrał meczu poprzez sprawdzanie zmienne winner, jesli tak obsługuje
        printa z informacja kto wygrał
        '''
        self.board.draw(self.win)
        self.printing_moves()
        self.draw_valid_moves(self.valid_moves)
        if self.bad_move_exce:
            self.bad_move_exe()
            pygame.time.delay(1000)
        self.bad_move_exce = False
        if self.outside_board_exce:
            self.outside_board_exe()
            pygame.time.delay(1000)
        self.outside_board_exce = False
        if self.winner() != None:
            if self.winner() == WHITE:
                pygame.draw.rect(
                    self.win, GREY,
                    (1 * SQUARE_SIZE + SQUARE_SIZE // 2, 4 * SQUARE_SIZE,
                     5 * SQUARE_SIZE, SQUARE_SIZE + 5))
                self.show_text("WHITE HAS WON", 4, 1.5, WHITE)
            else:
                pygame.draw.rect(
                    self.win, GREY,
                    (1 * SQUARE_SIZE + SQUARE_SIZE // 2, 4 * SQUARE_SIZE,
                     5 * SQUARE_SIZE, SQUARE_SIZE + 5))
                self.show_text("RED HAS WON", 4, 2, WHITE)
        pygame.display.update()

    def show_text(self, content, x, y, rgb):
        '''
        printowanie tekstu o zadanym kolorze rgb na ekranie w konkretnym miejscu
        '''
        text = FONT2.render(content, True, rgb)
        self.win.blit(text, (y * SQUARE_SIZE + SQUARE_SIZE // 4 + 5,
                             x * SQUARE_SIZE + SQUARE_SIZE // 4 + 5))

    def _init(self):
        '''
        de facto funkcja inicjalizująca wywoływana w __init__(), było to potrzebne aby łatwo robić resety
        mamy takie parametry jak selected - zaznaczony item (typu zwykła bierka/król)
        stworzenie obiektu Board (nasza plansza)
        aktualna tura
        dostępne ruchy do funkcji valid_moves
        pola dla wyjątków do obsługi nieco zawiłej procedury printowania wyjątków na ekranie gry pygame
        '''
        self.selected = None
        self.board = Board(self.win)
        self.turn = RED
        self.valid_moves = {}
        self.bad_move_exce = False
        self.outside_board_exce = False

    def reset(self):
        '''
        resetowanie gry poprzez ponowne wywołanie funkcji _init()
        :return:
        '''
        self._init()

    def select(self, row, col):
        '''
        wybranie konkretnego itemu z naszej tablicy (szachownica ma dostępne pola 0 - puste, Piece - obiekt podsatwowej bierki, King - bierka król)
        wybieranie przebiega na podsatwie zmiennych row,col które symbolizują pola 8x8 planszy
        obsługa dwóch wyjątków - łapanie wyjątku odnośnie "bad move" kliknięcie podczas tury ruchu pole które nie jest dozwolonym ruchem
        oraz podnoszenie wyjątku o kliknięciu w dolny pasek który nie jest responsywny a jest jedynie tłem
        w dodatku metoda obsługuje restart gry gdy przekazane współrzędne odpowiadają naszemu przyciskowi

        '''
        if row != 8:
            # jeśli mamy już coś zaznaczonego (bierkę) próbujemy zrobić ruch
            if self.selected:
                try:
                    result = self._move(row, col)
                    if not result:
                        self.selected = None
                        self.select(row, col)
                except BadMoveExceptions:
                    self.bad_move_exce = True
                    print("bad move")
            # pobieramy wartość z pod konkretnego indeksu na tablicy
            piece = self.board.get_piece(row, col)
            # jeżeli obiekt != znaczy ze jest to jakaś bierka, sprawdzamy czy to nasza tura
            # i czy mamy jakieś ruchy dla tej konkretnej instacji (bierki)
            # jeśli tak zracamy true, jesli nie false
            if piece != 0 and piece.color == self.turn:
                self.selected = piece
                self.valid_moves = self.board.get_valid_moves(piece)
                return True
            elif piece != 0 and piece.color != self.turn:
                print("zly kolor")
            return False
        # jeżeli klikniecie jest w 8 rząd czyli poniżej planszy (0-7 rzędy) sprawdzamy czy kliknęliśmy w guzik
        elif col == 0 or col == 1:
            self.restart_game()
        # jeśli kliknęlismy poza plansze ale nie w guzik wyrzucamy błąd
        else:
            raise OutsideBoardExceptions()

    def bad_move_exe(self):
        '''
        obsługa printu dla niedozwolonego ruchu
        '''
        pygame.draw.rect(self.win, GREY,
                         (1 * SQUARE_SIZE + SQUARE_SIZE // 2, 4 * SQUARE_SIZE,
                          5 * SQUARE_SIZE, SQUARE_SIZE + 5))
        self.show_text("BAD MOVE", 4, 1.5, BLACK)

    def outside_board_exe(self):
        '''
        obsługa printu dla kliknięcie poza obszar planszy który jednak dalej jest w oknie gry
        '''
        pygame.draw.rect(self.win, GREY,
                         (1 * SQUARE_SIZE + SQUARE_SIZE // 2, 4 * SQUARE_SIZE,
                          5 * SQUARE_SIZE, SQUARE_SIZE + 5))
        self.show_text("Outside board", 4, 1.5, BLACK)

    def restart_game(self):
        '''
        metoda restartująca poprzez ponowne wywołanie inita który inicjalizuje wartości
        '''
        print("restart")
        self._init()

    def _move(self, row, col):
        '''
        metoda sprawdzająca czy czy pod podanymi współrzędnymi znajduje się się 0 czyli brak jakiegoś obiektu i
        czy można tam przestawić naszą bierkę
        '''
        piece = self.board.get_piece(row, col)
        if self.selected and piece == 0 and (row, col) in self.valid_moves:
            self.board.move(self.selected, row, col)
            skipped = self.valid_moves[(row, col)]
            if skipped:
                self.board.remove(skipped)
            self.change_turn()
        else:
            if piece == 0:
                raise BadMoveExceptions()
        return True

    def change_turn(self):
        '''
        metoda która zmienia turę bazując na obecnej turze
        :return:
        '''
        self.valid_moves = {}
        if self.turn == RED:
            self.turn = WHITE
        elif self.turn == WHITE:
            self.turn = RED

    def draw_valid_moves(self, moves):
        '''
        na podstawie elementów w valid_moves = możliwe ruchy rysujemy niebieskie kropki w tych punktach
        '''
        for move in moves:
            row, col = move
            pygame.draw.circle(self.win, BLUE,
                               (col * SQUARE_SIZE + SQUARE_SIZE // 2,
                                row * SQUARE_SIZE + SQUARE_SIZE // 2), 12)

    def winner(self):
        '''
        metoda zwracająca zwycięzce na podstawie zmiennych zawartych w klasie
        '''
        return self.board.winner()

    def printing_moves(self):
        '''
        obsługa printowania tury gracza na dole ekranu z grą
        '''
        if self.turn == RED:
            self.show_text("RED's MOVE", 7.8, 2, BLACK)
        else:
            self.show_text("WHITE's MOVE", 7.8, 2, BLACK)
Пример #22
0
 def _init(self):
     self.selected = None
     self.board = Board()
     self.turn = RED
     self.valid_moves = {}
Пример #23
0
def fake_board():
    return Board(empty=True)
Пример #24
0
from checkers.board import Board
from checkers.player import *

# Constant
BOARD_DIMENSIONS = 8
NUM_OF_PIECES = 12
TILE_WIDTH = 1
TILE_HEIGHT = 1

# Initiate game variables and objects
gameOver = False
isBlackTurn = False
board = Board(8)
aiPlayer = AIPlayer(NUM_OF_PIECES, 'Black', board)
human = HomanPlayer(NUM_OF_PIECES, 'White', board)

while not gameOver:
    # White (human) starts
    board.win.getMouse()  # just to keep the window open
    human.play(board)
    aiPlayer.play(board)
Пример #25
0
def test_board():
    """test init"""
    board = Board(3)
    zero_field = np.zeros((3, 3), dtype='int8')
    game_field = board.field

    assert board
    assert (zero_field == game_field).all()
    assert board.check_state() is None

    """test function move"""
    board.move(0, 0, Board.BLACK)
    board.move(0, 1, Board.WHITE)
    game_field = board.field
    assert game_field[0, 0] == Board.BLACK
    assert game_field[0, 1] == Board.WHITE

    try:
        board.move(0, 1, Board.WHITE)
    except AssertionError:
        pass

    try:
        board.move(2, 2, 0)
    except AssertionError:
        pass

    """test function check_win"""
    board.remove_all()
    board.move(2, 0, Board.BLACK)
    board.move(0, 2, Board.WHITE)
    board.move(1, 2, Board.BLACK)
    board.move(2, 1, Board.WHITE)
    board.move(0, 0, Board.BLACK)
    board.move(1, 1, Board.WHITE)
    assert board.check_state() != Board.WHITE

    """test function remove"""
    board.remove(0, 2)
    board.remove(1, 1)
    board.remove(2, 0)
    game_field = board.field
    assert game_field[0, 2] == 0
    assert game_field[1, 1] == 0
    assert game_field[2, 0] == 0

    """test function remove_all"""
    board.remove_all()
    game_field = board.field
    assert (zero_field == game_field).all()

    """test function legal_moves"""
    board.move(0, 0, Board.BLACK)
    board.move(0, 1, Board.WHITE)
    board.move(0, 2, Board.BLACK)
    board.move(1, 0, Board.BLACK)
    board.move(1, 1, Board.WHITE)
    board.move(1, 2, Board.BLACK)
    moves = set([(2, 0), (2, 1), (2, 2)])
    assert board.legal_moves() == moves
Пример #26
0
class Game:
    def __init__(self, win):
        self._init()
        self.win = win

    def update(self):
        self.board.draw(self.win)
        self.drawValidMoves(self.validMoves)
        pygame.display.update()

    def _init(self):
        self.selected = None
        self.board = Board()
        self.turn = creamWhite
        self.validMoves = {}

    def winner(self):
        return self.board.winner()

    def reset(self):
        self._init()

    def select(self, row, col):
        if self.selected:
            result = self._move(row, col)
            if not result:
                self.selected = None
                self.select(row, col)

        piece = self.board.getPiece(row, col)
        if piece != 0 and piece.color == self.turn:
            self.selected = piece
            self.validMoves = self.board.getValidMoves(piece)
            return True

        return False

    def _move(self, row, col):
        piece = self.board.getPiece(row, col)
        if self.selected and piece == 0 and (row, col) in self.validMoves:
            self.board.move(self.selected, row, col)
            skipped = self.validMoves[(row, col)]
            if skipped:
                self.board.remove(skipped)
            self.changeTurn()
        else:
            return False

        return True

    def drawValidMoves(self, moves):
        for move in moves:
            row, col = move
            pygame.draw.circle(self.win, BLUE,
                               (col * SQUARE_SIZE + SQUARE_SIZE // 2,
                                row * SQUARE_SIZE + SQUARE_SIZE // 2), 15)

    def changeTurn(self):
        self.validMoves = {}
        if self.turn == creamWhite:
            self.turn = WHITE
        else:
            self.turn = creamWhite

    def getBoard(self):
        return self.board

    def aiMove(self, board):
        self.board = board
        self.changeTurn()
Пример #27
0
# -*- coding: UTF-8 -*-
from checkers.player import HumanPlayer, RandomPlayer
from checkers.board import Board

game_board = Board(3)
game_board.move(0, 0, Board.BLACK)
game_board.move(0, 1, Board.WHITE)

name = 'James'
a_player = HumanPlayer(name)
r_player = RandomPlayer('Random')


def test_human_player():
    assert a_player.name == 'James'
    assert r_player.name == 'Random'

    # i, j = a_player.next_move(game_board)
    # """input 1, 2"""
    # assert (i, j) == (1, 2)
Пример #28
0
def main():
    run = True
    clock = pygame.time.Clock()

    board = Board()
    board.create_board()

    while (run):
        clock.tick(FPS)

        for e in pygame.event.get():
            if (e.type == pygame.QUIT):
                run = False
            if (e.type == pygame.MOUSEBUTTONDOWN):
                pos = pygame.mouse.get_pos()
                col, row = get_row_col_from_mouse(pos)
                piece = board.get_piece(row, col)
                if piece:
                    if piece.is_hint and board.current_piece_coords[0] != None:
                        board.move(board.current_piece_coords[0],
                                   board.current_piece_coords[1], row, col)
                    else:
                        if board.is_hint_shown:
                            board.remove_hints()
                        else:
                            board.mark_neighbours(piece)

        board.draw_cubes(WIN)
        board.draw_pieces(WIN)
        pygame.display.update()

        pass

    pygame.quit()
Пример #29
0
class Game:
    def __init__(self, win):
        self._init()
        self.win = win

    def update(self):
        self.board.draw(self.win)
        self.draw_valid_moves(self.valid_moves)
        pygame.display.update()

    # _init makes it a private method of the class
    def _init(self):
        self.selected = None
        self.board = Board()
        self.turn = RED
        self.valid_moves = {}

    def winner(self):
        return self.board.winner()

    def reset(self):
        self._init()

    def select(self, row, col):
        if self.selected:
            result = self._move(row, col)
            if not result:
                self.selected = None
                self.select(row, col)

        piece = self.board.get_piece(row, col)
        if piece != 0 and piece.color == self.turn:
            self.selected = piece
            self.valid_moves = self.board.get_valid_moves(piece)
            return True

        return False

    def _move(self, row, col):
        piece = self.board.get_piece(row, col)
        if self.selected and piece == 0 and (row, col) in self.valid_moves:
            self.board.move(self.selected, row, col)
            skipped = self.valid_moves[(row, col)]
            if skipped:
                self.board.remove(skipped)
            self.change_turn()
        else:
            return False

        return True

    def draw_valid_moves(self, moves):
        for move in moves:
            row, col = move
            pygame.draw.circle(self.win, BLUE,
                               (col * SQUARE_SIZE + SQUARE_SIZE // 2,
                                row * SQUARE_SIZE + SQUARE_SIZE // 2), 15)

    def change_turn(self):
        self.valid_moves = {}
        if self.turn == RED:
            self.turn = WHITE
        else:
            self.turn = RED
class Game:
    def __init__(self, win):
        self._init()
        self.win = win

    # Update pygame display using this method
    def update(self):
        self.board.draw(self.win)
        self.draw_valid_moves(self.valid_moves)
        pygame.display.update()

    # Initilizing => private method init
    def _init(self):
        self.selected = None
        self.board = Board()
        self.turn = RED

        # dictionary of valid possible moves that can be taken from a position
        self.valid_moves = {}

    # Reset the game
    def reset(self):
        self._init()

    # When select something => call the select method, tell the row and col selected and do something based on that
    def select(self, row, col):

        # Move the already selected piece to the desired row,col
        if self.selected:
            result = self._move(row, col)

            # If incorrect/invalid move => reset the selection and reselect row and col
            if not result:
                self.selected = None
                self.select(row, col)

        piece = self.board.get_piece(row, col)

        # not selecting an empty piece and the color of the piece is same as the turn
        if piece != 0 and piece.color == self.turn:
            self.selected = piece
            self.valid_moves = self.board.get_valid_moves(piece)
            return True

        return False

    # Move currently selected piece to the row and col
    def _move(self, row, col):
        piece = self.board.get_piece(row, col)

        # If we have selected something and the piece that we selected is empty and the row, col is a valid move then we can move it
        if self.selected and piece == 0 and (row, col) in self.valid_moves:
            self.board.move(self.selected, row, col)
            skipped = self.valid_moves[(row, col)]
            if skipped:
                self.board.remove(skipped)
            self.change_turn()
        else:
            return False

        return True

    # Change the turn after the move
    def change_turn(self):
        self.valid_moves = []
        if self.turn == RED:
            self.turn = WHITE
        else:
            self.turn = RED

    def draw_valid_moves(self, moves):
        for move in moves:
            row, col = move
            pygame.draw.circle(self.win, BLUE,
                               (col * SQUARE_SIZE + SQUARE_SIZE // 2,
                                row * SQUARE_SIZE + SQUARE_SIZE // 2), 15)

    def winner(self):
        return self.board.winner()