问题
I just started with pygame, and I am just trying to move points across my screen. The problem is that it happens way to fast and my pygame screen freezes (Not Responding) while the loop runs and then only shows the last iterations position of dots. I am thinking the updating happens to fast.
When I include pygame.event.wait()
then as I give an input the loop progresses and I can follow live in the window how the dots are moving across the screen. However, I would like to have it that they move across the screen without an input required.
This is my main loop:
def run(self):
self.food_spread()
self.spawn_animal()
for k in range(20000):
print(k)
for member in self.zoo:
self.move(member)
self.screen.fill(black)
for i in range(self.food_locations.shape[0]):
pygame.draw.rect(self.screen, white, (self.food_locations[i,1], self.food_locations[i,2],1,1))
for member in self.zoo:
pygame.draw.circle(self.screen, green,(member.location[0], member.location[1]), 2,1)
pygame.display.update()
pygame.event.wait()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
回答1:
You have an application loop, use if. Use pygame.time.Clock() to control the framerate . The application loop has to
- control the framerate (
clock.tick(60)
) - handel the events and move the objects
- clear the display
- draw the scene
- update the display
e.g:
class App:
def __init__(self):
# [...]
self.clock = pygame.time.Clock()
def run(self):
self.food_spread()
self.spawn_animal()
run = True
while run:
# control the framerate
self.clock.tick(60) # 60 FPS
# handel the events
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# move the objects
for member in self.zoo:
self.move(member)
# clear the display
self.screen.fill(black)
# draw the scene
for i in range(self.food_locations.shape[0]):
pygame.draw.rect(self.screen, white, (self.food_locations[i,1], self.food_locations[i,2],1,1))
for member in self.zoo:
pygame.draw.circle(self.screen, green,(member.location[0], member.location[1]), 2,1)
# update the display
pygame.display.update()
来源:https://stackoverflow.com/questions/60029598/pygame-wait-for-screen-to-update