Source code for examples.mousefollower.mousefollower
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Example usage of the symplehfsm statemachine for a game entity using pygame. See inline comments!
A statemachine has certain input it has to process. Depending on the current state and the kind of input, the
statemachine can might perform some actions whether it changes state or not. There are three types of actions:
entry, exit and transition action. The entry and exit actions are bound to a state and are executed whenever
that state is entered of left (also when an external self transition is done).
So to use sympleHFSM you will have to define the input and the actions it can perform. The input are just symbols that
are passed to the 'event_handle' method of the statemachine instance. This method will handle the input and perform
the corresponding actions. Therefore you need to pass in an instance of the actions class you want to use at
creation time of the statemachine instance (this way you can use different 'backends', especially for testing).
The second thing the statemachine instance needs to know is the structure. By structure I mean the number of states
that exists and their relationship between them. This is the parent-child relationship and of course the
transitions between them.
So lets go through the mousefollower example [2]_ from the examples in [1]_:
The mousefollower example has a pretty simple statemachine: just three states: idle, following and a parent state.
Best way to visualize and plan a statemachine is on paper, here is the drawing for the example:
::
+--------------------------------------------------------------------+
| parent |
init --->| update/following_update |
| +------------------+ |
| | | |
| +-----------------+ in_range/ +------------------+ | |
| *-->| idle |---------------->| following |<-+ |
| | /idle_entry | | /following_entry | |
| | | | | |
| | | out_of_range/ | | |
| | |<----------------| | |
exit <---| +-----------------+ +------------------+ |
| |
+--------------------------------------------------------------------+
Now I will describe the different sections of the example:
1. The input events are defined. The mouse follower has a sensor that give the event 'in_range' if the mouse is in
range. Otherwise it will generate an 'out_of_range' event. There is also the 'update' event because it should
behave differently depending in which state it is. In idle state it will just do nothing (there is no action
registered for that) and in the following state it should just follow the mouse position.
2. The actions the state machine can perform are defined. There are two entry actions defined and an update action.
The entry action for the idle state named as 'idle_entry' and entry action for the following state named
'following_entry'.
3. Points 1 and 2 just define the 'interfaces' of the state machine, what its input is and what actions
(sort of output) it will perform. Now in point 3 the structure and the transitions are defined. First
the states are added. The spaces before 'idle' and 'following' state identifier should indicate that they are
both children of the 'parent' state. The only state that has no parent is the root state (here called 'parent').
The initial flag is to determine which leaf state the state machine should change in case a transition ends in
a state that is not a leaf. So in this case if a transition would end at the 'parent' state then it would
change to the idle state. For each level there can only be one initial state. In those lines of code also
the entry actions are defined (explanation methodcaller seel [3]_). In the next three lines the transitions
are added. There are three transitions (this are the arrows in the picture). Only the self transitions in
the 'following' state for the update event has an action to call. Its the 'following_update' action. Now
the structure and the relationships are defined.
4. Here the actual actions for the entity are implemented. The 'following_update' action just does move the
entity in direction of the mouse. The other two actions are the entry actions for the two substates, they
just change the color of the entity.
5. Now here the state machine will be instantiated. The structure is passed in and the well an instance of
the actions pointing to that instance of the entity (so the action can manipulate the entity). To make
the state machine work, input events need to be passed to the state machine. This will happen in the
update method of the entity. There the proximity sensor will detect the mouse and then a corresponding
event (in_range or out_of_range) is generated and passed to the state machine. This might change the state,
depending in which state it is and what event it gets. Then the update event is also passed to the state
machine, because it should show a behavior (updating the position in direction of the mouse if in
state 'following').
I hope this made some things clear. There is much more to it. Take a look at the symplehfsm_demo [4]_ for a more
complex and full featured example. Run it in the console, preferably with the -O option:
::
>>>python -O symplehfsm_demo.py
I hope that helps.
.. rubric:: Footnotes
.. [1] https://bitbucket.org/dr0id/symplehfsm/src/d9229897f4e6/trunk/symplehfsm/examples
.. [2] https://bitbucket.org/dr0id/symplehfsm/src/d9229897f4e6/trunk/symplehfsm/examples/mousefollower/mousefollower.py
.. [3] its a convenient way to call dynamically a method by its name on an object, see
http://docs.python.org/library/operator.html?highlight=methodcaller#operator.methodcaller
.. [4] https://bitbucket.org/dr0id/symplehfsm/src/d9229897f4e6/trunk/symplehfsm/examples/TestHFSM/symplehfsm_demo.py
"""
__version__ = "1.0.3.0"
__author__ = "dr0iddr0id {at} gmail [dot] com (C) 2012"
import math
import pygame
from operator import methodcaller
import symplehfsm
from symplehfsm import Structure
from symplehfsm import SympleHFSM
from symplehfsm import BaseHFSMTests
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
### 1. define the events the statemachin understands
### here we have the range sensor output and the update defined as events
[docs]class Events(object):
in_range = 1
out_of_range = 2
update = 3
# ------------------------------------------------------------------------------
### 2. define the actions (the action methods like entry, exit, guard and action methods of the
### states and transitions) the statemachine can call
### here only in the following state has something to be done
[docs]class Actions(object):
[docs] def idle_entry(self):
pass
[docs] def following_entry(self):
pass
[docs] def following_update(self):
pass
# ------------------------------------------------------------------------------
### 3. define the structure of the statemachine, e.g. what states it has and what transitions between those states
### also define the entry, exit, guard and action method to call (only if needed)
structure = Structure()
# state, parent, initial, entry, exit
structure.add_state("parent", None, False) # all containing state
structure.add_state( "idle", "parent", True, methodcaller("idle_entry"))
structure.add_state( "following", "parent", False, methodcaller("following_entry"))
# handling state, event, next state, action, (guard,) name
structure.add_trans( "following", Events.update, "following", methodcaller("following_update"), name="following->following") # self transition
structure.add_trans( "following", Events.out_of_range, "idle", name="following->idle")
structure.add_trans( "idle", Events.in_range, "following", name="idle->following")
# for greater execution speed, apply when statemachine is stable and works as expected
# structure.do_optimize()
# ------------------------------------------------------------------------------
### 4. implement the real actions used, e.g. the entity behavior in each state
[docs]class EntityActions(object):
def __init__(self, entity):
self.entity = entity
[docs] def following_update(self):
mx, my = pygame.mouse.get_pos()
dx = mx - self.entity.x
dy = my - self.entity.y
dist = math.hypot(dx, dy)
if dist > 0:
dirx = dx / dist
diry = dy / dist
self.entity.x += dirx * self.entity.speed
self.entity.y += diry * self.entity.speed
[docs] def idle_entry(self):
self.entity.color = (255, 255, 0) # yellow
[docs] def following_entry(self):
self.entity.color = (255, 0, 0) # red
# ------------------------------------------------------------------------------
### 5. the entity that will use the state machine. It has also the proximity sensor code
### to generate the in_range/out_of_range events
[docs]class Entity(Actions):
def __init__(self, x, y):
self.x = x
self.y = y
self.radius = 100.0
self.speed = 1
self.sm = SympleHFSM(structure, EntityActions(self))
self.color = None
# self.mouse_in_range = False
self.blip_radius = (x * y) / (x + y)
self.sm.init()
[docs] def update(self, dt):
# # little caching, only send an event to statemachine if something actually changed
# in_range = self.proximity_sensor()
# if in_range != self.mouse_in_range:
# self.mouse_in_range = in_range
# if in_range:
# self.sm.handle_event(Events.in_range)
# else:
# self.sm.handle_event(Events.out_of_range)
# this code is without caching, just throwing an event at the state that gets ignored
if self.proximity_sensor():
self.sm.handle_event(Events.in_range)
else:
self.sm.handle_event(Events.out_of_range)
# update
self.sm.handle_event(Events.update)
# blip
self.blip_radius += 2
if self.blip_radius >= self.radius:
self.blip_radius = 1
[docs] def proximity_sensor(self):
mx, my = pygame.mouse.get_pos()
dx = self.x - mx
dy = self.y - my
dist = math.hypot(dx, dy)
if dist < self.radius:
return True
return False
[docs] def draw(self, surf):
pos = (int(self.x), int(self.y))
pygame.draw.circle(surf, (0, 100 * ( 1.0 - self.blip_radius / self.radius), 0), pos, int(self.blip_radius), 0)
pygame.draw.circle(surf, (0, 200, 0), pos, int(self.blip_radius), 1)
pygame.draw.circle(surf, self.color, pos, int(self.radius), 1)
pygame.draw.circle(surf, self.color, pos, 5, 0)
# ------------------------------------------------------------------------------
### little main loop
[docs]def main():
entities = [Entity(400, 300), Entity(500, 400), Entity(100, 300)]
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("mousefollower.py - move the mouse")
clock = pygame.time.Clock()
running = True
while running:
dt = clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
print(clock.get_fps())
elif event.key == pygame.K_ESCAPE:
running = False
for entity in entities:
entity.update(dt)
screen.fill((0, 0, 0))
for entity in entities:
entity.draw(screen)
pygame.display.flip()
# ------------------------------------------------------------------------------
if __name__ == '__main__':
main()