Exemplo n.º 1
0
def startGame(game: Game):
    playerMoveWhite = True
    while (True):
        if playerMoveWhite:
            print(game.board)
        if not playerMoveWhite:
            engine = Engine()
            startTime = time.time()
            move = engine.selectmove(game.board, False)
            if move is None:
                print("Black resigns")
                break
            game.board.movePiece(move.startPosition, move.endPosition,
                                 move.piece)
            print("Black moves", move, "taking",
                  time.time() - startTime, "seconds")
        else:
            userMove = input()
            if userMove == "Resign" or userMove == "resign":
                break
            try:
                start, end = userMove.split()
                start = parsePositon(start)
                end = parsePositon(end)
                piece = game.board.getPiece(*start)
            except:
                print("Invalid command")
                continue
            if piece is None:
                print("No piece exists there")
                continue
            if piece.Color != WHITE:
                print("That piece is not yours")
                continue
            if not piece.isValid(start, end, piece, game.board):
                print("Invalid move")
                continue
            game.board.movePiece(start, end, piece)

        gs = game.gameStatus(playerMoveWhite)
        if not Engine().kingOnBoard(game.board,
                                    BLACK if playerMoveWhite else WHITE):
            print(game.board)
            print("King captured, ", "WHITE" if playerMoveWhite else "BLACK",
                  "wins")
            break
        if gs == GAME:
            playerMoveWhite = not playerMoveWhite
            print()
        elif gs == CHECKMATE:
            print("CHECKMATE", "WHITE" if playerMoveWhite else "BLACK", "wins")
            break
        else:
            print("STALEMATE game draw")
            break
Exemplo n.º 2
0
def main():
    screen = p.display.set_mode((W, H))
    clock = p.time.Clock()
    screen.fill(p.Color("blue"))
    gs = Engine.State()
    moveMade = False
    print(gs.board)
    LOADIMG()
    running = True
    sqSelected = ()
    playerClicks = []
    while running:  # Run game
        for e in p.event.get():  # get event
            if e.type == p.QUIT:  # if exit, quit
                running = False
                return "True"
                #MOUSE
            elif (e.type == p.MOUSEBUTTONDOWN):  # get which square is clicked
                location = p.mouse.get_pos()
                col = location[0] // sq_size
                row = location[1] // sq_size
                if sqSelected == (row, col):  # if its the same square, ignore
                    sqSelected = ()
                    playerClicks = []
                else:  # if its diffrent append clicks
                    sqSelected = (row, col)
                    playerClicks.append(sqSelected)
                if len(playerClicks
                       ) == 2:  # if the player cicks twice, do the operations
                    move = Engine.Move(playerClicks[0], playerClicks[1],
                                       gs.board)
                    print(move.getChessNotation)
                    gs.makeMove(move)
                    moveMade = True
                    sqSelected = ()
                    playerClicks = []
                    #BUTTON
            if e.type == p.KEYDOWN:  # if "z"is pressed, undo move
                if e.key == p.K_z:
                    gs.UndoMove(move)
                    moveMade = True
        if moveMade:  # if a move has been made, draw screen
            moveMade = False
        drawState(screen, gs)
        clock.tick(MAX_FPS)
        p.display.flip()
        print(gs.board)
Exemplo n.º 3
0
def main():
    pg.init()
    screen = pg.display.set_mode((WIDTH, HEIGHT))
    clock = pg.time.Clock()
    screen.fill(pg.Color("white"))
    game_state = Engine.GameState()
    load_images()
    running = True
    sq_selected = ()  # keep track of the user's last click (row,column)
    player_clicks = [
    ]  # Keep track of # of user clicks (two tuples: [(6,4),(4,4)])

    while running:
        for e in pg.event.get():
            if e.type == pg.QUIT:
                running = False
            elif e.type == pg.MOUSEBUTTONDOWN:
                location = pg.mouse.get_pos()
                col = location[0] // SQ_SIZE
                row = location[1] // SQ_SIZE

                if sq_selected == (row,
                                   col):  # user selected the same square twice
                    sq_selected = ()
                    player_clicks = []

                else:
                    sq_selected = (row, col)
                    player_clicks.append(sq_selected)
                #Resets the click if it is on an empty space
                if len(player_clicks) == 1 and game_state.board[
                        sq_selected[0]][sq_selected[1]].id == '--':
                    sq_selected = ()
                    player_clicks = []

                elif len(player_clicks) == 2:
                    move = Engine.Move(player_clicks[0], player_clicks[1],
                                       game_state.board)
                    if game_state.is_valid_move(move):
                        print(move.get_chess_notation())
                        game_state.makeMove(move)
                    sq_selected = ()
                    player_clicks = []

        draw_game_state(screen, game_state)
        clock.tick(MAX_FPS)
        pg.display.flip()
