Sunday, July 19, 2009

.NET Reactive Framework

In our game, stories are first-class beings -  invisible meddlers. They move around, observe and manipulate the world according to their plot. They wait for triggering conditions or patterns of events to occur, and then spring to life to advance the story.

In our case, we have an evil story waiting for the betrayal of a paladin. When this happens, the story will unravel a series of events, involving a horror, a child's toy and a man with a poisoned name.

How does the story listen out for the betrayal? Our game follows an event-driven design so we'll need to do some event-processing.

I recently saw Erik Meijer's presentation on .NET's up and coming Reactive Framework (Rx), which looks pretty cool and the right tool for the job. There are already a couple of other reactive programming frameworks out there, like Continous LINQ and Reactive LINQ, but I thought it would be interesting to see what's involved in writing one, so here we go.

Rx is the mathematical inverse of IEnumerable, dubbed IObservable. So instead of being able to iterate over a stream of objects you get to listen to a stream of events.

No big deal really, but the cool thing is that it supports Linq, so you can query over event streams.

IObservable<ICombatCommand> paladinFleeCmds =
  from cmd in CombatMediator.CombatCommands
  where cmd.CommandType == CommandType.Flee &&
        cmd.Subject.CharacterType == CharacterType.Paladin
  select cmd;

paladinFleeCmds.Subscribe(cmd =>
    IStoryPoint betrayal = new Betrayal(cmd.Subject);

I'll post how to implement this kind of Linq-to-Events shortly.

No comments:

Post a Comment