Search code examples
pythonpygame

code not related to events in the event loop for pygame


I am making a game with pygame and have a few doubts about the event loop

clock = pygame.time.Clock()
run = True
while run:
    clock.tick(60)
    # event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

Namely, does it run infinitely or does it run for a 60th of a second and can you put non event operators in the loop such as:

clock = pygame.time.Clock()
run = True
while run:
    clock.tick(60)
    # event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.MOUSEBUTTONUP:
            check = True
        if check:
            print("Hello")
            check = False

Would it print "Hello" every time you click or would it break in some way?


Solution

  • The game loop will run infinitely at a maximum of 60 iterations per second due to clock.tick(60). tick is a measure of time in PyGame: clock.tick(60) means that for every second at most 60 frames should pass.

    Your code seems mostly fine, but you need to initialize check before using it:

    clock = pygame.time.Clock()
    run = True
    check = False  #Initialization
    
    while run:
        clock.tick(60)
        # event loop
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            if event.type == pygame.MOUSEBUTTONUP:
                check = True
        if check:
            print("Hello")
            check = False
    

    I haven't run it, but I think it should print "Hello" each time you click.