微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么 Pygame 在创建窗口之前等待精灵加载?

如何解决为什么 Pygame 在创建窗口之前等待精灵加载?

我一直在尝试创建一个精灵创建器,但我注意到 pygame 窗口在所有这些精灵创建后才会加载,我想知道两件事:

  1. 为什么它只在所有这些精灵创建后才加载屏幕
  2. 如何在不改变太多的情况下解决此问题

代码

#!/usr/bin/env python3
import random
import pygame
import time

display_width = 1280
display_height = 720
rotation = random.randint(0,359)
size = random.random()
pic = pygame.image.load('assets/meteor.png')
pygame.init()
clock = pygame.time.Clock()
running = True


class Meteor(pygame.sprite.Sprite):
    def __init__(self,x=0,y=0):
        pygame.sprite.Sprite.__init__(self)

        self.rotation = random.randint(0,359)
        self.size = random.randint(1,2)
        self.image = pic
        self.image = pygame.transform.rotozoom(self.image,self.rotation,self.size)

        self.rect = self.image.get_rect()
        self.rect.center = (x,y)


all_meteors = pygame.sprite.Group()

# completely random spawn
for i in range(5):
    new_x = random.randrange(0,display_width)
    new_y = random.randrange(0,display_height)
    all_meteors.add(Meteor(new_x,new_y))
    time.sleep(2) # this*5 = time for screen to show up

主要:

import pygame
import meteors
pygame.init()
while True:
    meteors.all_meteors.update()
    meteors.all_meteors.draw(screen)
    pygame.display.update()

我不知道为什么它在创建 pygame 窗口之前优先创建精灵,它阻止我创建无数的流星精灵。

解决方法

不要在应用程序循环之前创建流星,而是在循环中延迟创建它们。

在主循环之前,使用 pygame.time.get_ticks() 以毫秒为单位获取当前时间并设置开始时间。 定义一个新陨石应该出现的时间间隔。当一颗陨石产生时,计算下一颗陨石必须产生的时间:

next_meteor_time = 0
meteor_interval = 2000 # 2000 milliseconds == 2 sceonds

while ready:
    clock.tick(60)  # FPS,Everything happens per frame
    for event in pygame.event.get():
        # [...]

    # [...]

    current_time = pygame.time.get_ticks()
    if current_time >= next_meteor_time:
         next_meteor_time += meteor_interval
         new_x = random.randrange(0,display_width)
         new_y = random.randrange(0,display_height)
         all_meteors.add(Meteor(new_x,new_y))

    # [...]


    meteors.all_meteors.update()
    meteors.all_meteors.draw(screen)
    pygame.display.update()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。