Exemplo n.º 4
0
def drawGameModeOptions():

    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))

    # Initialize game state
    gameState = Engine.GameState()
    print(gameState.board)

    running = True
    while(running):

        for event in p.event.get():

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

            if event.type == p.MOUSEBUTTONDOWN:
                mousePos = p.mouse.get_pos()

                row = mousePos[1]
                col = mousePos[0]

                selectGameModeOption(row, col)
                running = False

        drawBoard(screen, selectedPiece=None, validMoves=[], gameState=gameState)

        p.font.init()
        myfont = p.font.SysFont('calibri', 90)

        vsPlayer = myfont.render('VS Player', True, (0, 0, 0))
        vsPlayer = p.transform.rotate(vsPlayer, -90)

        screen.blit(vsPlayer, (int(1.5 * SQ_DIMENSION), int(1.5 * SQ_DIMENSION)))

        vsComputer = myfont.render('VS Computer', True, (0, 0, 0))
        vsComputer = p.transform.rotate(vsComputer, -90)

        screen.blit(vsComputer, (int(5.5 * SQ_DIMENSION), int(0.25 * SQ_DIMENSION)))

        clock.tick(MAX_FPS)
        p.display.flip()
Exemplo n.º 5
0
def main():
    p.init()
    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))
    gs = Engine.GameState()
    validMoves = gs.getValidMoves()
    moveMade = False
    animate = False
    LoadImages() #Images only loaded once
    running = True
    sqSelected = ()
    currentMove = [] #Keep track of starting and ending square coordinates
    gameOver = False

    while running:
        for e in p.event.get():
            if e.type == p.QUIT:
                running = False
            #Moving pieces
            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): #Player clicked same square twice, reset move.
                        sqSelected = ()
                        currentMove = []
                    else:
                        sqSelected = (row, col)
                        currentMove.append(sqSelected)
                    #Checks to see if move is valid
                    if len(currentMove) == 2:
                        move = Engine.Move(currentMove[0], currentMove[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 = ()
                                currentMove = []
                        if not moveMade:
                            currentMove = [sqSelected]

            elif e.type == p.KEYDOWN:
                #Undo move using "z"
                if e.key == p.K_z:
                    gs.unndoMove()
                    moveMade = True
                    #Don't animate when undoing
                    animate = False
                #Reset board using "r"
                if e.key == p.K_r:
                    gs = Engine.GameState()
                    validMoves = gs.getValidMoves()
                    sqSelected = ()
                    playerClicks = []
                    moveMade = False
                    animate = False

        if moveMade:
            if animate:
                moveAnimation(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.whiteTurn:
                drawText(screen, 'Black Wins By Checkmate')
            else:
                drawText(screen, 'White Wns By Checkmate')
        elif gs.staleMate:
            gameOver = True
            drawText(screen, 'Stalemate')

        clock.tick(MAX_FPS)
        p.display.flip()
Exemplo n.º 6
0
def playOneVsOne():

    screen = p.display.set_mode((WIDTH, HEIGHT))
    clock = p.time.Clock()
    screen.fill(p.Color("white"))

    # Initialize game state
    gameState = Engine.GameState()
    print(gameState.board)

    running = True

    # The selected piece
    selectedPiece = None

    # Valid moves of the selected piece
    validMoves = []

    # Specifies if the player needs to select the piece that the pawn will be promoted to
    hasToPromote = False

    global checkmateKing
    while running:
        for event in p.event.get():

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

            elif hasToPromote:

                drawGameState(screen, gameState, selectedPiece, validMoves)
                drawPromotionOptions(screen, gameState)

                if event.type == p.MOUSEBUTTONDOWN:
                    mousePos = p.mouse.get_pos()

                    row = mousePos[1]
                    col = mousePos[0]

                    piece = selectPromotedPiece(row, col)

                    if piece is not None:

                        color = Engine.BLACK
                        if not gameState.whiteToMove:
                            color = Engine.WHITE

                        hasToPromote = False
                        gameState.board[gameState.moveLog[-1].endRow][gameState.moveLog[-1].endCol] = color + piece
                        gameState.checkIfTheGameEnded()

            # Undo the last move if the U key is pressed
            elif event.type == p.KEYDOWN:
                if event.key == p.K_u:

                    gameState.undoMove()
                    gameState.checkIfTheGameEnded()

                    selectedPiece = None
                    validMoves = []

            # Mouse input handler
            elif event.type == p.MOUSEBUTTONDOWN and gameState.stalemate == False:
                mousePos = p.mouse.get_pos()

                row = mousePos[1] // SQ_DIMENSION
                col = mousePos[0] // SQ_DIMENSION

                if selectedPiece is None:
                    if (gameState.board[row][col] != Engine.EMPTY_SQUARE) and \
                            gameState.checkSelectedPiece(row, col):

                        selectedPiece = (row, col)

                        validMoves = gameState.getPieceValidMoves(selectedPiece[0], selectedPiece[1])
                        validMoves = validMoves[0] + validMoves[1]

                elif selectedPiece == (row, col): #deselect the piece if it is selected twice

                    selectedPiece = None
                    validMoves = []

                else:

                    destinationSquare = (row, col)

                    for validMove in validMoves:
                        if destinationSquare == (validMove.endRow, validMove.endCol):
                            print(validMove.getChessNotation())
                            gameState.makeMove(validMove)

                            selectedPiece = None
                            validMoves = []

                            if validMove.pawnPromotion is not None:

                                color = Engine.BLACK
                                if not gameState.whiteToMove:
                                    color = Engine.WHITE

                                gameState.board[gameState.moveLog[-1].endRow][gameState.moveLog[-1].endCol] = color + Engine.PAWN

                                hasToPromote = True

                            gameState.checkIfTheGameEnded()
                            MOVE_SOUND.play()
                            break

        if not hasToPromote:
            drawGameState(screen, gameState, selectedPiece, validMoves)

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