Using pygame.time.set_timer

℡╲_俬逩灬. 提交于 2020-02-02 14:08:45

问题


I am making a game in Pygame and Python, a form of Asteroids. Every 10 seconds, the game should make another asteroid if there isn't more than 10 on the screen at a time. As I was looking over the example code on how to implement it, I saw that I have to use USEREVENT in the code. Could I replace this with a function? For example:

    def testfunc():
      print "Test"

    pygame.time.set_timer(testfunc, 100)

If I can't use the function this way, how would I use the USEREVENT with this code?

Thanks

EDIT: Could the Python Timer object with Pygame instead of using the Pygame set_timer()? http://docs.python.org/2/library/threading.html#timer-objects


回答1:


Looking at the documentation, it seems that events are not functions, but numeric IDs representing the type of event. Thus, you want to declare your own event type, something like this:

SPAWNASTEROID = USEREVENT + 1

Then you can queue it up like this:

pygame.time.set_timer(SPAWNASTEROID, 100)

Finally add a handler to main loop, just like for button clicks and whatnot:

elif event.type == SPAWNASTEROID:
    if len(asteroids) < 10:
        asteroids.append(Asteroid())

EDIT (example code):

Custom event types declared

set_timer

Checking event type



来源:https://stackoverflow.com/questions/20318386/using-pygame-time-set-timer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!