• Jueves 20 de Febrero de 2025, 20:12

Mostrar Mensajes

Esta sección te permite ver todos los posts escritos por este usuario. Ten en cuenta que sólo puedes ver los posts escritos en zonas a las que tienes acceso en este momento.


Temas - warren

Páginas: [1]
1
C/C++ / Implementacion Maquina D Estados Finitos
« en: Miércoles 30 de Mayo de 2007, 15:09 »
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

2
C/C++ / Problema Reservando Array
« en: Viernes 9 de Marzo de 2007, 19:01 »
Hola,

Tengo un problema en un proyecto q estoy realizando.
El proyecto consiste en leer un fichero .bmp
Todo muy bien, la lectura y tal..
El problema viene al declarar una structura para almacenar los Pixeles:

Código: Text
  1. struct Pixel{
  2.  
  3.     int R,G,B;
  4. };
  5.  
  6.  

tmb declaro un array de esa estructura, el array bidimensional lo defino de tamaño 500x500

Pixel Data[MAXWIDTH][MAXHEIGHT];

pero al compilar el programa me peta al llegar (supongo) a la declaracion del array,
si pruebo con un tamaño menor q 500 funciona. Pero un dato mas importante, el proyecto lo estoy haciendo con el Code::Blocks, pero si pruebo el proyecto con el Dev-Cpp funciona perfectamente. Pero necesito hacerlo obligatoriamente con Code::Blocks.
El debugger no me da demasiada informacion, el backtrace me dice q la rotura se produce en la funcion probe(), q yo no defino, ni sé q es...

La verdad, no tengo ni idea de por q puede ser esto.
Alguien me puede ayudar??
Gracias por adelantado

3
C/C++ / Re: Libreria Qt En Dev-cpp
« en: Jueves 4 de Mayo de 2006, 18:06 »
hola,
gracias por vuestra atencion, ahi va mi problema:

Me he interesado por la libreria Qt para mis proyectos en Windows. Habituado a programar con el IDE de Bloodshed, el Dev-cpp, he decidido intentar configurarlo para mi mayor comodidad. No he tenido problema al linkar las librerias ni en compilaciones muy básicas, pero me ha surgido un problema al intentar crear mis propios Signals y Slots. El problema es q al crear mi propia clase donde definiré mis slots/signals debo poner en la cabecera de la declaracion Q_OBJECT, lo q me produce los siguientes errores de linkado:

SaveButton.cpp: undefined reference to `vtable for SaveButton'
SaveButton.cpp: undefined reference to `SaveButton::staticMetaObject

Buscando en la documentacion de las librerias me he encontrado con el Meta-Object System de Qt. Este sistema, segun entendi, mantiene las relaciones entre los signals y slots de una clase, por lo tanto cuando quiera crear mi propia clase con signals/slots definidos por mi tendre q someterla a este sistema mediante el MOC (Meta-Object Compiler).
Aqui es donde me he perdido del todo, mirando la documentacion no he comprendido la sintaxis del comando. Y lo q para mi es mas importante, no he visto manera de integrar el comando moc con mi Dev-cpp.
Esta es mi pregunta:
¿Puedo utilizar mi Dec-cpp directamente para compilar el codigo y los Meta-Objects a un mismo tiempo?
¿Como se utiliza el comando MOC?

Gracias por vuestras respuestas
Un Saludo!!

4
Programación de Videojuegos / Tutorial De Ia
« en: Jueves 16 de Septiembre de 2004, 00:33 »
Hola foreros

Quiero intentar adentrarme en el tema de la inteligencia artificial para mejorar la jugabilidad de mis demos. Pero solo he encontrado páginas relacionadas en inglés, ademas en español solo he encontrado articulos varios que tratan de manera muy general y teorica temas como algoritmos géneticos y redes neuronales . Yo buscaba algo mas particular y orientado a desarrollo de juegos.

Agradeceria si alguien conoce alguna buena página me la indicara.
De todos modos si alguien esta interesado y domina el ingles ahi van algunos links que he explorado:

http://generation5.org/
http://gameai.com


Un saludo

5
DirectX / Vertex Tweening
« en: Martes 20 de Julio de 2004, 03:52 »
hola a todos,
Soy nuevo en el foro y espero tanto poder ser ayudado como intentar ayudar a los demas con mi pequeña experiencia.

He estado buscando algun tutorial sobre como implementar animacion de personajes con la tecnica Vertex tweening en DX8.1 (ya que se suele comentar su facilidad en comparacion con Skinned Mesh).
Solo he encontrado documentacion  en ingles, lo cual se me atraganta bastante :( , por eso me gustaria saber si alguien conoce algun tutorial sobre el tema en español.
Me gustaria poder utilizarla con archivos .X ya que no se tratar el formato .md2

Sin nada mas que un saludo
Nos vemos!!!

Páginas: [1]