【问题标题】:Why is Pygame waiting for sprites to load before creating the window? [duplicate]为什么 Pygame 在创建窗口之前要等待精灵加载? [复制]
【发布时间】:2021-05-06 19:51:24
【问题描述】:

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

  1. 为什么它只在所有这些 sprite 创建后才加载屏幕
  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 窗口之前优先创建精灵,并且它阻止我创建无穷无尽的流星精灵。

【问题讨论】:

  • 问题不清楚。应用程序循环仅在执行循环之前的代码时开始。为什么在创建流星的循环中有time.sleep(2)
  • 复制随机流星生成。我现在只选择了 2

标签: python python-3.x pygame pygame-surface pygame2


【解决方案1】:

不要在应用程序循环之前创建流星,在循环中创建有时间延迟的流星。

在主循环之前使用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()

【讨论】:

  • 在创建所有流星之前,pygame 窗口仍然不会显示,并且由于这是一个循环,它只会继续制作流星而不创建窗口本身。
  • 我一点也不怪你,我只是告诉你我到底发生了什么。
  • 好吧,我可能听起来很粗鲁,所以我很抱歉。我以前读过你的答案,但当时它加载了除了流星之外的所有东西,所以我真的很困惑,想知道我是否做错了什么。我将我的代码修改为一个文件,这样我就可以知道什么不起作用,但我显然不能。 (pastebin.com/AeLxv6TZ)
  • @DarkSlayer3202 您必须将代码放在应用程序循环中,而不是在代码末尾添加第二个应用程序循环
  • 好的,我刚刚意识到我的 IDE 正在尝试运行我的主脚本的旧版本。 o_o 很抱歉浪费您的时间。
猜你喜欢
  • 1970-01-01
  • 2021-08-29
  • 2016-04-18
  • 1970-01-01
  • 1970-01-01
  • 2021-10-04
  • 1970-01-01
  • 2020-11-22
  • 2013-06-12
相关资源
最近更新 更多