python定时器毫秒_Python游戏计时器(线程?)

I am designing a game in Python and would like to know how to make an efficient timer that can run along side my game.

Note: I am using Pygame.

I currently have a timer like so:

import time

seconds = 60

def start_timer():

global seconds

while seconds > 0:

print seconds

seconds -= 1

time.sleep(1)

However, when run in my main game function my game hangs because of the timer.sleep.

def main(self):

Timer.start_timer()

I'm pretty sure my issue has something to do with not using threading, although I'm not 100% sure. Can somebody help explain to me what the proper solution is?

解决方案

If you're using PyGame, it has its own time functionality that you should be using.

If you're using an event-loop or hybrid design, where you loop over pygame.event.get() or similar and call "event handlers" for different events like mouse-click or key-down, you can use set_timer to create an event that fires every second. For example:

TIMER1_EVENT = pygame.USEREVENT + 1

def start_timer1():

global seconds

seconds = 60

pygame.time.set_timer(TIMER1_EVENT, 1000)

def on_timer1():

global seconds

print seconds

seconds -= 1

if seconds < 0:

pygame.time.set_timer(TIMER1_EVENT, 0)

# elsewhere, inside your main event loop

elif event.type == TIMER1_EVENT:

on_timer1()

There are very simple example programs linked in the docs for each function; if you look at the examples for set_timer you'll see how easy it is to use.

If you're using a pure frame loop instead, you're presumably already calling Clock.tick or similar, and you're going to have to use the return value from that to count down milliseconds since the last time and decide whether you've passed another integral number of seconds and when you're passed 0.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值