Skip to content
Advertisement

Draw rectangle on key click

I want to draw a rectangle with a button click , but the problem is with every loop it updates the display , display is filled with a color So the rectangle is only seen for a brief period of time. How to solve this.

while not run:
    
    display.fill((130,190,255) )
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit_game = True
                 
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_q:
                p_x -= 30
                
            if event.key == pygame.K_p:
                p_x += 30
            
            if event.key == pygame.K_g:
                
                pygame.draw.rect(display , (0,0,0) ,((p_x + 25),1309 ,20,30))

Advertisement

Answer

You have to draw the rectangle in the application loop. For example add a new rectangle to a list when g is pressed. Draw each rectangles in the list in the application loop

rectangles = []

exit_game = False
while not exit_game:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit_game = True
                
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_q:
                p_x -= 30
            if event.key == pygame.K_p:
                p_x += 30
            if event.key == pygame.K_g:
                rectangles.append((p_x + 25, 1309, 20, 30))

    display.fill((130,190,255))
     
    pygame.draw.rect(display, (0,0,0), (p_x + 25, 1309, 20, 30), 1)
    for rect in rectangles:
        pygame.draw.rect(display, (0,0,0), rect)

    pygame.display.update()

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement