问题
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