如何在不冻结整个代码的情况下在 python 中制作计时器 [英] How to make a timer in python without freezing up the entire code

查看:53
本文介绍了如何在不冻结整个代码的情况下在 python 中制作计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Pygame 编写 Mario 代码,我现在正在编写代码块.我想制作一个计时器,所以当我在一秒钟后击中方块时,方块会回到其原始位置以制作击球动画.问题是当让计时器带睡眠时,它会在计时器的持续时间内冻结整个游戏.我需要运行代码,并在一秒钟后启动前一个代码块.

I am coding Mario using Pygame and I'm coding the blocks right now. I want to make a timer so when I hit the block after a second the block goes back to its original position to make the hitting animation. The problem is when making the timer with sleep it freezer the entire game for the duration of the timer. I need the code to run and after a second that previous block of code to kick in.

我曾尝试使用睡眠来制作计时器,但它冻结了整个游戏.任何人都可以给我一些知识吗?谢谢!

I have tried using sleep to make the timer but it freezes the entire game. can anyone drop me some knowledge? Thanks!

推荐答案

我建议你使用 threading 模块和线程两个函数.

I would suggest you use the threading module and thread two functions.

最后,你可以这样格式化:

At the end, you can format as such:

from threading import Thread
if __name__ == '__main__':
    Thread(target = game()).start()
    Thread(target = timer()).start()

另一个选项是 timeit 模块.您可以设置一个计时器并检查何时使用 if/while 语句达到特定时间.

Another option is the timeit module. You can set a timer and check when a certain time is hit with a if/while statement.

第三个选项是您用于睡眠的时间模块:

A third option is with the time module you used for sleep:

import time

max_time = #the time you want
start_time = time.time()
while (time.time() - start_time) < max_time:
    game()

这篇关于如何在不冻结整个代码的情况下在 python 中制作计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