4

I'm currently writing an IRC bot in Ruby to play some kind of strategy game (it doesn't matter which), but I'm hesitating between several solutions to implement a phases system the "best" way.

The system: The game has several days; the first day some phases occur to give the players their jobs and so on, but they never occur again, so phases are sometimes conditional.

What's more, when a certain condition is met, e.g. an important player dies, a phase may be started before the next one. Phases may be added by the job system; jobs are each defined in a single file and they can define their own phases and logic.

My ideas:

  • The game is handled by a class in which I can store an instance variable to remember the actual phase and handle all of the logic in the code. I don't think this is the best idea.
  • Use a phases hash to store the next phase and other parameters and methods to handle each change.

Is there a better way? I don't think those I came up with are very flexible.

Cydonia7
  • 141
  • 2

1 Answers1

7

To expand on my comment, this is pretty much the perfect situation to use a Finite State Machine. You've got a set of different phases based on certain conditions, and each phase is handled in a different manner (at least, I'm assuming as much based on your description). The fact that some phases only occur once shouldn't make a huge difference. Switching between phases is easily handled, simply by changing the state. Each state handles one phase, and code is separated into nicely defined classes (or functions, if you implement it that way...)

The only possible downside is, for the most part, you can only have one state active at once. It's also tricky (but not impossible) to dynamically add newly defined states, though it's entirely possible to switch between defined states (heck, it's designed for it).

I'm not familiar enough with Ruby to know exactly how to implement a FSM, but it should be easy with any language that supports polymorphism.

thedaian
  • 4,491
  • 1
  • 24
  • 24
  • 1
    So, for example, one of your states would test if it's the first day and then move on to those special states, else it would move onto... whatever else. –  Oct 07 '11 at 16:20