Example #1
0
def main():  
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    screen.fill(BLACK) 
    gs = chessEngine.GameState()

    # to avoid generating every valid moves in every loop
    valid_moves = gs.get_valid_moves()
    move_made = False #flag variable for when a move is made

    load_images()
    running = True
    number_of_moves = 0
    squere_selected = () #keep track of last click 
    playerClicks = [] # keep track of player clicks eg. [(6, 4), (4, 4)]
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            # mouse handlers
            elif event.type == pygame.MOUSEBUTTONDOWN:
                location = pygame.mouse.get_pos() # (x, y) location of mouse
                col = location[0]//SQUERE_SIZE # location[0] = x
                row =  location[1]//SQUERE_SIZE 
                if squere_selected == (row, col): # if user select same squere twice
                    squere_selected = () # unselect
                    playerClicks = []
                else:
                    squere_selected = (row, col)
                    playerClicks.append(squere_selected)

                if len(playerClicks) == 2: # after 2nd click
                    move = chessEngine.Move(playerClicks[0], playerClicks[1], gs.board)
                    print(playerClicks)
                    for i in range(len(valid_moves)):
                        if move == valid_moves[i]:
                            gs.make_move(valid_moves[i])
                            number_of_moves += 1
                            move_made = True
                            squere_selected = ()
                            playerClicks = []
                    if not move_made:
                        playerClicks = [squere_selected]
                        
            # undo handler
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_z: # undo if 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, valid_moves, squere_selected)
        pygame.display.flip()
Example #2
0
def start_the_game(playerOneVALUE, playerTwoVALUE):
    clock = pg.time.Clock()
    surface.fill(pg.Color("white"))
    gs = cE.GameState()
    loadImages()
    running = True
    sqSelected = ()
    playerClicks = []
    validMoves = gs.getValidMoves()
    moveMade = False
    animate = False
    gameOver = False
    playerOne = playerOneVALUE
    playerTwo = playerTwoVALUE
    AIThinking = False
    moveFinderProcess = None
    moveUndone = False

    while running:
        humanTurn = (gs.whiteToMove and playerOne) or (not gs.whiteToMove
                                                       and playerTwo)

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

            elif e.type == pg.MOUSEBUTTONDOWN:
                if not gameOver and humanTurn:
                    location = pg.mouse.get_pos()
                    col = location[0] // SQ_SIZE
                    row = location[1] // SQ_SIZE
                    if sqSelected == (row, col):
                        sqSelected = ()
                        playerClicks = []
                        moveMade = False
                    else:
                        sqSelected = (row, col)
                        playerClicks.append(sqSelected)
                    if len(playerClicks) == 2:
                        move = cE.Move(playerClicks[0], playerClicks[1],
                                       gs.board)
                        for i in range(len(validMoves)):
                            if move == validMoves[i]:
                                gs.makeMove(validMoves[i])
                                moveMade = True
                                animate = True
                                sqSelected = ()
                                playerClicks = []
                        if not moveMade:
                            playerClicks = [sqSelected]

            elif e.type == pg.KEYDOWN:
                if e.key == pg.K_z:
                    gs.undoMove()
                    moveMade = True
                    animate = False
                    if AIThinking:
                        moveFinderProcess.terminate()
                        AIThinking = False
                    moveUndone = True
                if e.key == pg.K_r:
                    gs = cE.GameState()
                    validMoves = gs.getValidMoves()
                    sqSelected = ()
                    playerClicks = []
                    moveMade = False
                    animate = False
                    gameOver = False
                    if AIThinking:
                        moveFinderProcess.terminate()
                        AIThinking = False
                    moveUndone = True
                if e.key == pg.K_q:
                    menu.mainloop(surface)

        # AI decision
        if not gameOver and not humanTurn and not moveUndone:
            if not AIThinking:
                AIThinking = True
                print('thinking...')
                pg.event.post(pg.event.Event(7734))
                returnQueue = Queue()  # used to pass data between threads
                moveFinderProcess = Process(target=AI.findBestMoveNegaMax,
                                            args=(gs, validMoves, returnQueue))
                moveFinderProcess.start()

            if not moveFinderProcess.is_alive():
                print("done thinking")
                AIMove = returnQueue.get()
                if AIMove is None:
                    AIMove = AI.findRandomMove(validMoves)
                gs.makeMove(AIMove)
                moveMade = True
                animate = True
                AIThinking = False

        # Human decision
        if moveMade:
            if animate:
                animateMove(gs.moveLog[-1], surface, gs.board, clock)
            validMoves = gs.getValidMoves()
            moveMade = False
            animate = False
            moveUndone = False

        drawGameState(surface, gs, validMoves, sqSelected)

        # Check end of game
        if gs.checkMate:
            gameOver = True
            if gs.whiteToMove:
                drawText(surface, 'Black wins by checkmate!')
            else:
                drawText(surface, 'White wins by checkmate!')
        elif gs.staleMate:
            gameOver = True
            drawText(surface, 'Stalemate')

        clock.tick(MAX_FPS)
        pg.display.flip()
