python - 为什么在 Pygame 中clock.tick() 不能准确测量时间?
问题描述
我在 Pygame 中创建了一个简单的游戏,它在 x 时间内显示某种情绪的图像,然后让参与者有机会通过按下按钮来选择显示哪种情绪。但是,我无法维持图像的显示时间。我使用 clock.tick() 来获取增量时间的值,但它似乎比它应该慢了 3 倍。例如,如果我将计时器设置为 1000 毫秒,则图像显示约 3 秒,而我只希望它显示 1 秒。我总是可以将显示时间除以 3 以使其大致正确,但我想了解是什么原因造成的。这是主要的游戏循环:
def mainGame(images):
dt = 0 #delta time is set to 0 to begin
timer = displayTime #displayTime by default is 1000ms
imageNumber = 0
gameState = States.VIEWING #this is the game state where a participant views a question
running = True
while running:
mouse = pygame.mouse.get_pos()
screen.fill((255, 255, 255))
mainDisplay() #this displays the answer buttons
clock = pygame.time.Clock()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
if ( gameState == States.VIEWING):
dt = clock.tick_busy_loop(30) #should increase delta time by however many ms have passed
timer -= dt #minus delta time from the timer
if timer >= 0: #if the timer remains above 0, continue displaying image
askQuestion(images, imageNumber)
else: #when timer reaches 0, stop displaying image and move to answering state
gameState = States.ANSWERING
elif (gameState == States.ANSWERING): #this is where participants select their answer
timer = displayTime #reset the timer
screen.fill((255, 255, 255))
mainDisplay() #displays answer buttons
for emotion, rects in rectDict.items(): #this detects whether a button has been clicked or not
if event.type == pygame.MOUSEBUTTONDOWN:
if rects.collidepoint(mouse): #if a button is clicked
gameState = States.VIEWING #switch back to viewing state
answers.append(emotion) #add answer to answer list
imageNumber += 1 #move to the next image
elif not any(rect.collidepoint(mouse) for rect in rectList): #if a button is not clicked
print("You did not select an answer")
break
if practice == True: #if in practice mood, stop when number of practice questions is reached
if len(answers) == pnumberofQuestions:
break
elif practice == False: #if in main game loop, stop when number of questions is reached
if len(answers) == numberofQuestions:
break
pygame.display.update()
解决方案
每次通过while
循环时,您都在创建一个新时钟。
移动
clock = pygame.time.Clock()
从你的
while running:
并把它放在它上面的某个地方。
推荐阅读
- javascript - JsPDF canvas to pdf加速生成速度
- javascript - 如何删除具有动态标题名称的 HTML 列
- database - 在 CouchDB 中查找树的块指针
- javascript - 这种解构有什么问题?[['h1', 'text'].forEach( (case: [Component, assertion]) => { console.log(Component,assertion); });
- javascript - 从 FastAPI 获取文件时如何使用浏览器缓存?
- python - Pandas 在不同列上返回具有条件行 statemnet 的列的值
- c# - ERR_SSL_VERSION_OR_CIPHER_MISMATCH 在 Raspberry PI 上访问我的 asp.net Web api 时
- android-jetpack-navigation - 为什么导航可组合调用两次?
- bash - 未解析 Bash 脚本参数
- python - 我的 Python 程序因“致命的 Python 错误:取消分配无”而崩溃。这个错误是什么意思?