Reputation: 129
I recently just started to learn pygame and currently working on a tutorial example that has a cat run around the edge of the window.(I replaced the cat with a read rectangle so you can copy past the example)
import pygame
import sys
from pygame.locals import *
pygame.init()
FPS = 5
fpsClock = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((400, 300), 0, 32)
pygame.display.set_caption('Animation')
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# catImg = pygame.image.load('cat.png')
catx = 10
caty = 10
direction = 'right'
while True:
DISPLAYSURF.fill(WHITE)
if direction == 'right':
catx += 5
if catx == 280:
direction = 'down'
elif direction == 'down':
caty += 5
if caty == 220:
direction = 'left'
elif direction == 'left':
catx -= 5
if catx == 10:
direction = 'up'
elif direction == 'up':
caty -= 5
if caty == 10:
direction = 'right'
# DISPLAYSURF.blit(catImg, (catx, caty))
pygame.draw.rect(DISPLAYSURF, RED, (catx, caty, 100, 50))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
fpsClock.tick(FPS)
But if I run it the image shown is not what I expected: the red rectangle is not running unless I put the mouse over the window. (that is probably a design choose. so what ever) More worrying is that the rectangle is not moving in the way I expected. It moves a few steps than is jumps forward along the path a bit, then moves a bit, jumps again and so on. I could not find a pattern in the way the jumps happen. The only thing I can say is that it does not leave the path along the edge of the window.
If I move the line:
DISPLAYSURF.fill(WHITE)
Out of the while loop I can see that the screen is along the skipped part of the path is still colored red afterwards. So it seems to me that the code is still proceed in the background and rectangle is still written to a virtual DISPLAYSURF object, but that DISPLAYSURF object is not printed to the screen. Also the code is run really fast.
I use python 3.8.0 pygame 2.0.0.dev6 on windows
I didn’t find anything on the matter. Did someone have the same problem? Where did this come form?
Upvotes: 2
Views: 58
Reputation: 210890
It's a matter of Indentation. pygame.display.update()
has to be done in the application loop rather than the event loop:
while True:
DISPLAYSURF.fill(WHITE)
# [...]
pygame.draw.rect(DISPLAYSURF, RED, (catx, caty, 100, 50))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
#<---|
pygame.display.update()
fpsClock.tick(FPS)
Note, the code in the application loop is executed in every frame, but the code in the event loop is only executed when an event occurs, like the mouse movement (pygame.MOUSEMOTION
).
Upvotes: 2