Implementing state-machines in a turn based RPG

Posted on 03-09-2018

As mentioned in my Action Based RPG article I absolutely adore building RPG’s, which is probably a result of my love for the game Dofus. After I finished another project of mine I decided to finally give in to the urge and set out to recreate the combat system.

Entities can cast as many spells as their action points allow

Entities can cast as many spells as their action points allow

The initial draft was focused on creating a working prototype as fast as possible but this quickly turned in to a mess. Since entities can do a various amount of actions, each with their own requirements and special rules, the entity script became bloated and convoluted. I opted to refactor the game using state-machines, which allows each state to be concise and easy to read. Each state-machine is a state as well, which allows for nested behavior.

Besides the classic finite state-machine I also implemented a pushdown state-machine. This is useful for timed actions like moving to a certain tile or casting a spell. The pushdown state-machine automatically drops the current state once the bool isFinished is set to true, at which point the next state will be invoked. Once all states are done the pushdown state-machine sets the parent finite state-machine to the next state.

Example of the AI giving a list of actions to the pushdown state-machine

Example of the AI giving a list of actions to the pushdown state-machine

The state-machine submodule I wrote can be found here, keep it mind it has been specifically used for this project so I haven’t expanded on it as much as I’d like. I also have a code sample of how the AI picks actions, which can be found here.