0
votes

Yes, that title wasn't worded very properly at all.

Ok, here's what we've got - a Python program using the pyGame library, and we're making a game. We start in a menu environment main.py. When the user clicks on one of the menu buttons, an action is performed. The program checks for clicks on menu items using the following code:

if event.type == pygame.MOUSEBUTTONDOWN:
            mousePos = pygame.mouse.get_pos()
            for item in buttons: # For each button
                X = item.getXPos() # Check if the mouse click was...
                Y = item.getYPos() # ...inside the button
                if X[0] < mousePos[0] < X[1] and Y[0] < mousePos[1] < Y [1]:
                    # If it was
                    item.action(screen) # Do something

When the user clicks on the "Play Game" button, it opens a sub-module, playGame.py. In this sub-module is another pyGame loop etc.

Part of the game is to hold the left mouse button to 'grow' circles out of the current position (It's a puzzle game, and it makes sense in context). Here is my code for doing this:

mouseIsDown == False
r = 10
circleCentre = (0,0)

[...other code...]

if mouseIsDown == True:
    # This grown the circle's radius by 1 each frame, and redraws the circle
    pygame.draw.circle(screen, setColour(currentColourID), circleCentre, r, 2)
    r += 1

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        runningLevel = False

    elif event.type == pygame.MOUSEBUTTONDOWN:
        # User has pressed mouse button, wants to draw new circle
        circleCentre = pygame.mouse.get_pos()
        mouseIsDown = True

    elif event.type == pygame.MOUSEBUTTONUP:
        # Stop drawing the circle and store it in the circles list
        mouseIsDown = False
        newCircle = Circle(circleCentre, r, currentColourID)
        circles.append(newCircle)
        circleCount += 1
        r = 10 # Reset radius

The problem I have is that the user's left mouse click from the main menu is persisting into the playGame.py module, and causing it to create and store a new circle, of radius 10 and at position (0,0). Both of these are the default values.

This only happens for the one frame after the menu.

Is there any way to prevent this, or is it a flaw in my code?

All help greatly appreciated, as always. If you need more code or explanation of these snippets, let me know.

If you'd like the full code, it's on GitHub.

2

2 Answers

2
votes

You could use MOUSEBUTTONUP instead of MOUSBUTTONDOWN in the menu.

1
votes

Does adding pygame.event.clear() to the top of Play fix it?