How do I make an if block that checks for rectangle collisions operate only once?

Question:

I am creating a game in pygame where when a player rectangle collides with a green/blue rectangle, they get points. My issue is that when the player collides with the point rectangles, it registers the if block that adds points many times and thus adds way too many points to the points counter, when I only want it to add one point for each blue rectangle and three for each green. I’ll get numbers in the 200s for points, when I should be getting numbers from 0-50.

Here is the code that is relevant:

blpt = True
gnpt = True
while running:
    #add points if collide with rectangle
    if player_rect.colliderect(bluerect):
        blpt = False
        points += 1
    if player_rect.colliderect(greenrect):
        gnpt = False
        points += 3
    
    #draw point rectangles
    if blpt:
        pygame.draw.rect(screen, "aquamarine3", bluerect)
    if gnpt:
        pygame.draw.rect(screen, "darkolivegreen", greenrect)

I’ve tried moving the ‘add points’ if-blocks around in the code, but it doesn’t change anything significantly. I need a way to make the if-block operate only once when the collision occurs, turn it into an event somehow, or find some other way that adds only one point to the counter.

Asked By: amahd

||

Answers:

The issue you’re having is that the collision code checks every cycle (every time the while loop runs) but the player does not react that quickly. Normally, you’d handle this sort of thing as an event but you could also do it with a simple Boolean flag for each rectangle:

greenCollision = True
blueCollision = True
while running:
    if player_rect.colliderect(bluerect):
        if blueCollision:
            blpt = False
            points += 1
            blueCollision = False
    else:
        blueCollision = True
    if player_rect.colliderect(greenrect):
        if greenCollision:
            gnpt = False
            points += 3
            greenCollision = False
    else:
        greenCollision = True
Answered By: Woody1193
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.