home *** CD-ROM | disk | FTP | other *** search
/ AI Game Programming Wisdom / AIGameProgrammingWisdom.iso / SourceCode / 06 General Architectures / 05 Rabin / statemch.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2001-12-10  |  1.3 KB  |  65 lines

  1. /* Copyright (C) Steve Rabin, 2001. 
  2.  * All rights reserved worldwide.
  3.  *
  4.  * This software is provided "as is" without express or implied
  5.  * warranties. You may freely copy and compile this source into
  6.  * applications you distribute provided that the copyright text
  7.  * below is included in the resulting source code, for example:
  8.  * "Portions Copyright (C) Steve Rabin, 2001"
  9.  */
  10.  
  11. #include "statemch.h"
  12.  
  13.  
  14.  
  15. StateMachine::StateMachine( void )
  16. {
  17.     m_currentState = 0;
  18.     m_stateChange = false;
  19.     m_nextState = false;
  20. }
  21.  
  22.  
  23. void StateMachine::Initialize( void )
  24. {
  25.     Process( EVENT_Enter );
  26. }
  27.  
  28.  
  29. void StateMachine::Update( void )
  30. {
  31.     Process( EVENT_Update );
  32. }
  33.  
  34.  
  35. void StateMachine::Process( StateMachineEvent event )
  36. {
  37.     States( event, m_currentState );
  38.  
  39.     // Check for a state change
  40.     int safetyCount = 10;
  41.     while( m_stateChange && (--safetyCount >= 0) )
  42.     {
  43.         assert( safetyCount > 0 && "StateMachine::Process - States are flip-flopping in an infinite loop." );
  44.  
  45.         m_stateChange = false;
  46.  
  47.         // Let the last state clean-up
  48.         States( EVENT_Exit, m_currentState );
  49.  
  50.         // Set the new state
  51.         m_currentState = m_nextState;
  52.  
  53.         // Let the new state initialize
  54.         States( EVENT_Enter, m_currentState );
  55.     }
  56.  
  57. }
  58.  
  59.  
  60. void StateMachine::SetState( unsigned int newState )
  61. {
  62.     m_stateChange = true;
  63.     m_nextState = newState;
  64. }
  65.