Search code examples
pythonpygamecursor

Why does pygame window animationonly work when i am moving my cursor


I am making flappy bird following this guide https://www.youtube.com/watch?v=UZg49z76cLw&t=1309s but the screen only updates when i move my cursor does anyone know how to fix this

import pygame, sys


def draw_floor():
    screen.blit(floor_surface, (floor_animation, 400))
    screen.blit(floor_surface, (floor_animation + 275,400))


pygame.init()

screen = pygame.display.set_mode((275,512))
clock = pygame.time.Clock()

bg_surface = pygame.image.load('C:/Users/cuerv/Downloads/flappy-bird-assets-master/flappy-bird-assets-master/sprites/background-day.png').convert()
floor_surface = pygame.image.load('C:/Users/cuerv/Downloads/flappy-bird-assets-master/flappy-bird-assets-master/sprites/base.png').convert()
floor_animation = 0

bird_surface = pygame.image.load('C:/Users/cuerv/Downloads/flappy-bird-assets-master/flappy-bird-assets-master/sprites/bluebird-midflap.png').convert()
bird_rect = bird_surface.get_rect(center = (100,256))

while True:
   
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
         
            pygame.quit()
            sys.exit()
        screen.blit(bg_surface, (0, 0))
        screen.blit(bird_surface, (bird_rect))
        
        floor_animation -= 1
        draw_floor()
        if floor_animation <= -275:
            floor_animation = 0            
        screen.blit(floor_surface, (floor_animation, 400))




    pygame.display.update()
    clock.tick(120)
    enter code here

Solution

  • Its a matter of Indentation. Draw the scene in the application loop rather than the event loop:

    # application loop
    while True:
       
        # event loop
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
             
                pygame.quit()
                sys.exit()
        
        #<--| INDENTATION
    
        screen.blit(bg_surface, (0, 0))
        screen.blit(bird_surface, (bird_rect))     
        floor_animation -= 1
        draw_floor()
        if floor_animation <= -275:
            floor_animation = 0            
        screen.blit(floor_surface, (floor_animation, 400))
    
        pygame.display.update()
    

    Note, the event loop is only executed when an event occurs, but the application loop is executed continuously.