Esempio n. 1
0
 def test_move(PosY, PosX, DestPosY, DestPosX):
     game_state = ChessEngine.GameState()
     move = ChessEngine.Move([PosY, PosX], [DestPosX, DestPosY],
                             game_state.board)
     game_state.make_move(move)
     piece = game_state.board[DestPosX][DestPosY]
     return piece
Esempio n. 2
0
def main():
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    screen.fill(p.Color("white"))
    gs = ChessEngine.GameState()
    loadImages()
    running = True
    selectedSq = ()
    playerClicks = []
    validMoves = []
    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False

            if e.type == p.MOUSEBUTTONDOWN:
                location = p.mouse.get_pos()
                col = location[0]//SQ_SIZE
                row = location[1]//SQ_SIZE
                selectedSq = (row, col)
                playerClicks.append((row, col))
                if len(playerClicks) == 1:
                    if gs.board[row][col][0] == ("w" if gs.whiteToMove else "b"): #Valid selection
                        validMoves = gs.generateValidMoves(row, col)
                    else:
                        playerClicks = []

                elif len(playerClicks) == 2:
                    move = ChessEngine.Move(playerClicks[0][0], playerClicks[0][1], row, col)
                    if gs.checkValidMove(move, validMoves):
                        gs.makeMove(move)
                    playerClicks = []

        drawGameState(screen, gs, selectedSq, validMoves)
        p.display.flip()
Esempio n. 3
0
def main():
    p.init()
    screen=p.display.set_mode((Width,Height))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    gs=ChessEngine.GameState()
    print(gs.board)
Esempio n. 4
0
def main():
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    clock = pygame.time.Clock()
    screen.fill(pygame.Color("white"))
    game_state = ChessEngine.GameState()  # GAME_STATE
    validMoves = game_state.getValidMoves()
    moveMade = False  # flag variable for when a move is made

    load_images()
    running = True
    sqSelected = ()  # Square clicked by user tuple(row, col)
    playerClicks = []  # Where user clicked after list[(row, col), (row2,col2)]

    while running:
        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                running = False

            # mouse handler

            elif e.type == pygame.MOUSEBUTTONDOWN:
                location = pygame.mouse.get_pos()  # (x,y) location of mouse
                col = location[0] // SQ_SIZE
                row = location[1] // SQ_SIZE
                if sqSelected == (
                        row, col):  # The user clicked the same square twice
                    sqSelected = ()  # unselect
                    playerClicks = []  # clear clicks
                else:
                    sqSelected = (row, col)
                    playerClicks.append(sqSelected)
                if len(playerClicks) == 2:  # after 2nd click
                    move = ChessEngine.Move(playerClicks[0], playerClicks[1],
                                            game_state.board)
                    print(move.get_chess_notation())
                    for i in range(len(validMoves)):
                        if move == validMoves[i]:
                            game_state.make_move(validMoves[i])
                            moveMade = True
                            sqSelected = ()  # Reset clicks
                            playerClicks = []  # Reset clicks
                    if not moveMade:
                        playerClicks = [sqSelected]

            # key handler
            elif e.type == pygame.KEYDOWN:
                if e.key == pygame.K_z:  # "z" pressed
                    game_state.undo_move()
                    moveMade = True

        # Create new valid moves after move
        if moveMade:
            validMoves = game_state.getValidMoves()
            moveMade = False

        drawGameState(screen, game_state)
        clock.tick(15)
        pygame.display.flip()
Esempio n. 5
0
 def test_move(PosY, PosX, DestPosY, DestPosX, figure):
     game_state = ChessEngine.GameState()
     game_state.clearBoard()
     game_state.set_figure_in_position(PosY, PosX, figure)
     move = ChessEngine.Move([PosY, PosX], [DestPosX, DestPosY],
                             game_state.board)
     game_state.make_move(move)
     piece = game_state.board[DestPosX][DestPosY]
     return piece
Esempio n. 6
0
def main():
    # initialise pygame
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))

    gs = ChessEngine.GameState()
    validMoves = gs.getValidMoves()
    moveMade = False  #flag to check the move made

    loadImages()
    running = True
    sqSelected = ()  #keeps track of last click of the user, Tuple
    playerClicks = []  #keeps a track of player clicks, Two tuples. (
    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False
            #Mouse Listener
            elif e.type == p.MOUSEBUTTONDOWN:
                location = p.mouse.get_pos()  # x,y cords of mouse click
                col = location[0] // SQ_SIZE
                row = location[1] // SQ_SIZE
                if sqSelected == (row, col):
                    sqSelected = ()  # deselect
                    playerClicks = []  # clear player clicks
                else:
                    sqSelected = (row, col)
                    playerClicks.append(sqSelected)
                if len(playerClicks) == 2:
                    move = ChessEngine.Move(playerClicks[0], playerClicks[1],
                                            gs.board)
                    print(move.getChessNotation())
                    for i in range(len(validMoves)):
                        if move == validMoves[i]:
                            gs.makeMove(move)
                            moveMade = True
                            sqSelected = ()  # reset clicks
                            playerClicks = []
                    if not moveMade:
                        playerClicks = [sqSelected]

            # Keyboard Listener
            elif e.type == p.KEYDOWN:
                if e.key == p.K_z:  #Undo when z is pressed
                    gs.UndoMove()
                    moveMade = True

        if moveMade:
            validMoves = gs.getValidMoves()
            moveMade = False

        drawGameState(screen, gs)
        clock.tick(MAX_FPS)
        p.display.flip()
Esempio n. 7
0
def main():
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    gs = ChessEngine.GameState()
    validMoves = gs.getValidMoves()
    moveMade = False  #flag variable for when a move is made

    load_images()
    running = True
    sqSelected = ()  #keeps track of the last click of the user
    playerClicks = []  #keeps track of player clicks
    while (running):
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False
            #clicking
            elif e.type == p.MOUSEBUTTONDOWN:
                location = p.mouse.get_pos()  #x and y location of mousezx
                col = location[0] // SQ_SIZE
                row = location[1] // SQ_SIZE
                if sqSelected == (row, col):  #clicking the same square cancels
                    sqSelected = ()
                    playerClicks = []
                else:
                    sqSelected = (row, col)
                    playerClicks.append(sqSelected)
                if len(playerClicks) == 2:
                    move = ChessEngine.Move(playerClicks[0], playerClicks[1],
                                            gs.board)
                    for i in range(len(validMoves)):
                        if move == validMoves[i]:
                            print(validMoves[i].getChessNotation())
                            gs.makeMove(validMoves[i])
                            moveMade = True
                            sqSelected = ()  #reset user click
                            playerClicks = []
                    if not moveMade:
                        print('Invalid Move')
                        sqSelected = ()
                        playerClicks = []
            #key press
            elif e.type == p.KEYDOWN:
                if e.key == p.K_z:
                    gs.undoMove()
                    moveMade = True

            if moveMade:
                validMoves = gs.getValidMoves()
                moveMade = False

        draw_gamestate(screen, gs)
        clock.tick(MAX_FPS)
        p.display.flip()
Esempio n. 8
0
def main():
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("White"))
    gs = ChessEngine.GameState()
    validMoves = gs.getValidMoves()
    moveMade = False
    loadImages()
    running = True
    sqSelected = ()
    playerClicks = []
    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False
            #souris
            elif e.type == p.MOUSEBUTTONDOWN:
                location = p.mouse.get_pos()  #(x,y) position de la souris
                col = location[0] // SQ_SIZE
                row = location[1] // SQ_SIZE
                if sqSelected == (
                        row, col
                ):  #l'utilisateur clique sur le même carré deux fois
                    sqSelected = ()  #déselectionne la case
                    playerClicks = []  #efface/enlève le click du joueur
                else:
                    sqSelected = (row, col)
                    playerClicks.append(sqSelected)
                if len(playerClicks) == 2:  #après le deuxième click
                    move = ChessEngine.Move(playerClicks[0], playerClicks[1],
                                            gs.board)
                    print(move.getChessNotation())
                    for i in range(len(validMoves)):
                        if move == validMoves[i]:
                            gs.makeMove(validMoves[i])
                            moveMade = True
                            sqSelected = ()  #reset le click
                            playerClicks = []
                    if not moveMade:
                        playerClicks = [sqSelected]
            #clavier
            elif e.type == p.KEYDOWN:
                if e.key == p.K_z:  #annule le coup quand w(w = z en qwerty) est pressé
                    gs.undoMove()
                    moveMade = True

        if moveMade:
            validMoves = gs.getValidMoves()
            moveMade = False

        drawGameState(screen, gs)
        clock.tick(MAX_FPS)
        p.display.flip()
