简体   繁体   English

我如何实时更新pygame中的时间

[英]How do i update time in pygame in real time

I am trying to display how long the game has been running for in real time.我正在尝试实时显示游戏运行了多长时间。 To do this, i have used self.time_passed = pygame.time.get_ticks()/1000 and called it as g.write("Time: %d" %(g.time_passed), g.white ,10, 10, 50) .为此,我使用了self.time_passed = pygame.time.get_ticks()/1000并将其称为g.write("Time: %d" %(g.time_passed), g.white ,10, 10, 50) My write function looks like this:我的写函数如下所示:

def write(self, text, color, x , y, size):
            font = pygame.font.SysFont("airel", size)
            text = font.render(text, True, color)
            textRect = text.get_rect()
            self.screen.blit(text,(x , y))

My probelm is that the time is not updated in real time.我的问题是时间不是实时更新的。 It only updates the number of seconds everytime the player dies, even though i placed g.write("Time: %d" %(g.time_passed), g.white ,10, 10, 50) inside my main while True: game loop.它只会在玩家死亡时更新秒数,即使我将g.write("Time: %d" %(g.time_passed), g.white ,10, 10, 50)放在我的 main while True: game环形。 Thanks for help.感谢帮助。

I guess it is because the system font is called Arial and not airel .我想这是因为系统字体被称为Arial而不是airel Or maybe you are using the font Aerial ?或者,也许您正在使用字体Aerial

This probably causes this funcion to fail and the one called when the player dies works fine.这可能会导致此功能失败,而在玩家死亡时调用的功能可以正常工作。

Personally I would use time.time()我个人会使用 time.time()

import time

start = time.time()

# your code

end = time.time()
duration = end - start # answer in seconds
print(duration)

Also you might want to just declare the font once like this:此外,您可能只想像这样声明一次字体:

import pygame

pygame.init()

font18 = pygame.font.SysFont("ariel", 18)

displaysurf = pygame.display.init((1280, 720))

def write(f, t, x, y, c):
    textsurf = f.render(t, True, c)
    displaysurf.blit(textsurf, (x, y)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM