Panda3D Manual: Creating a Classic Finite State Machine
  <<prev top next>>  

Note: the ClassicFSM class is deprecated. We recommend new code should use the new FSM implementation instead. The following documentation is provided for historical reasons.

Finite state machines require importing two modules. After importing these modules, two functions must be created for each state of the machine. One is called when the machine moves into that state, and one is called when the machine moves out of the state. Then the finite state machine may then be created.

from direct.fsm import ClassicFSM
from direct.fsm import State

def my_Entrance_Function():
  ...

def my_Exit_Function():
  ...

myFSM = ClassicFSM.ClassicFSM('FSM name',
  [State.State('State Name',my_Entrance_Function,my_Exit_Function,
  ['Allowed State Transition'])],
  'Initial State','Final State')

It may be that each state has a very specific number of states it may transition to, which is why the allowed state transition argument is available. If this is not a concern, then the argument may be omitted. In this case, the state may transition to any state.

While the above is the general format, finite state machines are varied. An example of a traffic light as a finite state machine is below to help clarify.

from direct.fsm import ClassicFSM
from direct.fsm import State

#Entrance and Exit Functions
def enterRed():
  print ‘Entered Red’
def enterYellow():
  print ‘Entered Yellow’
def enterGreen():
  print ‘Entered Green’
def exitRed():
  print ‘Exited Red’
def exitYellow():
  print ‘Exited Yellow’
def exitGreen():
  print ‘Exited Green’


#Finite State Machine

fsmLight = ClassicFSM.ClassicFSM('stopLight',
  [ State.State('red', enterRed, exitRed, ['green']),
  State.State('yellow', enterYellow, exitYellow, ['red']),
  State.State('green', enterGreen, exitGreen, ['yellow']) ],
  'red',
  'red')

Each state of the light has its own entrance and exit function. The finite state machine has three states for each color, and each state is limited to what it may transition to. Finally, the red state has been designated as the initial and the final state. Whenever the finite state machine transitions, two lines will print: one for the state it is leaving and one for the state it is entering. Of course, these entrance and exit functions can do much more.

  <<prev top next>>