def main():
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    gs = ChessEngine.GameState()
    validMoves = gs.getValidMoves()
    moveMade = False

    loadImages()
    running = True
    sqSelected = ()  #no square is selected
    playerClicks = []  #keep trac k of player place

    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False
            elif e.type == p.MOUSEBUTTONDOWN:
                location = p.mouse.get_pos()
                col = location[0] // SQ_SIZE
                row = location[1] // SQ_SIZE
                if sqSelected == (row, col):  # clicks same square twice
                    sqSelected = ()
                    playerClicks = []
                else:
                    sqSelected = (row, col)
                    playerClicks.append(sqSelected)
                if len(playerClicks) == 2:
                    move = ChessEngine.Move(playerClicks[0], playerClicks[1],
                                            gs.board)
                    print(move.getChessNotation())
                    for i in range(len(validMoves)):
                        if move == validMoves[i]:
                            gs.makeMove(validMoves[i])
                            moveMade = True
                            sqSelected = ()
                            playerClicks = []
                    if not moveMade:
                        playerClicks = [sqSelected]

            elif e.type == p.KEYDOWN:
                if e.key == p.K_z:
                    gs.undoMove()
                    moveMade = True

        if moveMade:
            validMoves = gs.getValidMoves()
            moveMade = False

        drawGameState(screen, gs)
        clock.tick(MAX_FPS)
        p.display.flip()
Esempio n. 10
0
def main():
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    gs = ChessEngine.GameState()
    validMoves = gs.getValidMoves()
    moveMade = False  #flag variable for when a move is made

    loadImages()  #Load once, move images around
    running = True
    sqSelected = (
    )  #Intial selection is empty, tracks last click of user (row, col)
    playerClicks = []  #list with 2 tuples: [(6, 5), (4, 4)] pawn move tracked
    while running:
        for e in p.event.get():
            if e.type == p.QUIT:  #exit strategy
                running = FALSE
                #MouseFunctions
            elif e.type == p.MOUSEBUTTONDOWN:
                location = p.mouse.get_pos()  #Where is the mouse
                col = location[0] // SQ_SIZE
                row = location[1] // SQ_SIZE
                if sqSelected == (
                        row, col
                ):  #this clears the selection after a 2nd click on a square
                    sqSelected = ()
                    Playerclicks = []
                else:
                    sqSelected = (row, col)
                    playerClicks.append(sqSelected)
                if len(playerClicks
                       ) == 2:  #Make a move on the second unique click
                    move = ChessEngine.Move(playerClicks[0], playerClicks[1],
                                            gs.board)
                    print(move.getChessNotation())
                    if move in validMoves:
                        gs.makeMove(move)
                        moveMade = True
                    sqSelected = ()  #reset the click count
                    playerClicks = []
                #Key functions
            elif e.type == p.KEYDOWN:
                if e.key == p.K_z:  #undo when keyboard z is pressed
                    gs.undoMove()
                    moveMade = True
        if moveMade:
            validMoves = gs.getValidMoves()
            movemade = False

        drawGameState(screen, gs)
        clock.tick(MAX_FPS)
        p.display.flip()
Esempio n. 11
0
def main():
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    gs = ChessEngine.GameState()
    validMoves = gs.getValidMoves()
    moveMade = False #flag varible for when a move is made

    loadImages()
    running = True
    sqSelected = () #nosquare is selected at first. Keeps track of the last click of the user 
    playerClicks = [] #keeps track of player's clicks
    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False
                #mouse handler
            elif e.type == p.MOUSEBUTTONDOWN:
                location = p.mouse.get_pos()
                col = location[0]//SQ_SIZE
                row = location[1]//SQ_SIZE
                if sqSelected == (row, col): #if the user clicks the smae square twice
                    sqSelected = ()
                    playerClicks =[]
                else:
                    sqSelected = (row, col)
                    playerClicks.append(sqSelected)
                if len(playerClicks) == 2 :
                    move = ChessEngine.Move(playerClicks[0], playerClicks[1], gs.board)
                    print(playerClicks)
                    print(move.getChessNotation())
                    if move in validMoves:
                        gs.makeMove(move)
                        moveMade = True

                    sqSelected = () #reset clicks
                    playerClicks = []
                #key handler
            elif e.type == p.KEYDOWN:
                if e.key == p.K_z: #undo when 'z' is pressed
                    gs.undoMove()
                    moveMade = True

        if moveMade:
            validMoves = gs.getValidMoves()
            moveMade = False

                

        drawGameState(screen, gs)
        clock.tick(MAX_FPS)
        p.display.flip()
Esempio n. 12
0
def main():
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color('white'))
    gs = ChessEngine.GameState()
    valid_moves = gs.get_valid_moves()
    move_made = False  # flag variable for when a move is made

    load_images()  # only do this once, before the while loop
    running = True
    sq_selected: Tuple = ()  # no square is selected, keep track of the last click of the user (tuple: (row, col))
    player_clicks = []  # keep track of player clicks (two tuples: [(6, 4), (4, 4)])

    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False

            # mouse handler
            elif e.type == p.MOUSEBUTTONDOWN:
                location = p.mouse.get_pos()  # (x,y) location of mouse
                col = location[0] // SQ_SIZE
                row = location[1] // SQ_SIZE
                if sq_selected == (row, col):  # the user clicked the same square twice
                    sq_selected = ()  # unselect
                    player_clicks = []  # clear player clicks
                else:
                    sq_selected = (row, col)
                    player_clicks.append(sq_selected)  # append for both 1st and 2nd clicks
                if len(player_clicks) == 2:  # after 2nd click
                    move = ChessEngine.Move(player_clicks[0], player_clicks[1], gs.board)
                    print(move.get_chess_notation())
                    if move in valid_moves:
                        gs.make_move(move)
                        move_made = True
                    sq_selected = ()  # reset user clicks
                    player_clicks = []

            # key handlers
            elif e.type == p.KEYDOWN:
                if e.key == p.K_z:  # undo when 'z' is pressed
                    gs.undo_move()
                    move_made = True

        if move_made:
            valid_moves = gs.get_valid_moves()
            move_made = False

        draw_game_state(screen, gs)
        clock.tick(MAX_FPS)
        p.display.flip()
Esempio n. 13
0
def main():
    ''' Main '''
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    gs = ChessEngine.GameState()
    load_images()
    running = True
    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False
        draw_game_state(screen, gs)
        clock.tick(MAX_FPS)
        p.display.flip()
Esempio n. 14
0
def main():
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    gs = ChessEngine.GameState()
    loadImages()
    running = True
    sqSelected = ()  # no square is selected initially - one tuple:(row,col)
    playerClicks = [
    ]  # keep tracks of the player clicks - two tuples: [(6,4),(4,4)]
    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False
                p.quit()
            elif e.type == p.MOUSEBUTTONDOWN:
                location = p.mouse.get_pos(
                )  # (x, y) coordinates for the mouse
                col = location[0] // SQ_SIZE
                row = location[1] // SQ_SIZE
                #check if the user already selected this square, as it wqould be an undo
                if sqSelected == (row, col):
                    sqSelected = ()  #Unselect the square
                    playerClicks = []  #reset the clicks
                else:
                    sqSelected = (row, col)
                    playerClicks.append(
                        sqSelected
                    )  # we append both the first and second clicks
                #was this the user's second click?
                if len(playerClicks) == 2:  #after the second click
                    move = ChessEngine.Move(playerClicks[0], playerClicks[1],
                                            gs.board)
                    print(move.getChessNotation())
                    gs.makeMove(move)
                    sqSelected = ()  # reset the user clicks
                    playerClicks = []

        drawGameState(screen, gs)
        clock.tick(MAX_FPS)
        p.display.flip()
Esempio n. 15
0
def main():
    """
    The main driver for our code. This will handle user input and updating
    the graphics.
    """

    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color('white'))
    gs = ChessEngine.GameState()
    load_images()  # only do this once, before the while loop

    running = True
    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False

        draw_game_state(screen, gs)
        clock.tick(MAX_FPS)
        p.display.flip()
Esempio n. 16
0
def main():
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color('white'))
    gs = ChessEngine.GameState()
    loadImages()
    running = True
    sqSelected = ()  # no square selected, keep track of last click of the user tuples: (row, col)
    playerClicks = []  # keep track of player clicks, [(6,4), (4,4)]
    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False
            elif e.type == p.MOUSEBUTTONDOWN:
                location = p.mouse.get_pos()  # (x,y) position of mouse
                col = location[0]//SQ_SIZE
                row = location[1]//SQ_SIZE
                if sqSelected == (row, col):
                    sqSelected = ()  # deselect
                    playerClicks = []  # clear the clicks
                else:
                    sqSelected = (row, col)
                    playerClicks.append(sqSelected)

                if len(playerClicks) == 2:  # after second click move the pawn
                    move = ChessEngine.Move(
                        playerClicks[0], playerClicks[1], gs.board)
                    print(move.getChessNotation())
                    gs.makeMove(move=move)
                    sqSelected = ()
                    playerClicks = []

        drawGameState(screen, gs)
        clock.tick(MAX_FPS)
        p.display.flip()
