• Domingo 15 de Diciembre de 2024, 00:42

Autor Tema:  Implementacion Maquina D Estados Finitos  (Leído 1011 veces)

warren

  • Nuevo Miembro
  • *
  • Mensajes: 10
    • Ver Perfil
Implementacion Maquina D Estados Finitos
« en: Miércoles 30 de Mayo de 2007, 15:09 »
0
Hola,
Necesito implementar una maquina de estados finitos para una aplicacion gráfica q estoy haciendo, entonces, buscando informacion sobre como llevarla a cabo, me he encontrado con varias propuestas. La mas sencilla es un bloque se seleccion swicht para controlar transiciones entre estados, pero es engorroso, dificil de mantener y aumentar.
Leyendo algunos documentos me he encontrado con esta seccion en el libro Programming game AI by example / by Mat Buckland., llamada State-Driven Agent Design donde describe una tecnica referida como Embedded Rules, por   la q se define una clase State q contiene la logica de transiciones de estados mientras q las acciones a realizar van dentro de la propia entidad. El metodo es sencillo y me parece q mas limpio q los tradicionales. Para q lo podais entender os pego la seccion:


Embedded Rules

An alternative approach is to embed the rules for the state transitions
  within the states themselves. Applying this concept to Robo-Kitty, the state
transition chip can be dispensed with and the rules moved directly into the
cartridges. For instance, the cartridge for “play with string” can monitor
the kitty’s level of hunger and instruct it to switch cartridges for the “eat
fish” cartridge when it senses hunger rising. In turn the “eat fish” cartridge
can monitor the kitten’s bowel and instruct it to switch to the “poo on carpet”
cartridge when it senses poo levels are running dangerously high.
Although each cartridge may be aware of the existence of any of the
other cartridges, each is a self-contained unit and not reliant on any external
logic to decide whether or not it should allow itself to be swapped for
an alternative. As a consequence, it’s a straightforward matter to add states
or even to swap the whole set of cartridges for a completely new set
(maybe ones that make little Kitty behave like a raptor). There’s no need to
take a screwdriver to the kitten’s head, only to a few of the cartridges
themselves.
Let’s take a look at how this approach is implemented within the context
of a video game. Just like Kitty’s cartridges, states are encapsulated as
objects and contain the logic required to facilitate state transitions. In addition,
all state objects share a common interface: a pure virtual class named
State. Here’s a version that provides a simple interface:
Código: Text
  1.  
  2. class State
  3. {
  4.     public:
  5.  
  6.     virtual void Execute (Troll* troll) = 0;
  7. };
  8.  
  9.  
Now imagine a Troll class that has member variables for attributes such as
health, anger, stamina, etc., and an interface allowing a client to query and
adjust those values. A Troll can be given the functionality of a finite state
machine by adding a pointer to an instance of a derived object of the State
class, and a method permitting a client to change the instance the pointer is
pointing to.
Código: Text
  1.  
  2. class Troll
  3. {
  4.        /* ATTRIBUTES OMITTED */
  5.        State* m_pCurrentState;
  6.  
  7.        public:
  8.        /* INTERFACE TO ATTRIBUTES OMITTED */
  9.       void Update()
  10.       {
  11.            m_pCurrentState->Execute(this);
  12.        }
  13.      
  14.       void ChangeState(const State* pNewState)
  15.       {
  16.         delete m_pCurrentState;
  17.         m_pCurrentState = pNewState;
  18.       }
  19. };
  20.  
When the Update method of a Troll is called, it in turn calls the Execute
method of the current state type with the this pointer. The current state
may then use the Troll interface to query its owner, to adjust its owner’s
attributes, or to effect a state transition. In other words, how a Troll
behaves when updated can be made completely dependent on the logic in
its current state. This is best illustrated with an example, so let’s create a
couple of states to enable a troll to run away from enemies when it feels
threatened and to sleep when it feels safe.

Código: Text
  1.  
  2. //----------------------------------State_RunAway
  3. class State_RunAway : public State
  4. {
  5.       public:
  6.       void Execute(Troll* troll)
  7.       {
  8.           if (troll->isSafe())
  9.           {
  10.                 troll->ChangeState(new State_Sleep());
  11.           }
  12.           else
  13.          {
  14.                 troll->MoveAwayFromEnemy();
  15.          }
  16.       }
  17. };
  18.  
  19.  
  20.  
  21. //----------------------------------State_Sleep
  22. class State_Sleep : public State
  23. {
  24.     public:
  25.     void Execute(Troll* troll)
  26.     {
  27.         if (troll->isThreatened())
  28.        {
  29.            troll->ChangeState(new State_RunAway())
  30.        }
  31.        else
  32.        {
  33.          troll->Snore();
  34.        }
  35.     }
  36. };
  37.  
As you can see, when updated, a troll will behave differently depending on
which of the states m_pCurrentState points to. Both states are encapsulated
as objects and both provide the rules effecting state transition. All very neat
and tidy.
This architecture is known as the state design pattern and provides an
elegant way of implementing state-driven behavior. Although this is a
departure from the mathematical formalization of an FSM, it is intuitive,
simple to code, and easily extensible. It also makes it extremely easy to add
enter and exit actions to each state; all you have to do is create Enter and
Exit methods and adjust the agent’s ChangeState method accordingly.
You’ll see the code that does exactly this very shortly.[/i]


Bien, el metodo se comprende perfectamente, y tiene como ventajas que las transiciones llaman directamente por el Objeto ( troll->MoveAwayFromEnemy() ) independientemente de las relaciones entre estados o de la propia naturaleza del objeto.
El Problema con el q me encuentro, es q en el codigo anterior se realiza una dependencia circular de declaraciones, si se declara primero la clase Troll no se reconoce el miembro State* m_pCurrentState y si primero se declara la clase State no se reconoce ninguna clase Troll en virtual void Execute (Troll* troll) = 0.
Como resolver este problema de dependencias?? un fallo de este tipo puede indicar una mala planificacion, pero es la propia naturaleza de esta solucion la que plantea el dilema.

Gracias por adelantado
y perdon por este post tan larrrrgo :s