Pygame wait for screen to update

試著忘記壹切 提交于 2021-02-05 08:33:09

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!