1

I'm new to using Pygame and have a question about MOUSEBUTTONDOWN and pygame.draw.circle() When clicking the 62.5x62.5 square inside of the screen , I want it to show a green circle and when clicking it again, I want it to disappear. I don't know how to do it and in my code I have to spam click the square for the circle to appear for a split second then it disappears again. I've also tried using a while loop but couldn't make it work.

import pygame
pygame.init()

screen = pygame.display.set_mode((800, 600))

running = True
while running:
    screen.fill((0, 0, 0))
    mouse_pos = pygame.mouse.get_pos()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False          
        if event.type == pygame.MOUSEBUTTONDOWN and  mouse_pos[0] >= 150 and  mouse_pos[0] <= 212.5 \
            and  mouse_pos[1] >= 425 and  mouse_pos[1] <= 487.5: 
            pygame.draw.circle(screen, (152, 251, 152), (181.25, 393.75), 20)
            

    pygame.display.update()
Beza
  • 37
  • 4

1 Answers1

1

You need to draw the circle in the event loop rather than in the event loop. Add a Boolean variable draw_circle and toggle the state of the variable when you click the mouse.
You can't draw with floating point accuracy. Pixels and the mouse position have integral units.
Use a pygame.Rect object and collidepoint() for the click test. The position of the mouse click is stored in the pos attribute of the pygame.event.Event() object:

import pygame
pygame.init()

screen = pygame.display.set_mode((800, 600))

draw_circle = False
test_rect = pygame.Rect(0, 0, 40, 40)
test_rect.center = (181, 393)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False          
        if event.type == pygame.MOUSEBUTTONDOWN:
            if test_rect.collidepoint(event.pos):
                draw_circle = not draw_circle

    screen.fill((0, 0, 0))
    pygame.draw.rect(screen, (127, 127, 127), test_rect, 1) # for debugging
    if draw_circle:        
        pygame.draw.circle(screen, (152, 251, 152), (181, 393), 20)
    pygame.display.update()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174