Example #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()  #initialize game state
    validMoves = gs.getValidMoves()
    moveMade = False
    animate = False  #flag variable which moves are to be animated

    loadImages()  #load images only once before while loop

    running = True
    gameOver = False  # Game is over flag
    selected_sq = ()  # no square selected initially, tuple (row, col)
    player_clicks = [
    ]  # keep track of clicks, max two tuples [(r1, c1), (r2, c2)]
    while running:

        for e in p.event.get():

            if e.type == p.QUIT:
                running = False

            # mouse event handlers
            elif e.type == p.MOUSEBUTTONDOWN:
                if not gameOver:
                    location = p.mouse.get_pos()  #(x,y) coordinates of mouse
                    col = location[
                        0] // sq_size  # // double divide to get integers
                    row = location[1] // sq_size
                    if selected_sq == (row,
                                       col):  #user clicks same square twice
                        selected_sq = ()
                        player_clicks = []
                    else:
                        selected_sq = (row, col)
                        player_clicks.append(
                            selected_sq)  #append both 1st and 2nd click
                    if len(player_clicks) == 2:  #2nd click
                        move = chessEngine.Move(player_clicks[0],
                                                player_clicks[1], gs.board)
                        for i in range(len(validMoves)):
                            if move == validMoves[i]:
                                gs.makeMove(
                                    validMoves[i])  # make move if it is valid
                                moveMade = True
                                animate = True  #only animate made moves
                                print("White to Move? - " +
                                      str(gs.whiteToMove))
                                selected_sq = (
                                )  # reset selected player squares
                                player_clicks = []
                                break
                        if not moveMade:
                            player_clicks = [selected_sq]

            # key event handlers
            elif e.type == p.KEYDOWN:
                if e.key == p.K_z:  # 'z' Key to undo move
                    gs.undoMove()
                    selected_sq = ()  # reset selections
                    player_clicks = []
                    moveMade = True
                    animate = False
                    gameOver = False
                if e.key == p.K_r:  # resets the board with 'r' Key
                    gs = chessEngine.GameState()
                    validMoves = gs.getValidMoves()
                    selected_sq = ()
                    player_clicks = []
                    moveMade = False
                    animate = False
                    gameOver = False

        if moveMade:  #only generate new valid move list if a valid move was actually made
            if animate:
                animateMove(gs.moveLog[-1], screen, gs.board,
                            clock)  #animate move
            validMoves = gs.getValidMoves()
            moveMade = False
            animate = False

        # draw game
        drawGameState(screen, gs, validMoves, selected_sq)
        if gs.isCheckMate:
            gameOver = True
            if not gs.whiteToMove:
                drawText(screen, "White wins by Checkmate!")
            else:
                drawText(screen, "Balck wins by Checkmate!")
        if gs.isStaleMate:
            gameOver = True
            drawText(screen, "Stalemate!")

        clock.tick(max_fps)
        p.display.flip()
