Python Event Timing, send stuff to the future!!

This forum is currently in read-only mode.
  • class EventTimer:

         iClock = 0 #incremented each frame

         Events = [] #[iTime, cCodeToExec]

         def AddEvent(self, iTime, cCodeToExec): #keep it neat, add events with this function

              self.Events.append([iTime,cCodeToExec])

         def CallEvents(self): #run once each frame

              for n in range(0, (len(self.Events))):

                   try:

                        if self.Events[n][0] <= self.iClock:

                                            

                             text1.text = self.Events[n][1] #i suggest trying it first to make messages not events

                             #exec self.Events[n][1] #Now this bit is YOUR job xD, exec can run strings as code

                                                     

                             del self.Events[n]

                   except:#when the del is called it reduces the list size, causing an exception, another thing is certain events can be missed until the next frame because of this

                        pass

                        

                        

    Events = EventTimer() #create a class, keep it neat!

    Events.AddEvent(200, "Hello") #here some examples, note this is just next, you could call functions in here and run with the exec

    Events.AddEvent(400, "There")

    Events.AddEvent(600, "Good")

    Events.AddEvent(800, "Sir")

    #In your game loop, I suggest every frame calling this

    Events.iClock += 1 #increment the clock

    Events.CallEvents()

    Hello, my first "tutorial", I hope you enjoy this little demo of how one would go about causing things to happen in the future in Python. Shock horror you may have added "import time" and found it freezes the game! What you need is an eventing system. Released under the do what the frak you like license.

    Now it's presented as a text messaging system because exec is a troublesome command, it's really up to you if you opt for this or some other solution. Me personally this is my first dynamically typed language so exec it makes me a bit uneasy but I am starting to see how epic it can be for scripting a game.

    A few words about the exception, the list shortens with the del command WHILE we are still in the for loop, now this is a little bit of bad practise but I code this way as it's more efficient. You may need to bear in mind some events could be missed on a cycle, they will get called next frame (notice the greater or equal than comparison)...I decided this was the best way for my stuff, something to ponder

  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)