pygame - 为什么 pygame 中的 while 循环不断导致游戏崩溃?

标签 pygame

代码工作得很好,直到我添加 while true: 也由于某种原因,sleep函数让整个代码等待。但是,我只希望 sleep() 之后的部分等待

import pygame, sys
pygame.init()
from time import sleep

screen = pygame.display.set_mode((500,400))

PINK = (255,192,203)
WHITE = (255,255,255)


screen.fill(PINK)
pygame.display.update()


font = pygame.font.SysFont("comicsansms", 72)


text = font.render("loading", True, WHITE)
textrect = text.get_rect()
textrect.center = (225,40)
screen.blit(text,textrect)


while True:
    pygame.event.get()    sleep(1)
    text = font.render(".", True, WHITE)
    textrect = text.get_rect()
    textrect.center = (350,40)
    screen.blit(text,textrect)
    sleep(0.5)
    text = font.render(".", True, WHITE)
    textrect = text.get_rect()
    textrect.center = (370,40)
    screen.blit(text,textrect)
    sleep(0.5)
    text = font.render(".", True, WHITE)
    textrect = text.get_rect()
    textrect.center = (390,40)
    screen.blit(text,textrect)
    sleep(0.5)

最佳答案

[...] The sleep function makes the entire code wait

是的!确实如此。无论如何,整个线程。 PyGame 使用“事件模型”来处理用户界面。上面的代码与此“对抗”,但是虽然您可能会在屏幕上看到更新,但就您的操作环境而言,本质上该应用程序已“锁定”(无响应)。您的操作系统认为这是因为您的程序不接受事件。

PyGame 应用程序应该处理事件队列中的事件(即使它除了退出之外什么也不做)。因此,与其使用 time.sleep() 实现时间,不如使用 pygame.time.get_ticks() 提供的实时时钟要好得多。此函数返回时间为自程序启动以来的毫秒数。您的程序需要在特定时间发生多种事情。这些可以在开始时(时间=0)创建,并且可以在未来的某个时间创建。如果时钟显示时间已经过去,那么就去做这些事情。

实现此目的的一种方法是创建一个简单的结构来保存文本项以及将来需要绘制它们的时间:

### Structure to hold some text to draw
### after a certain number of seconds have passed
class TimedText:
    def __init__( self, text, position, at, colour=WHITE ):
        self.text     = text
        self.position = position,
        self.at_time  = at * 1000    # convert to milliseconds
        self.colour   = colour

在主循环开始之前创建这些项目:

### Make some timed-text structures/objects
timed_texts = []
timed_texts.append( TimedText( "loading", (225,40), 0.0 ) )
timed_texts.append( TimedText( ".",       (350,40), 0.5 ) )
timed_texts.append( TimedText( ".",       (370,40), 1.0 ) )
timed_texts.append( TimedText( ".",       (390,40), 1.5 ) )

然后在主循环中,查看每个项目,绘制需要绘制的文本 - 但根据时钟。

# Loop through each timed-text structure
#     Check if enough time has elapsed, and if-so, draw the text:
for tt in timed_texts:
    if ( time_now >= tt.at_time ):   # has enough time elapsed
        text = font.render( tt.text, True, tt.colour )
        textrect = text.get_rect()
        textrect.center = tt.position
        screen.blit( text, textrect )

这允许您的代码处理事件,并且仍然具有定时文本动画。

引用代码:

import pygame

# Window size
WINDOW_WIDTH    = 500
WINDOW_HEIGHT   = 400
WINDOW_SURFACE  = pygame.HWSURFACE|pygame.DOUBLEBUF|pygame.RESIZABLE

PINK  = (255,192,203)
WHITE = (255,255,255)

### initialisation
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ), WINDOW_SURFACE )
pygame.display.set_caption("Going Dotty...")


### Structure to hold some text to draw
### after a certain number of seconds have passed
class TimedText:
    def __init__( self, text, position, at, colour=WHITE ):
        self.text     = text
        self.position = position,
        self.at_time  = at * 1000    # convert to milliseconds
        self.colour   = colour


### Make some timed-text structures/objects
font = pygame.font.SysFont("comicsansms", 72)
timed_texts = []
timed_texts.append( TimedText( "loading", (225,40), 0 ) )
timed_texts.append( TimedText( ".",       (350,40), 0.5 ) )
timed_texts.append( TimedText( ".",       (370,40), 1.0 ) )
timed_texts.append( TimedText( ".",       (390,40), 1.5 ) )

### Main Loop
clock = pygame.time.Clock()
done = False
while not done:

    # Handle user-input
    for event in pygame.event.get():
        if ( event.type == pygame.QUIT ):
            done = True
        elif ( event.type == pygame.MOUSEBUTTONUP ):
            # On mouse-click
            pass
        elif ( event.type == pygame.KEYUP ):
            # On key-release
            #keys = pygame.key.get_pressed()
            pass

    # Update the window, but not more than 60fps
    screen.fill( PINK )

    time_now = pygame.time.get_ticks()

    # Loop through each timed-text structure
    #     Check if enough time has elapsed, and if-so, draw the text:
    for tt in timed_texts:
        if ( time_now >= tt.at_time ):   # has enough time elapsed
            text = font.render( tt.text, True, tt.colour )
            textrect = text.get_rect()
            textrect.center = tt.position
            screen.blit( text, textrect )

    pygame.display.flip()
    clock.tick_busy_loop(60)


pygame.quit()

关于pygame - 为什么 pygame 中的 while 循环不断导致游戏崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62747184/

相关文章:

python - 如何在 pygame 中限制调整窗口大小

python - 使用多处理创建两个 pygame 屏幕

python - Pygame 文本不渲染

python - 在 mac 上安装 Python/PyGame

python - pygame中盒子的连续移动

python - Pygame 程序停止响应,没有错误

python - Sprite 没有朝它所面对的同一方向移动

Python点曲线

python - Pygame - 按退格键更改 Sprite 颜色

python - 使用pygame移动矩形不断闪烁