Search code examples
pythontimepygamewaitsleep

Pygame and pygame.time.wait() function is working in a bizarre way


I am trying to change the pygame screen. First, I draw a rect. Then, I fill the screen again. In-between I add wait function to see the change. When I run program, screen starts black and waits for every wait function without doing any changes. Then, it shows the end result.

import pygame
BlockList=[]
pygame.init()
block_side_length=30
black = 0,0,0
GameArea_start_x=5
GameArea_start_y=5
GameArea_width=300
GameArea_height=270
gameDisplay = pygame.display.set_mode((400,300))
pygame.display.set_caption("Tetris")
gameDisplay.fill((0,100,100))
GameArea = pygame.draw.rect(gameDisplay,black,[GameArea_start_x,GameArea_start_y,GameArea_width,GameArea_height])
lowest_block_y =GameArea_start_y+GameArea_height-block_side_length
pygame.time.wait(2000)
gameDisplay.fill((0,100,100))
pygame.draw.rect(gameDisplay,(0,250,0),[50,50,40,90])
pygame.time.wait(2000)
gameDisplay.fill((0,100,100))
GameArea

Output:

enter image description here

After 4 secs

enter image description here

Note: I am trying to draw the rectangle by calling its name. It doesn't work. Is there any similar fashion?


Solution

  • In order to update what is shown in the pygame window, you must call pygame.display.update(), like so:

    import pygame
    BlockList=[]
    pygame.init()
    block_side_length=30
    black = 0,0,0
    GameArea_start_x=5
    GameArea_start_y=5
    GameArea_width=300
    GameArea_height=270
    gameDisplay = pygame.display.set_mode((400,300))
    pygame.display.set_caption("Tetris")
    gameDisplay.fill((0,100,100))
    GameArea = pygame.draw.rect(gameDisplay,black,[GameArea_start_x,GameArea_start_y,GameArea_width,GameArea_height])
    lowest_block_y =GameArea_start_y+GameArea_height-block_side_length
    pygame.display.update()
    pygame.time.wait(2000)
    gameDisplay.fill((0,100,100))
    pygame.draw.rect(gameDisplay,(0,250,0),[50,50,40,90])
    pygame.display.update()
    pygame.time.wait(2000)
    gameDisplay.fill((0,100,100))
    pygame.display.update()
    

    Note that your approach of calling pygame.time.wait() for long periods of time will cause the window to freeze and become unresponsive while waiting. Some better approaches are described in this stackoverflow question.