在我的游戏中,我有一个计时器正在运行。计时器是在“Play”类中定义的(用于与玩家控制角色相关的所有内容),而不是在“Victory”类中(目的是在您通过关卡时显示图像)。这两个类都在 main.py 文件中定义。我想在最终胜利屏幕上打印(当角色到达确定位置时玩家获胜)玩家到达该位置所花费的时间。我该怎么做?谢谢。不幸的是,我无法显示代码。
问问题
73 次
1 回答
2
我编写了一小段代码,可以帮助您构建这个计时器。
import pygame
pygame.init() # init is important there because it starts the timer
screen = pygame.display.set_mode((500, 500))
running = True
victory = False
class Play:
def __init__(self):
# all infos about player
self.time = pygame.time.get_ticks()
self.end_time = 0
def update_timer(self):
# here we get the actual time after 'init' has been executed
self.time = pygame.time.get_ticks()
# we divide it by 1000 because we want seconds instead of ms
self.end_time += self.time / 1000
return self.end_time
class Victory:
def __init__(self):
self.play = Play()
def pin_up_timer(self):
# Here I chose to print it inside of the console but feel free to pin it up wherever you want.
print(self.play.update_timer())
vic = Victory()
pl = Play()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# here I chose to end the game when I press KeyUp but you can do something else to stop it
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
victory = True
# I update timer every frame and BEFORE checking if victory is True in order to get a result more accurate
pl.update_timer()
# if victory is True, I pin up the timer and I end the code
if victory:
vic.pin_up_timer()
running = False
pygame.display.flip()
pygame.quit()
如果您希望仅在玩家移动时才开始计时器,请检测键并添加如下变量:
# (this variable outside of the main loop)
moved = False
# left or anything else
if event.key == pygame.K_LEFT:
moved = True
if moved:
pl.update_timer()
于 2020-12-24T14:18:32.863 回答