سؤال

So in a game I'm creating when the player picks up the speed boost sprite I want the players speed to periodically boosted for around five seconds, could someone help me understand how to do this? The 'Handle Caught' method will contain the code for the speed boost, the actual speed of the player is also set as a global variable 'speed' which is equal to 2. Thank you in advance

class Addspeed(games.Sprite):
    image = games.load_image('addspeed.png')
    speed = 2

    def __init__(self,x,y = 10):
        super(Addspeed, self).__init__(image = Addspeed.image,
                                       x = x, y = y,
                                       dy = Addspeed.speed)
    def update(self):
        if self.bottom>games.screen.height:
            self.destroy()

    def handle_caught(self):
        global speed
هل كانت مفيدة؟

المحلول

If your game is big enough, I would suggest a timer manager. Have one big timer based on the pygame.Clock. Create methods, to register time and methods to be called when the time passes. So something like:

timerMananger.register(self.myMethod,5000) 
# registers an event to be called after 5 seconds

The manager should encompass the Clock, as well as have a priority queue of tasks to complete. A short sketch of how this would look like:

def register(myMethod,t):
    pqueue.add(myMethod,time_now+t)

def tick():
    clock.tick()
    if(time_now > pqueue[0]):
        pqueue.pop()[0]()

This way you only check the most recent event. You could change the if to a while loop, if there will be many events, so that they will be all processed at once.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top