为什么while循环不断使pygame中的游戏崩溃? [英] why does the while loop keep making the game crash in pygame?

查看:58
本文介绍了为什么while循环不断使pygame中的游戏崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码工作正常,直到我添加 while true:也出于某种原因,睡眠功能使整个代码等待.但是,我只希望 sleep() 之后的部分等待

the code works just fine until I add the while true: also for some reason, the sleep function makes the entire code wait. however, I want only the parts after sleep() to wait

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)

推荐答案

[...] sleep 函数让整个代码等待

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

是的!确实如此.无论如何,整个线程.PyGame 使用事件模型"使用用户界面.您上面的代码打架"与此相反,虽然您可能会在屏幕上看到更新,但实际上该应用程序已锁定";(无响应)就您的操作环境而言.您的操作系统认为这是因为您的程序不接受事件.

Yes! It does. The entire thread anyway. PyGame uses an "event model" to work with the user-interface. Your code above "fights" against this, but while you might see the updates on-screen, essentially the application has "locked up" (is non-responsive) as far as your operating environment it concerned. Your OS thinks this because your program is not accepting events.

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

A PyGame application should process the events in the event-queue (even if it does nothing except exit). So instead of implementing times with time.sleep(), it's much better to use the real-time clock provided by pygame.time.get_ticks(). This function returns the time as the number of milliseconds since your program started. Your program needs multiple things to happen at certain times. These can be created at the beginning (time=0), with a time in the future. If the clock says this time has passed, then do the things.

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

One way to implement this is to create a simple structure to hold your text items, and the time they need to be drawn in the future:

### 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

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

Create these items before your main loop starts:

### 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 ) )

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

Then in your main loop, look through each of the items, drawing the texts that need to be draw - but according to the clock.

# 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 )

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

This allows your code to process the events, and still have timed text-animation.

参考代码:

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()

这篇关于为什么while循环不断使pygame中的游戏崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