Esempio n. 17
0
def main():
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    gs = ChessEngine.GameState()
    validMoves = gs.getValidMove()
    moveMade = False
    ChessEngine.print_text_board(gs.board)
    loadImages()
    running = True
    sqSelected = ()  # box clicked by the user (row,col)
    playerClicks = []  # all clicks by user [(row,col),(row,col)]
    gameOver = False
    p.display.set_caption(turnText(gs.whiteToMove))
    flag = 1
    choice = 1
    while running:
        if flag:
            flag = 0
            choice = OptionWindow(screen, gs)
            if choice == 0:
                break
        for event in p.event.get():
            if not gs.whiteToMove and choice == 2:
                move = aimove(gs, 3)
                gs.makeMove(move)
                moveMade = True
                p.display.set_caption(turnText(gs.whiteToMove))
                print(len(gs.moveLog))
            if event.type == p.QUIT:
                running = False
            # mouse handel
            # mouse press
            elif event.type == p.MOUSEBUTTONDOWN and (gs.whiteToMove
                                                      or choice == 1):
                if gameOver == True:
                    break
                location = p.mouse.get_pos()
                col = location[0] // SQ_SIZE
                row = location[1] // SQ_SIZE
                if sqSelected == (row, col):
                    sqSelected = ()
                    playerClicks = []
                else:
                    sqSelected = (row, col)
                    playerClicks.append(sqSelected)
                if len(playerClicks) == 2:  # two box selected move the piece
                    move = ChessEngine.Move(playerClicks[0], playerClicks[1],
                                            gs.board)
                    print(move.getChessNotation())
                    print(playerClicks)
                    for i in range(len(validMoves)):
                        if move == validMoves[i]:
                            print("moved here:", move.endRow, move.endCol)
                            if validMoves[i].isPawnPromotion:
                                print("Promote to:")
                                new_piece = input().upper()
                                validMoves[
                                    i].promotionChoice = new_piece if new_piece in (
                                        "Q", "R", "N", "B") else "Q"
                            gs.makeMove(validMoves[i])
                            moveMade = True
                            p.display.set_caption(turnText(gs.whiteToMove))
                            sqSelected = ()
                            playerClicks = []
                            break
                    if not moveMade:
                        playerClicks = [sqSelected]
            elif event.type == p.KEYDOWN:
                if event.key == p.K_z:  # z to undo move
                    print(gs.moveLog)
                    gs.undoMove()
                    if not gs.whiteToMove and choice == 2:
                        gs.undoMove()
                    moveMade = True
                    p.display.set_caption(turnText(gs.whiteToMove))

                if event.key == p.K_c:  # c to clear variables
                    sqSelected = ()
                    playerClicks = []
                if event.key == p.K_f:  # f to print valid moves
                    for i in validMoves:
                        print(i.startRow, i.startCol, i.endRow, i.endCol)
                if event.key == p.K_r:
                    gs = ChessEngine.GameState()
                    validMoves = gs.getValidMove()
                    playerClicks = []
                    sqSelected = ()
                    moveMade = False
                    p.display.set_caption(turnText(gs.whiteToMove))

        if moveMade:
            validMoves = gs.getValidMove()
            moveMade = False
            p.display.set_caption(turnText(gs.whiteToMove))

        drawGameState(screen, gs, validMoves, sqSelected)
        if gs.checkMate:
            gameOver = True
            if gs.whiteToMove:
                drawText(screen, "Black WON by checkmate")
            else:
                drawText(screen, "White WON by checkmate")
        clock.tick(MAX_FPS)
        p.display.flip()
Esempio n. 18
0
def main():
    """
    Main driver.
    Handles user input and updating the board
    """
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    gs = ChessEngine.GameState()
    valid_moves = gs.get_valid_moves()
    move_made = False  # Flag variable for when a move is made
    animate = False  # Flag variable for when to animate
    load_images()
    running = True
    square_selected = ()  # no square selected initially, keeps track of the last user click
    player_clicks = []  # keeps track of player clicks [(1,2),(2,2)]
    game_over = False
    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False
            # mouse handlers
            elif e.type == p.MOUSEBUTTONDOWN:
                if not game_over:
                    location = p.mouse.get_pos()  # (x,y) location of mouse
                    column = location[0]//SQ_SIZE
                    row = location[1]//SQ_SIZE
                    if square_selected == (row, column):  # checking if user clicks the same square twice
                        square_selected = ()  # deselects
                        player_clicks = []  # clear player clicks
                    else:
                        square_selected = (row, column)
                        player_clicks.append(square_selected)
                    if len(player_clicks) == 2:
                        move = ChessEngine.Move(player_clicks[0], player_clicks[1], gs.board)
                        for i in range(len(valid_moves)):
                            if move == valid_moves[i]:
                                gs.make_move(valid_moves[i])
                                print(move.get_chess_notation())
                                move_made = True
                                animate = True
                                # reset user clicks
                                square_selected = ()
                                player_clicks = []
                        if not move_made:
                            player_clicks = [square_selected]
            # key handlers
            elif e.type == p.KEYDOWN:
                if e.key == p.K_z:
                    gs.undo_move()
                    move_made = True
                    animate = False
                    game_over = False
                if e.key == p.K_r:
                    gs = ChessEngine.GameState()
                    valid_moves = gs.get_valid_moves()
                    square_selected = ()
                    player_clicks = []
                    move_made = False
                    animate = False
                    game_over = False
        if move_made:
            if animate:
                animate_move(gs.move_log[-1], screen, gs.board, clock)
            valid_moves = gs.get_valid_moves()
            move_made = False
            animate = False
        draw_game_state(screen, gs, valid_moves, square_selected)

        if gs.checkmate:
            game_over = True
            if gs.white_to_move:
                draw_text(screen, "Black wins by checkmate")
            else:
                draw_text(screen, "White wins by checkmate")
        elif gs.stalemate:
            game_over = True
            draw_text(screen, "Stalemate")
        clock.tick(MAX_FPS)
        p.display.flip()
