Not logged inGosu Forums
Forum back to Help Search Register Login
Up Topic Gosu / Gosu Exchange / A State Pattern implementation
- By banister Date 2009-06-13 00:16
Introducing Stateology, an implementation of the State Pattern using the Mixology C extension.

Use it like the following:

    class Sample
        include Stateology
        state(:Happy) {
            def do_something
                puts "Pets a puppy"
        state(:Angry) {
            def do_something
                puts "Kicks a puppy"

    s =

    # switch to Happy state
    s.state :Happy
    s.do_something  #=> "Pets a puppy"

    # now switch to Angry state
    s.state :Angry
    s.do_something  #=> "Kicks a puppy"

The State Pattern is quite useful in game-dev where you may want different behaviours depending on whether the Player is Running, Jumping, Sleeping, etc

* Stateology is different to other implementations in that it works by dynamically mixing and unmixing modules from the target class.

* How to get Stateology: gem install stateology

* Note that stateology requires the mixology extension to work. The stateology gem will try to install the mixology gem itself and should work fine out of the box with ruby 1.8.6.

* However I am unsure whether the mixology maintainer applied my 1.9.1 patch to the mixology source - if you are trying to use Stateology with ruby 1.9.1 and encountering troubles
go here to get the 1.9.1 compatible version of mixology:
- By Maverick Date 2009-06-13 00:26
s.state :Chinese
s.do_something #=> "Cook and eat a puppy"

Cool idea but couldn't just as easily do this?:

def do_something
     if @state == "Happy"
          puts "Pets a puppy"
     elseif @state == "Angry"
          puts "Kicks a puppy"
          puts "Stares dumbfounded at puppy"
- By banister Date 2009-06-13 00:31
of course you could :) but that's potentially alot of boiler-plate esp. if you have many methods that all change behaviour depending on the state. I guess it's up to each person and their own situation; but i've found using it makes my code both easier to read and maintain :)
- By jlnr (dev) Date 2009-06-13 00:37
Hmmm, this sounds nice. Might even work well for the main window if there are very few/simple states the actual game app can be in, hehe :) Why not obj.state = :foo though?

How does it work with instance variables?
- By banister Date 2009-06-13 00:47
ivars work fine, since a 'state' is really just a module that is dynamically included upon transition (and, more complicatedly, unincluded upon transition out of that state). 
Up Topic Gosu / Gosu Exchange / A State Pattern implementation

Powered by mwForum 2.29.7 © 1999-2015 Markus Wichitill