Search code examples
pythonimagepygameflicker

Why is one of my image flickering in Pygame?


When I tried to run this program one of the image doesnt flicker(no conditions), but for the other image(i made it it only shows if you click the left mouse button) flickers, and i dont really know how to fix it, So here is my program:

import pygame, sys
from pygame.locals import *

pygame.init()

screen_size = (900, 600)#game size

screen = pygame.display.set_mode(screen_size,0, 32)

clock = pygame.time.Clock()

bullet = pygame.image.load('bullet_right.png')

display = pygame.Surface((300,200))

displaybullet = False

while True:
    display.fill((255,255,255))

    display.blit(bullet, (0,100))#no flicker :)
    
    mouse_x, mouse_y = pygame.mouse.get_pos()

    mouse_info = pygame.mouse.get_pressed()#0.lmb, 1.scroll thing 2.rmb

    print(mouse_info[0])
    
    for event in pygame.event.get():
        if event.type == QUIT:#stops the program when press exit
            pygame.quit()
            sys.exit()

        if mouse_info[0] == True:
            displaybullet = True
            #display.blit(bullet, (100,100))
        if displaybullet:
            display.blit(bullet, (100,100))#flicker:(
            
    surf = pygame.transform.scale(display, screen_size)
    screen.blit(surf, (0,0))
    
    pygame.display.update()

    clock.tick(60)

I first tried removing the clock.tick(60) but it doesnt seem to work.


Solution

  • This is a matter of indentation. You need to draw the image in the application loop, not the event loop. The application loop is executed once per frame, but the event loop is executed only when an event occurs. If you draw the image in the event loop, it is drawn only when an event occurs, and not once per frame. This causes the flickering.

    displaybullet = False
    
    while True:
        display.fill((255,255,255))
        display.blit(bullet, (0,100))#no flicker :)
        
        mouse_x, mouse_y = pygame.mouse.get_pos()
        mouse_info = pygame.mouse.get_pressed()#0.lmb, 1.scroll thing 2.rmb
    
        print(mouse_info[0])
        
        for event in pygame.event.get():
            if event.type == QUIT:#stops the program when press exit
                pygame.quit()
                sys.exit()
    
            if mouse_info[0] == True:
                displaybullet = True
                #display.blit(bullet, (100,100))
    
        # INDENTAITON
        #<--|
        if displaybullet:
            display.blit(bullet, (100,100))#flicker:(
                
        surf = pygame.transform.scale(display, screen_size)
        screen.blit(surf, (0,0))
        pygame.display.update()
        clock.tick(60)