+-
python-pygame.time.wait()使程序崩溃
在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.wait或delay,因为这些函数会使您的程序在给定的时间内进入睡眠状态,并且窗口无响应.您还需要在每个帧中处理事件(使用 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()使程序崩溃 - 乐贴网