Example #4
0
def main():
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))

    # game state object
    gs = chessEngine.GameState()
    validMoves = gs.getValidMoves()
    moveMade = False  # flag variable for when a move is made
    animate = False  # flag variable for when we animate a move
    loadImages()

    run = True
    # no square selected initially(keeps track of last square selected)
    sqSelected = ()
    # keep track of player clicks e.g.(two tuples=>[(6,5),(5,5)])
    playerClicks = []
    gameOver = False

    playerOne = False  # if a human is playing white then it will be true,if AI then false
    playerTwo = False  # same as above but for black

    while run:
        humanTurn = (gs.whiteToMove and playerOne) or (not gs.whiteToMove
                                                       and playerTwo)
        for e in p.event.get():
            if e.type == p.QUIT:
                run = False
            # mouse handlers
            elif e.type == p.MOUSEBUTTONDOWN:
                if not gameOver and humanTurn:
                    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):  # user clicked on same square twice
                        sqSelected = ()  # deselect
                        playerClicks = []  # clear player clicks
                    else:
                        sqSelected = (row, col)
                        # append for both first and second clicks
                        playerClicks.append(sqSelected)

                    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])
                                moveMade = True
                                print(move.getChessNotation())
                                sqSelected = ()  # reset user clicks
                                playerClicks = []
                                animate = True
                        if not moveMade:
                            playerClicks = [sqSelected]
            # key handlers
            elif e.type == p.KEYDOWN:
                if e.key == p.K_z:  # undo when z  is pressed
                    gs.undoMove()
                    animate = False
                    moveMade = True
                if e.key == p.K_r:  # reset the board when r is pressed
                    gameOver = False
                    gs = chessEngine.GameState()
                    validMoves = gs.getValidMoves()
                    sqSelected = ()
                    playerClicks = []
                    moveMade = False
                    animate = False

        # AI move
        if not gameOver and not humanTurn:
            AIMove = moveAI.findBestMove(gs, validMoves)
            if AIMove is None:
                AIMove = moveAI.findRandomMove(validMoves)
            gs.makeMove(AIMove)
            moveMade = True
            animate = True

        if moveMade:
            if animate:
                animateMove(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()
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
    animate=False
    loadImages()   #only do this once , before the while loop
    running = True
    sqSelected = ()  #no square is slected ,keep track of the last click of the user (tuple:(row,col))
    playerClicks = []  #keep track of player clicks(two tuples:[;(6,4),(4,4)])
    gameOver = False
    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False
                
            elif e.type == p.MOUSEBUTTONDOWN:
                if gameOver!=True:
                    location = p.mouse.get_pos()#(x,y) location of mouse motion
                    col = location[0]//SQ_SIZE
                    row = location[1]//SQ_SIZE
                    if sqSelected == (row, col):# user clicked the same squre twice
                        sqSelected = ()# deselected
                        playerClicks = []#cler player click
                    else:
                        sqSelected = (row, col)
                        playerClicks.append(sqSelected)
                    if len(playerClicks) == 2: #after 2nd
                        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
                                animate = True
                                sqSelected = ()
                                playerClicks = []
                        if not moveMade:
                            playerClicks = [sqSelected]          
            elif e.type == p.KEYDOWN:
                if e.key == p.K_z:
                    gs.undoMove()
                    moveMade = True
                if e.key ==p.K_r :# reset
                    gs = chessEngine.GameState()
                    validMoves = gs.getValidMoves()
                    sqSelected = ()
                    playerClicks=[]
                    moveMade = False
                    animate = False 
        if moveMade:
            if animate:
                animateMove(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 Win by CheckMate')
            else :
                drawText(screen,'White  win by CheckMet')
        elif gs.staleMate:
            gameOver = True
            drawText(screen,'Check')

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