Python游戏计时器(线程?) [英] Python Game Timer (Threads?)

查看:626
本文介绍了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.

注意:我正在使用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)

但是,当在我的主要游戏功能中运行时,由于timer.sleep,我的游戏挂起了.

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

def main(self):
    Timer.start_timer()

我很确定我的问题与不使用线程有关,尽管我不确定100%.有人可以帮我解释什么是正确的解决方案吗?

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?

推荐答案

如果您使用的是PyGame,则它具有自己的

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

如果您使用的是事件循环或混合设计,则在pygame.event.get()或类似内容上循环并针对诸如鼠标单击或按下鼠标键之类的不同事件调用事件处理程序",则可以使用 set_timer 创建一个每秒触发的事件.例如:

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()

每个函数的文档中都链接有非常简单的示例程序;如果您查看set_timer的示例,将会发现它的使用非常简单.

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.

如果您使用的是纯框架循环,则可能已经调用了 Clock.tick 或类似的东西,您将不得不使用返回值来倒数自上次以来的毫秒数,并确定您是否又经过了整数秒和当您通过0时.

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.

这篇关于Python游戏计时器(线程?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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