January 14, 2008

More about the Event Scheduler

In addition to the classic "main loop", the game will have an event scheduler. This is a queue for function calls. You pass it a command and the number of seconds from now in which to run it. This can be 1 / 1000 of second or years. Let's say you wanted to give a room some character by telling the players something like "You hear the scurrying of rats deep within the walls." Now, you don't want it to print every time someone enters or it seems canned and loses all effect. So you could do something like
event_scheduler.add(600, say_ambient, "You hear the scurrying of rats deep within the walls.")

So now the message will play in exactly 10 minutes. To make it even better, let's do this:
def the_rats():
say_ambient("You hear the scurrying of rats deep within the walls.")
offset = random.randrange(600,1200)
event_scheduler.add(offset, the_rats)

We just made a function that, once called, continues to re-schedule itself forever in random intervals between 10 to 20 minutes apart -- and the best part is we can forget all about it.

Let's say we wanted to implement a four-hour game-day. We could write functions for noon(), dusk(), midnight(), and dawn() which did things like sent farmers to the fields and turned vampires to dust in the sunlight. Each one of these would re-schedule itself, just like the_rats() did, but with a four hour delay (14,400 seconds). So in our start up code we do something like:
# Call noon right now
noon()

# call dusk() in 1 hour
event_scheduler.add(3600, dusk)

# call midnight() in 2 hours
event_scheduler.add(7260, midnight)

# call dawn() in 3 hours
event_scheduler.add(10860, dawn)
And our world begins to spin.

An even more efficient version would have each daily event schedule the next one to fire in one hour, round-robin style.

No comments: