所以我正在关注 this tutorial
下面是我到目前为止的代码
import pygame
import time
pygame.init()
display_width = 800
display_height = 600
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
car_width = 73
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('A bit Racey')
clock = pygame.time.Clock()
carImg = pygame.image.load('racecar.png')
def car(x, y):
gameDisplay.blit(carImg, (x, y))
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf', 115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width / 2), (display_height / 2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def crash():
message_display('You Crashed')
def game_loop():
x = (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
if event.key == pygame.K_RIGHT:
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
x += x_change
gameDisplay.fill(white)
car(x, y)
if x > display_width - car_width or x < 0:
crash()
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()
这是给我带来麻烦的一点:
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf', 115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width / 2), (display_height / 2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
对了,“你崩溃了!”当汽车超出屏幕边界时,消息应该显示 2 秒,然后重新启动游戏。然而,汽车等待了 2 秒钟才出现该消息。因此,消息不会显示 2 秒,而是屏幕会在消息出现之前暂停 2 秒。在游戏重新开始之前,该消息仅闪烁一瞬间。看起来 Python 在我的 pygame.display.update 代码之前运行 time.sleep 函数。
我在这里做错了什么?我的 time.sleep 明显低于我的显示更新,因此不应该稍后执行吗?
最佳答案
也许该消息是在执行game_loop()
之后出现的,该函数中也有一个pygame.display.update()
。
API 执行的顺序可能是异步。
关于Python time.sleep() 问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53910319/