开发者

Handling Events in a State Machine

I have a state machine for my npcs that is structured like the following,

execute state
[[[pred1 pred2....] state1]
 [[pred3 pred开发者_如何学Go4....] state2]
 [[pred5 pred6....] staten]]

What happens is after current state completes, it starts iterating through the states/predicates list and as soon as a list of predicates that returns all true it will jump to the state that it is associated with.

Certain events can happen during all states, say player commands npc to go somewhere. Just like any other state transition I can check for a predicate and change state but adding the same piece of code to every state seems a bit lame. So I was wondering how people deal with events in state machines?


Just make a data structure like:

state1 -> event1, event2
state2 -> event1
state3 -> event2, event3

By the way, what you have outlined doesn't look like a state machine. In state machine, next state depends on the previous one, so it would look like:

[state1, condition1] -> state2
[state1, condition2] -> state3
...

(condition is your set of predicates). You must also somehow assure that the transition is unique, i.e. that condition1 and condition2 cannot be fulfilled at the same time. Or take the first one which is true.


Try to use pattern called "State" - http://en.wikipedia.org/wiki/State_pattern

Define abstract superclass (e.g. class AbsatractState, put there code of methods that common for all states), and all classes that represents real states must been subclassed from it.


When you have a particular action that can be undertaken from all possible states, do as you would do in mathematics : factor it!

i.e : 4*10 + 5*10 + 6*10 + 4*20 + 5*20 + 6*20 = (4+5+6)*(10+20)

i.e : your (oblivion) npc can be sleeping, or at work, or eating. In all three cases, it must react to some events (be talked to, be attacked, ...). Build two FSM : Daily activity = [sleep, work, eat]. Reaction state : {Undisturbed, Talked to, Attacked, ...}. Then forward the events only to the second FSM

And you can keep on factoring FSM, as long as you're factoring independant things. For example, the mood of the npc (happy, neutral, angry, ...) is independant from it's daily activity and its reaction state. I mean "independant" in the sense "the npc can be at work, talked to, and angry, and there's no contradiction". Of course FSM influence each other, npc that are attacked tend to be angry.

So you could add a third FSM for the Mood state, instead of incorporating it in every single node


Use a hierarchical state machine (HSM). HSMs are exactly designed to factor out the common behavior into superstates and make it reusable for all substates. To learn more about HSMs, you can start with the Wikipedia article "UML State Machine" at http://en.wikipedia.org/wiki/UML_state_machine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