python - pygame.time.wait() 使程序崩溃

标签 python python-3.x pygame

在 pygame 代码中,我想做一个改变颜色的标题。 我试着做一个简单的标题来改变颜色,但它甚至没有把颜色变成蓝色(或做一秒钟),程序崩溃了。代码:

title_font = pygame.font.SysFont("monospace", TITLE_SIZE)

while True:
    title = title_font.render("game", 5, RED)
    game_display.blit(title, TITLE_POS)
    pygame.display.update()
    pygame.time.wait(2000)

    title = title_font.render("game", 5, BLUE)
    game_display.blit(title, TITLE_POS)
    pygame.display.update()
    pygame.time.wait(3000)

    title = title_font.render("game", 5, RED)
    game_display.blit(title, TITLE_POS)
    pygame.display.update()
    pygame.time.wait(2000)

pygame.time.delay()也会出现,不知道是哪里出了问题...

最佳答案

不要使用 pygame.time.waitdelay,因为这些函数会使您的程序在给定时间内休眠,并且窗口变得无响应。您还需要在每一帧处理事件(使用 pygame.event 函数之一)以避免这种情况。

这里有一些不阻塞的计时器示例:Countdown timer in Pygame

要切换颜色,您只需将下一种颜色分配给变量并使用它来呈现文本。

import pygame


pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
title_font = pygame.font.SysFont('monospace', 50)
BACKGROUND_COLOR = pygame.Color('gray12')
BLUE = pygame.Color('blue')
RED = pygame.Color('red')
# Assign the current color to the color variable.
color = RED
timer = 2
dt = 0

done = False
while not done:
    # Handle the events.
    for event in pygame.event.get():
        # This allows the user to quit by pressing the X button.
        if event.type == pygame.QUIT:
            done = True

    timer -= dt  # Decrement the timer by the delta time.
    if timer <= 0:  # When the time is up ...
        # Swap the colors.
        if color == RED:
            color = BLUE
            timer = 3
        else:
            color = RED
            timer = 2

    screen.fill(BACKGROUND_COLOR)
    title = title_font.render('game', 5, color)
    screen.blit(title, (200, 50))

    pygame.display.flip()
    # dt is the passed time since the last clock.tick call.
    dt = clock.tick(60) / 1000  # / 1000 to convert milliseconds to seconds.

pygame.quit()

关于python - pygame.time.wait() 使程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51411713/

相关文章:

python - 获取要展开的 WxPython 面板项

python - gdaltools 将 geojson 点导出为多点

python - 有没有办法删除群组的特定内容?

python - 简单的 Tic-Tac_Toe 游戏 Pygame

python - 蛇游戏,但问题是,如果我向左移动蛇,然后向右移动蛇,蛇本身会崩溃或相反,上下相同

python - 通过conda安装特定版本的spyder

python - 稀疏 SciPy 矩阵与两个 NumPy 向量的矩阵乘法

Python列表构建

python - 从生成器获取下一项失败

python - 比较两个字符串中的字符,无论其位置如何