Esempio n. 19
0
def main():
    """
    The main driver for our code.
    This will handle user input and updating the graphics.
    """
    p.init()
    screen = p.display.set_mode(
        (BOARD_WIDTH + MOVE_LOG_PANEL_WIDTH, BOARD_HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    game_state = ChessEngine.GameState()
    valid_moves = game_state.getValidMoves()
    move_made = False  # flag variable for when a move is made
    animate = False  # flag variable for when we should animate a move
    loadImages()  # do this only once before while loop
    running = True
    square_selected = (
    )  # no square is selected initially, this will keep track of the last click of the user (tuple(row,col))
    player_clicks = []  # this will keep track of player clicks (two tuples)
    game_over = False
    ai_thinking = False
    move_undone = False
    move_finder_process = None
    move_log_font = p.font.SysFont("Arial", 14, False, False)
    player_one = True  # if a human is playing white, then this will be True, else False
    player_two = False  # if a hyman is playing white, then this will be True, else False

    while running:
        human_turn = (game_state.white_to_move
                      and player_one) or (not game_state.white_to_move
                                          and player_two)
        for e in p.event.get():
            if e.type == p.QUIT:
                p.quit()
                sys.exit()
            # mouse handler
            elif e.type == p.MOUSEBUTTONDOWN:
                if not game_over:
                    location = p.mouse.get_pos(
                    )  # (x, y) location of the mouse
                    col = location[0] // SQUARE_SIZE
                    row = location[1] // SQUARE_SIZE
                    if square_selected == (
                            row, col
                    ) or col >= 8:  # user clicked the same square twice
                        square_selected = ()  # deselect
                        player_clicks = []  # clear clicks
                    else:
                        square_selected = (row, col)
                        player_clicks.append(
                            square_selected
                        )  # append for both 1st and 2nd click
                    if len(player_clicks
                           ) == 2 and human_turn:  # after 2nd click
                        move = ChessEngine.Move(player_clicks[0],
                                                player_clicks[1],
                                                game_state.board)
                        for i in range(len(valid_moves)):
                            if move == valid_moves[i]:
                                game_state.makeMove(valid_moves[i])
                                move_made = True
                                animate = True
                                square_selected = ()  # reset user clicks
                                player_clicks = []
                        if not move_made:
                            player_clicks = [square_selected]

            # key handler
            elif e.type == p.KEYDOWN:
                if e.key == p.K_z:  # undo when 'z' is pressed
                    game_state.undoMove()
                    move_made = True
                    animate = False
                    game_over = False
                    if ai_thinking:
                        move_finder_process.terminate()
                        ai_thinking = False
                    move_undone = True
                if e.key == p.K_r:  # reset the game when 'r' is pressed
                    game_state = ChessEngine.GameState()
                    valid_moves = game_state.getValidMoves()
                    square_selected = ()
                    player_clicks = []
                    move_made = False
                    animate = False
                    game_over = False
                    if ai_thinking:
                        move_finder_process.terminate()
                        ai_thinking = False
                    move_undone = True

        # AI move finder
        if not game_over and not human_turn and not move_undone:
            if not ai_thinking:
                ai_thinking = True
                return_queue = Queue()  # used to pass data between threads
                move_finder_process = Process(target=ChessAI.findBestMove,
                                              args=(game_state, valid_moves,
                                                    return_queue))
                move_finder_process.start()

            if not move_finder_process.is_alive():
                ai_move = return_queue.get()
                if ai_move is None:
                    ai_move = ChessAI.findRandomMove(valid_moves)
                game_state.makeMove(ai_move)
                move_made = True
                animate = True
                ai_thinking = False

        if move_made:
            if animate:
                animateMove(game_state.move_log[-1], screen, game_state.board,
                            clock)
            valid_moves = game_state.getValidMoves()
            move_made = False
            animate = False
            move_undone = False

        drawGameState(screen, game_state, valid_moves, square_selected)

        if not game_over:
            drawMoveLog(screen, game_state, move_log_font)

        if game_state.checkmate:
            game_over = True
            if game_state.white_to_move:
                drawEndGameText(screen, "Black wins by checkmate")
            else:
                drawEndGameText(screen, "White wins by checkmate")

        elif game_state.stalemate:
            game_over = True
            drawEndGameText(screen, "Stalemate")

        clock.tick(MAX_FPS)
        p.display.flip()
Esempio n. 20
0
def main():
    p.init()
    screen = p.display.set_mode((BOARD_WIDTH+MOVE_LOG_PANEL_WIDTH, BOARD_HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    currState = ChessEngine.GameState()
    validMoves = currState.get_all_valid_moves()
    moveLogFont = p.font.SysFont("Times New Roman", 15, False, False)
    moveMade = False
    animate = False
    gameOver = False
    load_images()
    running = True
    squareSelected = ()
    playerClicks = []
    humanIsWhite = True  # If a human is playing white, this flag will be true, else False
    humanIsBlack = True  # If a human is playing black, this flag will be true, else False
    while running:
        humanTurn = (currState.whiteToMove and humanIsWhite) or (not currState.whiteToMove and humanIsBlack)
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False
            # handle mouse clicks
            elif e.type == p.MOUSEBUTTONDOWN:
                if not gameOver and humanTurn:
                    location = p.mouse.get_pos()
                    col = location[0] // SQ_SIZE
                    row = location[1] // SQ_SIZE
                    if squareSelected == (row, col) or col >= 8:  # user clicked the same square or user clicked side panel => UNDO
                        squareSelected = ()
                        playerClicks = []
                    else:
                        squareSelected = (row, col)
                        playerClicks.append(squareSelected)
                        if len(playerClicks) == 2:
                            move = ChessEngine.Move(playerClicks[0], playerClicks[1], currState.board)
                            for i in range(len(validMoves)):
                                if move == validMoves[i]:
                                    moveMade = True
                                    animate = True
                                    currState.make_move(validMoves[i])
                                    # reset
                                    squareSelected = ()
                                    playerClicks = []
                            if not moveMade:
                                # set the first square as the last selected square
                                playerClicks = [squareSelected]
            # handle key presses
            elif e.type == p.KEYDOWN:
                if e.key == p.K_z:  # if 'z' is pressed, undo move
                    currState.undo_move()
                    moveMade = True
                    animate = False
                    gameOver = False
                if e.key == p.K_r:  # if 'r' is pressed, reset board
                    currState = ChessEngine.GameState()
                    validMoves = currState.get_all_valid_moves()
                    squareSelected = ()
                    playerClicks = []
                    moveMade = False
                    animate = False
                    gameOver = False

        if not gameOver and not humanTurn:
            AIMove = ChessAI.find_best_move_nega_max_alpha_beta(currState, validMoves)
            if AIMove is None:
                AIMove = ChessAI.find_random_move(validMoves)
            currState.make_move(AIMove)
            moveMade = True
            animate = True

        if moveMade:
            if animate:
                animate_move(currState.moveLog[-1], screen, currState.board, clock)
            validMoves = currState.get_all_valid_moves()
            moveMade = False

        draw_game_state(screen, currState, validMoves, squareSelected, moveLogFont)
        if currState.checkmate or currState.stalemate or currState.repetition or currState.fiftyMovesDone:
            gameOver = True
            text = "Draw by stalemate!" if currState.stalemate else "Draw by repetition!" if currState.repetition else "Draw by 50-move rule!" if currState.fiftyMovesDone\
                else "0-1 : Black wins by checkmate!" if currState.whiteToMove else "1-0 : White wins by checkmate!"
            draw_game_end_text(screen, text)
        p.display.flip()
        clock.tick(MAX_FPS)
Esempio n. 21
0
import ChessEngine

game = ChessEngine.GameState()

moves = []

game.KnightMove(4,4,4,moves)

board = [
            ["bR", "bN", "bB", "bQ", "bK", "bB", "bN", "bR"],
            ["bP", "bP", "bP", "bP", "bP", "bP", "bP", "bP"],
            ["--", "--", "--", "--", "--", "--", "--", "--"],
            ["--", "--", "--", "--", "--", "--", "--", "--"],
            ["--", "--", "--", "--", "--", "--", "--", "--"],
            ["--", "--", "--", "--", "--", "--", "--", "--"],
            ["wP", "wP", "wP", "wP", "wP", "wP", "wP", "wP"],
            ["wR", "wN", "wB", "wK", "wQ", "wB", "wN", "wR"]
        ]
board16 = [
            ["bR", "bR", "bN", "bN", "bB", "bB", "bQ", "bQ", "bK", "bQ", "bB", "bB", "bN", "bN", "bR", "bR"],
            ["bP", "bP", "bP", "bP", "bP", "bP", "bP", "bP", "bP", "bP", "bP", "bV", "bV", "bP", "bP", "bP"],
            ["--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--"],
            ["--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--"],
            ["--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--"],
            ["--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--"],
            ["--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--"],
            ["--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--"],
            ["--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--"],
            ["--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--"],
            ["--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--"],
            ["--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--", "--"],
Esempio n. 22
0
def main():
    p.init()
    screen = p.display.set_mode((width,height))
    clock = p.time.Clock()
    screen.fill(p.Color("White"))

    gs = ChessEngine.GameState()
    validMoves = gs.getValidMoves()
    moveMade = False
    loadImages()
    running = True
    
    sqSelected = ()
    playerClicks = []
    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False
                
            elif e.type == p.MOUSEBUTTONDOWN and gs.whiteToMove:
                location = p.mouse.get_pos()
                col = location[0]//sqsize
                row = location[1]//sqsize
                if sqSelected == (row,col):
                    sqSelected = ()
                    playerClicks = []
                else:
                    sqSelected = (row,col)
                    playerClicks.append(sqSelected)
                    
                if len(playerClicks) == 2:
                    move = ChessEngine.Move(playerClicks[0],playerClicks[1], gs.board)
                    for i in range(len(validMoves)):
                        if move == validMoves[i]:
                            gs.makeMove(validMoves[i])
                            moveMade = True
                            sqSelected = ()
                            playerClicks = []
                    if not moveMade:
                        playerClicks = [sqSelected]
            
                    
            elif e.type == p.KEYDOWN:
                if e.key == p.K_z:
                    gs.undoMove()
                    sqSelected = ()
                    playerClicks = []
                    moveMade = True
                    
        if moveMade:
            validMoves = gs.getValidMoves()
            moveMade = False
        drawGameState(screen, gs)
        clock.tick(maxfps)
        p.display.flip()

        if gs.checkMate and not gs.AIturn:
            print("Black wins by checkmate") if gs.whiteToMove else print("White wins by checkmate")
            running = False
        
        if gs.stalemate and not gs.AIturn:
            print("Draw by stalemate")
            running = False

        if not gs.whiteToMove and len(validMoves) != 0 and not moveMade:
            x = gs.getBestMove(2, False)
            gs.makeMove(x)
            moveMade = True
Esempio n. 23
0
def main():
    """ Main function that handles user input and graphics """

    # PyGame initialization
    pg.init()
    clock = pg.time.Clock()
    screen = pg.display.set_icon(IMAGES['logo'])  # add icon to the pg window
    screen = pg.display.set_caption(' Chess')  # add title to the pg window
    screen = pg.display.set_mode((BOARD_WIDTH + MOVE_LOG_PANEL_WIDTH,
                                  BOARD_HEIGHT))  # set size of the pg window
    screen.fill(pg.Color("black"))  # add background color to the pg window

    move_log_font = pg.font.SysFont("Arial", 13, True, False)

    # GameEngine initialization
    game_state = ChessEngine.GameState()
    running = True
    sq_selected = ()  # store last click of the user
    player_click = []  # store clicks up to two clicks
    move_finder_process = None  # allow multi processing

    valid_moves = game_state.get_all_valid_moves()
    move_made = False  # flag variable for when a move is made
    animate = False  # flag variable for when a move needs to be animated
    game_over = False  # flag variable for when game is over
    ai_thinking = False  # flag variable for when the AI is finding best move
    move_undone = False  # flag variable for when the move is undone

    # if a human is playing white, then this will be True, else False
    player_one = False

    # if a human is playing black, then this will be True, else False
    player_two = False

    # infinite loop
    while running:

        human_turn = (game_state.white_to_move and player_one) or (
            not game_state.white_to_move and player_two
        )  # check if the human is controlling the turn

        for e in pg.event.get():  # for each event in event queue

            if e.type == pg.QUIT:  # trigger for ending infinite loop
                pg.quit()
                sys.exit()

            elif not game_over and e.type == pg.MOUSEBUTTONDOWN:
                if not game_over and human_turn:
                    location = pg.mouse.get_pos(
                    )  # (x, y) location fot the mouse
                    col = location[0] // SQ_SIZE
                    row = location[1] // SQ_SIZE

                    # storing player clicks
                    if sq_selected == (
                            row, col
                    ) or col >= 8:  # in case the click is same as previous click, reset player clicks
                        sq_selected = ()
                        player_click.clear()

                    else:  # else update the new click position
                        sq_selected = (row, col)
                        player_click.append(sq_selected)

                    if len(player_click
                           ) == 2:  # when 2 unique clicks have been identified
                        move = ChessEngine.Move(player_click[0],
                                                player_click[1],
                                                game_state.board)

                        for i in range(len(valid_moves)):
                            if move == valid_moves[i]:
                                game_state.make_move(valid_moves[i])

                                move_made = True
                                animate = True

                                # reset input
                                sq_selected = ()
                                player_click.clear()
                                break

                        else:
                            player_click = [sq_selected]

            elif e.type == pg.KEYDOWN and e.key == pg.K_z:  # trigger for undoing a move
                game_state.undo_move()
                move_made = True
                animate = False
                game_over = False

                if ai_thinking:
                    move_finder_process.terminate()
                    ai_thinking = False

                move_undone = True

            elif e.type == pg.KEYDOWN and e.key == pg.K_r:  # trigger for resetting the board
                game_state = ChessEngine.GameState()
                valid_moves = game_state.get_all_valid_moves()
                sq_selected = ()
                player_click.clear()
                move_made = False
                animate = False
                game_over = False

                if ai_thinking:
                    move_finder_process.terminate()
                    ai_thinking = False

                move_undone = True

        # AI move finder
        if not game_over and not human_turn and not move_undone:

            if not ai_thinking:
                ai_thinking = True
                return_queue = Queue()  # store and pass data between threads
                move_finder_process = Process(target=ChessAI.find_best_move,
                                              args=(game_state, valid_moves,
                                                    return_queue))
                move_finder_process.start()

            if not move_finder_process.is_alive():
                ai_move = return_queue.get()

                if ai_move is None:
                    ai_move = ChessAI.findRandomMove(valid_moves)

                game_state.make_move(ai_move)
                move_made = True
                animate = True
                ai_thinking = False

        if move_made:
            if animate:
                animate_move(game_state.move_log[-1], screen, game_state.board,
                             clock)  # animate the move made by the user
            valid_moves = game_state.get_all_valid_moves()
            move_made = False
            animate = False
            move_undone = False

        if not game_over:
            draw_GameState(screen, game_state, valid_moves, sq_selected,
                           move_log_font)

        if game_state.check_mate or game_state.stale_mate:
            game_over = True
            win_txt = 'Stalemate' if game_state.stale_mate else 'Black wins by checkmate.' if game_state.white_to_move else 'White  wins by checkmate.'
            draw_end_game_text(screen, win_txt)

        clock.tick(MAX_FPS)
        pg.display.flip()
Esempio n. 24
0
def main():
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    p.display.set_caption('Chess')

    # Game state
    gs = ChessEngine.GameState()
    minmaxPruning = ChessEngine.MinMaxPruning()

    validMoves = gs.getValidMoves()
    moveMade = False
    loadImages()

    # loadImage()
    running = True
    sqSelected = ()  # tuple (row, col)
    playerClicks = []
    while running:
        if gs.whiteToMove:
            for e in p.event.get():
                if e.type == p.QUIT:
                    running = False
                # mouse handler
                elif e.type == p.MOUSEBUTTONDOWN:
                    location = p.mouse.get_pos()  # (x, y) location of mouse
                    col = location[0] // SQ_SIZE
                    row = location[1] // SQ_SIZE
                    if sqSelected == (row,
                                      col):  # player clicked the same square
                        sqSelected = ()  # deselect
                        playerClicks = []  # clear player click
                    else:
                        sqSelected = (row, col)
                        playerClicks.append(
                            sqSelected)  # apend fot 1st and 2nd click
                    if len(playerClicks) == 2:  # after player's 2nd click
                        move = ChessEngine.Move(playerClicks[0],
                                                playerClicks[1], gs.board)
                        print(move.getChessNotation())
                        if move in validMoves:
                            gs.makeMove(move)
                            moveMade = True
                            sqSelected = ()  # reset player clicks
                            playerClicks = []
                        else:
                            playerClicks = [sqSelected]
                # key handler
                elif e.type == p.KEYDOWN:
                    if e.key == p.K_z:
                        gs.undoMove()
                        moveMade = True
            if moveMade:
                validMoves = gs.getValidMoves()
                moveMade = False
        else:
            # print(minmaxPruning.minmaxRoot(2, gs))
            bestMove = minmaxPruning.minmaxRoot(3, gs)
            gs.makeMove(bestMove)
            print("best move: ", bestMove.getChessNotation())
            moveMade = True
            sqSelected = ()  # reset player clicks
            playerClicks = []
            print("luot cua trang: ", gs.whiteToMove)

        # drawGameState(screen, gs)
        drawGameState(screen, gs, validMoves, sqSelected)

        clock.tick(MAX_FPS)
        p.display.flip()
Esempio n. 25
0
def main():
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("pink"))

    #GameState object will keep track of the game and determine valid moves
    gs = ChessEngine.GameState()

    #Generate valid moves for pieces. Expensive operation!! Only call when necessary!!
    validMoves = gs.getValidMoves()
    promotionMoves = gs.getPawnPromotionMoves()
    moveMade = False
    highlight = [0, 0, 0, validMoves]

    #Just loading the images once instead of loading after each move

    loadImages()

    #Keeping track of the last square that the user has clicked (initially none)
    sqSelected = ()

    #Keeping track of up to two of the squares last clicked (two tuples)
    playerClicks = []
    running = True
    while running:

        if gs.checkMate:
            color = "black" if gs.whiteToMove else "white"
            drawText(screen, "CHECKMATE", color)
        elif gs.staleMate:
            drawText(screen, "STALEMATE", "red")

        #If we press X on the window stop this while -loop
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False

            #key handlers
            elif e.type == p.KEYDOWN:

                #If key 'z' is pressed, undo previous move and make sure valid moves are checked again
                if e.key == p.K_z:
                    gs.undoMove()
                    moveMade = True
                elif e.key == p.K_r:
                    gs = ChessEngine.GameState()
                    validMoves = gs.getValidMoves()
                    promotionMoves = gs.getPawnPromotionMoves()
                    highlight = [0, 0, 0, validMoves]
                    playerClicks = []
                    sqSelected = ()

            #mouse handler
            elif e.type == p.MOUSEBUTTONDOWN:

                #Use the location of the mouse to determine which of squares has been clicked
                location = p.mouse.get_pos()
                col = location[0] // SQ_SIZE
                row = location[1] // SQ_SIZE

                #If the user clicked the same square twice, don't make a move. Clear sqSelected and playerClicks
                if sqSelected == (row, col):
                    sqSelected = ()
                    playerClicks = []
                    highlight = [0, 0, 0, validMoves]
                elif len(playerClicks) == 0 and gs.board[row][col] == "--":
                    print("SELECT A PIECE INSTEAD")
                #If not, keep track of this click
                else:
                    sqSelected = (row, col)
                    playerClicks.append(sqSelected)
                    #If this was the players 1st click highlight square
                    if len(playerClicks) == 1:
                        highlight = [row, col, 1, validMoves]
                    #If this was the players 2nd click and the move will be valid, move the piece and cancel highlight
                    if len(playerClicks) == 2:
                        highlight = [0, 0, 0, validMoves]
                        move = ChessEngine.Move(playerClicks[0],
                                                playerClicks[1], gs.board)
                        for i in range(len(validMoves)):
                            if move == validMoves[i]:
                                print(move.getChessNotation())
                                if move in promotionMoves:
                                    gs.makeMove(validMoves[i])
                                    pieceColor = gs.board[playerClicks[1][0]][
                                        playerClicks[1][1]][0]
                                    piece = choosePromotionPiece(
                                        screen, pieceColor)
                                    gs.makePawnPromotion(
                                        playerClicks[1][0], playerClicks[1][1],
                                        piece)
                                else:
                                    gs.makeMove(validMoves[i])
                                moveMade = True
                            sqSelected = ()
                            playerClicks = []

        #If a move has been made since the last time valid moves were checked, check them again
        if moveMade:
            validMoves = gs.getValidMoves()
            promotionMoves = gs.getPawnPromotionMoves()
            moveMade = False

        #To run slower wait the amount of millisecond in MAX_FPS
        clock.tick(MAX_FPS)

        #Update the contents of the display
        p.display.flip()

        drawGameState(screen, gs, highlight)
Esempio n. 26
0
def game():
    global drag_move, vs_ai, vs_ml
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    gs = ChessEngine.GameState()
    valid_moves = gs.getValidMoves()
    move_made = False  # flag variable for when a move is made
    undo_made = False

    playing = True
    sq_selected = (
    )  # initially no square is selected, keeps track of last selected click (6, 4)
    player_clicks = []  # keeps track of the players clicks [(6, 4) , (4, 4)]
    game_over = False

    drag = False
    selected = None
    piece_selected_rect = []
    for piece in pieces:
        piece_selected_rect.append(IMAGES[piece].get_rect())

    draw_gamestate(
        screen, gs, valid_moves, sq_selected, player_clicks, move_made,
        undo_made, drag, mouse_pos
    )  # initial draw of gamestate as it only updates on player clicks

    while playing:
        for e in p.event.get():
            if e.type == p.QUIT:
                playing = False

            # Mouse Presses
            # elif drag_move:
            if e.type == p.MOUSEBUTTONDOWN:
                if e.button == 1:
                    col, row = e.pos[0] // SQ_SIZE, e.pos[1] // SQ_SIZE
                    sq_selected = (row, col)
                    piece_selected = gs.board[row][col]
                    if gs.whiteToMove and piece_selected[
                            0] == 'w' or not gs.whiteToMove and piece_selected[
                                0] == 'b':
                        if piece_selected != '--':
                            piece_rect = IMAGES[piece_selected].get_rect()
                            gs.board[row][
                                col] = "--"  # removes piece from current pos
                            draw_gamestate(screen, gs, valid_moves,
                                           sq_selected, player_clicks,
                                           move_made, undo_made, drag,
                                           mouse_pos)
                            drag = True  # time to drag
                            offset_x = piece_rect.x - e.pos[
                                0]  # offset between mouse and center of item
                            offset_y = piece_rect.y - e.pos[1]
                            piece_rect.x = col * SQ_SIZE + e.pos[0] + offset_x
                            piece_rect.y = row * SQ_SIZE + e.pos[1] + offset_y
                            screen.blit(IMAGES[piece_selected], piece_rect)

            elif e.type == p.MOUSEBUTTONUP:
                if e.button == 1:
                    drag = False
                    sq_released = (int(e.pos[1] / SQ_SIZE),
                                   int(e.pos[0] / SQ_SIZE))
                    if sq_released == sq_selected:
                        gs.board[sq_selected[0]][
                            sq_selected[1]] = piece_selected
                        sq_selected = ()
                        player_clicks = []
                        draw_gamestate(screen, gs, valid_moves, sq_selected,
                                       player_clicks, move_made, undo_made,
                                       drag, mouse_pos)
                    else:
                        player_clicks = [sq_selected, sq_released]
                        draw_gamestate(screen, gs, valid_moves, sq_selected,
                                       player_clicks, move_made, undo_made,
                                       drag, mouse_pos)
                    if len(player_clicks) == 2:
                        move = ChessEngine.Move(player_clicks[0],
                                                player_clicks[1], gs.board)
                        poly_move = str(
                            chess.Move.from_uci(
                                ChessEngine.Move.getChessNotation(move)))
                        for i in range(len(valid_moves)):
                            if move == valid_moves[i]:
                                gs.board[player_clicks[0][0]][
                                    player_clicks[0][1]] = piece_selected
                                gs.makeMove(valid_moves[i])
                                ChessAI.polyboard.push(
                                    chess.Move.from_uci(poly_move))
                                move_made = True
                                ChessAI.Calculations.best_move = 0
                                ChessAI.Calculations.opening_move = 0
                                draw_gamestate(screen, gs, valid_moves,
                                               sq_selected, player_clicks,
                                               move_made, undo_made, drag,
                                               mouse_pos)

                        if not move_made:
                            gs.board[sq_selected[0]][
                                sq_selected[1]] = piece_selected
                            sq_selected = ()
                            player_clicks = []
                            draw_gamestate(screen, gs, valid_moves,
                                           sq_selected, player_clicks,
                                           move_made, undo_made, drag,
                                           mouse_pos)

            elif e.type == p.MOUSEMOTION:
                if drag:  # if item is clicked on
                    piece_rect.x = col * SQ_SIZE + e.pos[
                        0] + offset_x  # update the pos of the item to mouse pos
                    piece_rect.y = row * SQ_SIZE + e.pos[1] + offset_y
                    draw_gamestate(screen,
                                   gs,
                                   valid_moves,
                                   sq_selected,
                                   player_clicks,
                                   move_made,
                                   undo_made,
                                   drag,
                                   mouse_pos=(e.pos[0], e.pos[1]))
                    screen.blit(IMAGES[piece_selected], piece_rect)

            elif e.type == p.KEYDOWN:
                if e.key == p.K_ESCAPE:
                    main()

        if move_made:
            if not vs_ml and not vs_ai:
                valid_moves = gs.getValidMoves()
                sq_selected = ()
                draw_gamestate(screen, gs, valid_moves, sq_selected,
                               player_clicks, undo_made, move_made, drag,
                               mouse_pos)
                draw_gamestate(screen, gs, valid_moves, sq_selected,
                               player_clicks, move_made, undo_made, drag,
                               mouse_pos)
                player_clicks = []
                move_made = False

            if vs_ml or vs_ai:
                move_made = False

                if vs_ml:
                    ml_thread = threading.Thread(target=ChessAI.AI.get_ai_move)
                    ml_thread.daemon = True
                    ml_thread.start()
                    while ml_thread.is_alive:
                        if ChessAI.Calculations.best_move != 0:
                            ml_thread.is_alive = False
                        else:
                            p.display.update()
                        time.sleep(1)
                    best_move, poly_move = ChessAI.Calculations.best_move, ChessAI.Calculations.opening_move

                elif vs_ai:
                    ai_thread = threading.Thread(target=ChessAI.AI.get_ai_move)
                    ai_thread.daemon = True
                    ai_thread.start()
                    while ai_thread.is_alive:
                        if ChessAI.Calculations.best_move != 0:
                            ai_thread.is_alive = False
                        else:
                            p.display.update()
                        time.sleep(1)
                    best_move, poly_move = ChessAI.Calculations.best_move, ChessAI.Calculations.opening_move

                if best_move == poly_move == "N":
                    if gs.inCheck():
                        gs.checkmate = True
                        break
                    else:
                        gs.stalemate = True
                        break

                gs.makeMove(best_move)
                ChessAI.polyboard.push(poly_move)
                valid_moves = gs.getValidMoves()
                draw_gamestate(screen, gs, valid_moves, sq_selected,
                               player_clicks, move_made, undo_made, drag,
                               mouse_pos)
                draw_gamestate(screen, gs, valid_moves, sq_selected,
                               player_clicks, move_made, undo_made, drag,
                               mouse_pos)

        if gs.checkmate:
            game_over = True
            if gs.whiteToMove:
                draw_text(screen,
                          text_location='center',
                          text='Black wins by Checkmate')
            else:
                draw_text(screen,
                          text_location='center',
                          text='White wins by Checkmate')
        elif gs.stalemate:
            game_over = True
            draw_text(screen, text_location='center', text='Stalemate')

        clock.tick(MAX_FPS)
        p.display.flip()
Esempio n. 27
0
    def __init__(self):
        self.gs = ChessEngine.GameState()
        self.WhitetoMove = self.gs.WhiteToMove
        self.allMoves = self.gs.getValidMoves()
        self.gameOver = False
        self.whiteWin = False
        self.blackWIn = False
        self.previousCastleMove = False
        self.whiteToTurnRight = True
        self.castleRule = ChessMain.castleRule
        self.castlingCopy = ()
        self.board = np.array([
            ["bR", "bN", "bB", "bQ", "bK", "bB", "bN", "bR"],
            ["bp", "bp", "bp", "bp", "bp", "bp", "bp", "bp"],
            ["--", "--", "--", "--", "--", "--", "--", "--"],
            ["--", "--", "--", "--", "--", "--", "--", "--"],
            ["--", "--", "--", "--", "--", "--", "--", "--"],
            ["--", "--", "--", "--", "--", "--", "--", "--"],
            ["wp", "wp", "wp", "wp", "wp", "wp", "wp", "wp"],
            ["wR", "wN", "wB", "wQ", "wK", "wB", "wN", "wR"]])

        self.whitePawnPositionValue = [
            [1, 1, 1, 1, 1, 1, 1, 1],
            [1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5],
            [1.1, 1.1, 1.2, 1.3, 1.3, 1.2, 1.1, 1.],
            [1.05, 1.05, 1.1, 1.25, 1.25, 1.1, 1.05, 1.05],
            [1, 1, 1, 1.5, 1.5, 1, 1, 1],
            [1.05, 0.95, 0.9, 1.05, 1.05, 0.9, 0.95, 1.05],
            [1.05, 1.1, 1.1, 0.8, 0.8, 1.1, 1.1, 1.05],
            [1, 1, 1, 1, 1, 1, 1, 1]]

        self.blackPawnPositionValue = [
            [1, 1, 1, 1, 1, 1, 1, 1],
            [1.05, 1.1, 1.1, 0.8, 0.8, 1.1, 1.1, 1.05],
            [1.05, 0.95, 0.9, 1.05, 1.05, 0.9, 0.95, 1.05],
            [1, 1, 1, 1.5, 1.5, 1, 1, 1],
            [1.05, 1.05, 1.1, 1.25, 1.25, 1.1, 1.05, 1.05],
            [1.1, 1.1, 1.2, 1.3, 1.3, 1.2, 1.1, 1.],
            [1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5, 1.5],
            [1, 1, 1, 1, 1, 1, 1, 1]]

        self.KnightPositionValue = [
            [0.5, 0.6, 0.7, 0.7, 0.7, 0.7, 0.6, 0.50],
            [0.6, 0.8, 1, 1, 1, 1, 0.8, 0.6],
            [0.7, 1, 1.1, 1.15, 1.15, 1.1, 1, 0.7],
            [0.7, 1.05, 1.15, 1.2, 1.2, 1.15, 1.05, 0.7],
            [0.7, 1.05, 1.15, 1.2, 1.2, 1.15, 1.05, 0.7],
            [0.7, 1, 1.1, 1.15, 1.15, 1.1, 1, 0.7],
            [0.6, 0.8, 1, 1, 1, 1, 0.8, 0.6],
            [-50, -40, -30, -30, -30, -30, -40, -50]]

        self.BishopPositionValue = [
            [0.8, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.8],
            [0.9, 1, 1, 1, 1, 1, 1, 0.9],
            [0.9, 1, 1.05, 1.1, 1.1, 1.05, 1, 0.9],
            [0.9, 1.05, 1.05, 1.1, 1.1, 1.05, 1.05, 0.9],
            [0.9, 1.05, 1.05, 1.1, 1.1, 1.05, 1.05, 0.9],
            [0.9, 1, 1.05, 1.1, 1.1, 1.05, 1, 0.9],
            [0.9, 1, 1, 1, 1, 1, 1, 0.9],
            [0.8, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.8]]

        self.RookPositionValue = [
            [1, 1, 1, 1, 1, 1, 1, 1],
            [1.05, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.05],
            [0.95, 1, 1, 1, 1, 1, 1, 0.95],
            [0.95, 1, 1, 1, 1, 1, 1, 0.95],
            [0.95, 1, 1, 1, 1, 1, 1, 0.95],
            [0.95, 1, 1, 1, 1, 1, 1, 0.95],
            [1.05, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.05],
            [1, 1, 1, 5, 5, 1, 1, 1]]

        self.QueenPositionValue = [
            [0.8, 0.9, 0.9, 0.95, 0.95, 0.90, 0.9, 0.8],
            [0.9, 1, 1, 1, 1, 1, 1, 0.9],
            [0.9, 1, 1.5, 1.5, 1.5, 1.5, 1, 0.9],
            [0.95, 1, 1.5, 1.5, 1.5, 1.5, 1, 0.95],
            [0.95, 1, 1.5, 1.5, 1.5, 1.5, 1, 0.95],
            [0.9, 1, 1.5, 1.5, 1.5, 1.5, 1, 0.9],
            [0.9, 1, 1, 1, 1, 1, 1, 0.9],
            [0.8, 0.9, 0.9, 0.95, 0.95, 0.90, 0.9, 0.8]]

        self.KingPositionValue = [
            [1.2, 1.1, 1.1, 1.05, 1.05, 1.1, 1.2, 1.2],
            [1, 1, 1, 1, 1, 1, 1, 1],
            [1, 1, 1, 1, 1, 1, 1, 1],
            [1, 1, 1, 1, 1, 1, 1, 1],
            [1, 1, 1, 1, 1, 1, 1, 1],
            [1, 1, 1, 1, 1, 1, 1, 1],
            [1, 1, 1, 1, 1, 1, 1, 1],
            [1.2, 1.1, 1.1, 1.05, 1.05, 1.1, 1.2, 1.2]]
Esempio n. 28
0
def chess_game(game_kind, board_type, countdown_len):
    countdown_start = countdown_len * 60 * 60
    screen = p.display.set_mode((WIDTH + 200, HEIGHT))
    clock = p.time.Clock()  #built in pygame
    screen.fill(p.Color("grey"))
    gs = ChessEngine.GameState(
    )  #now all the fields within the ChessEngine.py file can be called using gs.
    board = gs.board
    validMoves = gs.getValidMoves()  #get initial valid moves
    moveMade = False  #flag varable for when a move is made. Until a move is made, we don't want to regenerate the valid
    #moves function
    whiteToMove = 1  #keep track of whose turn it is
    loadImages(board_type)  #only do this once, before the while loop
    running = True
    sqSelected = (
    )  #no square is selected, keep track of the last click of the user (tuple: (row,col))
    playerClicks = [
    ]  #keep track of player clicks (two tuples: [(6,4), (4,4)]) first clicks on (6,4) and
    #later on (4,4) to move the pawn
    gameOver = False

    time_black = countdown_start
    time_white = countdown_start
    start_ticks = p.time.get_ticks()
    stop_clocks = False
    while running:

        milliseconds_past = (
            p.time.get_ticks() - start_ticks
        ) / 15  #define time relative to each loop and divide by 15
        if not stop_clocks:
            if whiteToMove % 2 == 0:  #alternate clock depending on who'e turn it is
                time_black = time_black - milliseconds_past
            else:
                time_white = time_white - milliseconds_past

        timer_visualize(screen, time_black, time_white)  #load clock screen
        start_ticks = p.time.get_ticks()  #ensure time does not accelerate
        # if time_white/(60*60) <=0: #end game if time runs out
        #     gameOver = True
        #     stop_clocks = True
        #
        # elif time_black/(60*60) <= 0:
        #     gameOver = True
        #     stop_clocks = True

        for e in p.event.get():
            if e.type == p.QUIT:
                running = False
            ## The below takes care of AI moves from the black side.
            elif whiteToMove % 2 == 0 and game_kind == "Human vs. NPC Chess":  #When it's blacks turn
                if not gameOver:
                    bestMove = gs.minimax(
                        3, -999999999, 999999999, False
                    )  #call the minimax function which returns the best move
                    gs.makeMove(bestMove[1])  #do best move
                    moveMade = True  #set to True so we can get the valid moves for white next
                else:  #in case we make a check mate to black and we want to go back, we need to include this piece of code
                    if e.type == p.KEYDOWN:
                        if e.key == p.K_z:  # undo when "z" is pressed
                            gs.undoMove()
                            moveMade = True

                            if gameOver:
                                gameOver = False
                            break

                        if e.key == p.K_r:  # reset the board
                            gs = ChessEngine.GameState()
                            validMoves = gs.getValidMoves()
                            sqSelected = ()
                            playerClicks = []
                            whiteToMove = 1
                            moveMade = False
                            if gameOver:
                                gameOver = False
                break
            #mouse handler
            elif e.type == p.MOUSEBUTTONDOWN:
                if not gameOver and p.mouse.get_pos()[0] < WIDTH:
                    bestMove = gs.minimax(
                        1, -999999999, 999999999, True
                    )  # call the minimax function which returns the best move

                    location = p.mouse.get_pos()  #(x,y) location of the mouse
                    col = location[0] // SQ_SIZE
                    row = location[1] // SQ_SIZE

                    if sqSelected == (
                            row, col
                    ):  #this means the user clicked the same square twice
                        sqSelected = ()  #deselect
                        playerClicks = []  #clear player clicks
                    else:
                        sqSelected = (row, col)
                        playerClicks.append(
                            sqSelected)  #append for both 1st and 2nd clicks
                    if len(
                            playerClicks
                    ) == 2:  #after the second click, we want to make the move
                        move = ChessEngine.Move(playerClicks[0],
                                                playerClicks[1], gs.board)
                        ## See that creating the move is pretty inexpensive, we are just creating 4 variables and accessing
                        ## two elements of an array
                        print(move.getChessNotation())
                        for i in range(len(validMoves)):
                            if move == validMoves[i]:
                                gs.makeMove(validMoves[i])
                                # whiteToMove = whiteToMove + 1
                                animateMove(gs.moveLog[-1], screen, gs.board,
                                            clock, board_type)
                                moveMade = True  #a move was made, so now go ahead and regenerate the list of valid moves
                                sqSelected = ()  #reset user clicks
                                playerClicks = []
                        if not moveMade:  #this allows to select a new piece and dislect the previous one
                            playerClicks = [sqSelected]
            #key handler
            elif e.type == p.KEYDOWN:
                if e.key == p.K_z:  #undo when "z" is pressed
                    gs.undoMove()

                    moveMade = True

                    if gameOver:
                        gameOver = False
                    break

                if e.key == p.K_r:  #reset the board
                    gs = ChessEngine.GameState()
                    validMoves = gs.getValidMoves()
                    sqSelected = ()
                    playerClicks = []
                    moveMade = False
                    if gameOver:
                        gameOver = False
                    stop_clocks = False  #restart the clocks
                    time_black = countdown_start
                    time_white = countdown_start
                    start_ticks = p.time.get_ticks()
                    whiteToMove = 1  #reset white's turn

        if moveMade:
            validMoves = gs.getValidMoves()
            moveMade = False
            whiteToMove = whiteToMove + 1  #counter for AI

        drawGameState(screen, gs, validMoves, sqSelected, board_type)

        if gs.checkMate:
            gameOver = True
            drawText(screen, "Checkmate")
            stop_clocks = True

        elif gs.staleMate:
            gameOver = True
            drawText(screen, "Stalemate")
            stop_clocks = True

        elif gameOver:
            drawText(screen, "Time out")

        clock.tick(MAX_FPS)
        p.display.flip()
Esempio n. 29
0
def main():
    p.init()
    screen = p.display.set_mode((BOARD_WIDTH+MOVE_LOG_PANEL_WIDTH, BOARD_HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    moveLogFont = p.font.SysFont("Arial", 12, False, False)
    gs = ChessEngine.GameState()
    validMoves = gs.getValidMoves()
    moveMade = False #flag variable for when a move is made
    animate = False #flag for when to animate
    
    #print(gs.board)
    loadImages() #only do once, before while loop
    running = True
    sqSelected = () #no square selected initially, keep track of last click of user (tuple: (row,col))
    prevSqSelected = ()
    secondPrevSqSelected = ()
    playerClicks = [] #keeps track of player clicks (two tuples: [(6,4),(4,4)])
    gameOver = False
    playerOne = -1 #if human is playing white,then this will be true. If AI is playing, then false
                     #can also make this an integer value, 0 being human 1-10 being difficulty of AI
    playerTwo = -1 #Same as above but for black
    while running:
        humanTurn = (gs.whiteToMove and playerOne == -1) or (not gs.whiteToMove and playerTwo == -1)
        
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False
            #handles mouse
            elif e.type == p.MOUSEBUTTONDOWN:
                if not gameOver and humanTurn:
                    location = p.mouse.get_pos() #(x,y) location of mouse
                    col = location[0]//SQ_SIZE #to get col, integer divide x coord on board w size of each square 
                    row = location[1]//SQ_SIZE #to get row, integer divide y coord on board w size of each square 
                    if sqSelected == (row,col) or col >= 8: #user clicked same square twice, so unselect or user clicked mouse log
                        sqSelected = () #deselect
                        playerClicks = [] #clear player clicks
                    else:
                        sqSelected = (row,col)
                        playerClicks.append(sqSelected) #append for both 1st and 2nd clicks
                    if len(playerClicks) == 2: #after 2nd click
                        move = ChessEngine.Move(playerClicks[0], playerClicks[1], gs.board)
                        for i in range(len(validMoves)):
                            if move == validMoves[i]:
                                gs.makeMove(validMoves[i])
                                print(str(gs.moveLog[-1]))
                                moveMade = True
                                animate = True
                                prevSqSelected = playerClicks[-1]
                                secondPrevSqSelected = playerClicks[-2]
                                sqSelected = () #reset uer clicks
                                playerClicks = []
                        if not moveMade:
                            playerClicks = [sqSelected]
                            
            #handles keys
            elif e.type == p.KEYDOWN:
                if e.key == p.K_z: #undo when 'z' is pressed
                    gs.undoMove()
                    moveMade = True
                    animate = False
                    gameOver = False
                if e.key == p.K_r: #reset when 'r' is pressed
                    gs = ChessEngine.GameState()
                    validMoves = gs.getValidMoves()
                    sqSelected = ()
                    prevSqSelected = ()
                    secondPrevSqSelected = ()
                    moveMade = False
                    gameOver = False
                    animate = False
                    
        #Chess AI
        if not gameOver and not humanTurn:
            if gs.whiteToMove:
                AIMove = chessAI.findBestMove(gs, validMoves, playerOne)
            else:
                AIMove = chessAI.findBestMove(gs, validMoves, playerTwo)
            if AIMove is None:
                if(len(validMoves) != 0):
                    AIMove = chessAI.findRandomMove(validMoves)
                else:
                    break
            gs.makeMove(AIMove)
            print(str(gs.moveLog[-1]))
            moveMade = True
            animate = True
        
        if moveMade:
            if animate:
                animateMove(gs.moveLog[-1], screen, gs.board, clock)
            validMoves = gs.getValidMoves()
            moveMade = False
                
        #print(prevSqSelected)
        drawGameState(screen,gs, validMoves, sqSelected, prevSqSelected, secondPrevSqSelected, moveLogFont)
        
        if gs.checkMate or gs.staleMate:
            gameOver = True
            text = 'Draw by stalemate' if gs.staleMate else ('Black wins by checkmate' if gs.whiteToMove else 'White wins by checkmate')
            drawEndGameText(screen, text)
        clock.tick(MAX_FPS)
        p.display.flip()
Esempio n. 30
0
def main():
    p.init()
    p.display.set_caption('Pysah')
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    gs = ChessEngine.GameState()
    validMoves = gs.getValidMoves()
    moveMade = False
    animate = False

    loadImages()
    running = True
    sqSelected = ()
    playerClicks = []
    gameOver = False

    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False
            elif e.type == p.MOUSEBUTTONDOWN:
                if not gameOver:
                    location = p.mouse.get_pos()
                    col = location[0] // SQ_SIZE
                    row = location[1] // SQ_SIZE
                    if sqSelected == (row, col):
                        sqSelected = ()
                        playerClicks = []
                    else:
                        sqSelected = (row, col)
                        playerClicks.append(sqSelected)
                    if len(playerClicks) == 2:
                        move = ChessEngine.Move(playerClicks[0],
                                                playerClicks[1], gs.board)
                        print(move.getChessNotation())
                        for i in range(len(validMoves)):
                            if move == validMoves[i]:
                                gs.makeMove(validMoves[i])
                                if move.isPawnPromotion:
                                    gs.whiteToMove = not gs.whiteToMove
                                    pieceType = getChoice(screen, gs)
                                    gs.board[move.endRow][
                                        move.endCol] = move.pieceMoved[
                                            0] + pieceType
                                    gs.whiteToMove = not gs.whiteToMove
                                moveMade = True
                                animate = True
                                sqSelected = ()
                                playerClicks = []
                        if not moveMade:
                            playerClicks = [sqSelected]
            elif e.type == p.KEYDOWN:
                if e.key == p.K_z:
                    gs.undoMove()
                    moveMade = True
                    animate = False
                if e.key == p.K_r:
                    gs = ChessEngine.GameState()
                    validMoves = gs.getValidMoves()
                    sqSelected = ()
                    playerClicks = []
                    moveMade = False
                    animate = False

        if moveMade:
            if animate:
                animatedMove(gs.movelog[-1], screen, gs.board, clock)
            validMoves = gs.getValidMoves()
            moveMade = False
            animate = False

        drawGameState(screen, gs, validMoves, sqSelected)

        if gs.checkMate:
            gameOver = True
            if gs.whiteToMove:
                drawText(screen, 'Black wins by checkmate')
            else:
                drawText(screen, 'White wins by checkmate')
        elif gs.staleMate:
            gameOver = True
            drawText(screen, 'Stalemate')

        clock.tick(MAX_FPS)
        p.display.flip()