Skip to content
Advertisement

PyGame: issue with MOUSEBUTTONDOWN events

I’m trying to build a game of Chess in PyGame. My code is something like this:

while running:
    pygame.display.update()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                select_piece(event.pos)
                        
        
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                # Will move the piece if it is selected:
                if piece_currently_selected and event.pos == selected_piece_coordinates:
                    selected_piece_name = moves[selected_piece]
                    
                    Position.move_piece(selected_piece_name, 'd4') 
                    piece_currently_selected = False # The piece has been moved, so we change this to False again.

What I’m trying to do is this: The first MOUSEDOWNEVENT will select a piece that the user clicks on. If the user didn’t click on the piece, it will simply return None. The second MOUSEDOWNEVENT will actually move the selected piece to the new address that the user clicked on.

The problem is, both events run almost instantaneously. As soon as the first MOUSEDOWNEVENT has selected the piece, the second MOUSEDOWNEVENT runs and immediately moves it, before the user has the chance to click on a new square and move it there.

So I need to make it so that the user first clicks to select a piece, then clicks on a different location to move that piece there. How would I do that? Thank you! <3

Advertisement

Answer

You cannot implement a “first” and a “second” MOUSEBUTTONDOWN event. The event doesn’t know whether it is the first or the second. You have to implement 1 MOUSEBUTTONDOWN event and distinguish whether a piece is currently selected or not:

while running:
    pygame.display.update()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:

                if not piece_currently_selected:
                    # no pices is selected -> select a piece

                    select_piece(event.pos)

                else:
                    # a pieces is selected -> move the piece
                    # [...]

                    # deselect the piece when the piece is successfully moved
                    piece_currently_selected = False
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement