conyieie
conyieie

Reputation: 225

Pygame clock and event loops

i am new to pygame and i was wondering what an event loop is and what clock does in this situation, like what is clock.tick(60)? I don't understand any explanations online

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

Upvotes: 2

Views: 4649

Answers (1)

Rabbid76
Rabbid76

Reputation: 210890

The method tick() of a pygame.time.Clock object, delays the game in that way, that every iteration of the loop consumes the same period of time.
That meas that the loop:

clock = pygame.time.Clock()
run = True
while run:
   clock.tick(60)

runs 60 times per second.

for event in pygame.event.get() handles the internal events an retrieves a list of external events (the events are removed from the internal event queue).
If you press the close button of the window, than the causes the QUIT event and you'll get the event by for event in pygame.event.get(). See pygame.event for the different event types. e.g. KEYDOWN occurs once when a key is pressed.

e.g. The following loop prints the names of the a key once it it pressed:

run = True
while run:

    # event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            print(pygame.key.name(event.key))

Upvotes: 3

Related Questions