ebmDevMag.com home
ebm Developer's Magazine
links

developer's mag
main page

article
part 1
part 2
part 3
part 4
part 5
part 6
part 7


3 - Working With States

That last item requires more explanation. By writing a game (or any program) as a state machine, code can be simplified. For instance, the m_state variable can be either STATE_GAME_OVER or STATE_GAME_BEGIN in this game, making it a single test to determine whether a game is running or not. In a simple game like Tic-Tac-Toe, the only test actually used is when handling pen messages (ignoring them when a game is over), but the state idea can be expanded for more complicated programs.

A more important reason to use a state variable in your code is that your functions become more detached from program flow. In a typical DOS program, a program might call a loop from time to time to monitor the computer (check for key or mouse presses, etc.). In many Window operating systems, including the ebm, you never write these time-consuming loops. Instead, the operating system monitors hardware and software events, and calls you when it has something of interest to your program (in effect, the loop you would call to check on the computer now calls you!) As an example, in DOS you would repeatedly call a function to check for key presses (called polling the keyboard). On the ebm, you poll nothing, but your program remains in limbo until your MsgHandler() function is called with a MSG_KEY message, indicating the ebm has a keystroke for your program.

If you're making the transition to message-based programming like this, using a state variable can be quite handy to simplify things. For instance, at any given time, our Tic-Tac-Toe message loop is likely to receive a pen press to choose an X or O position, a menu request to display itself, a menu selection to quit or start a new game, and many more messages we don't need to explicitly handle, as the window takes care of them for us (such as drawing, which invokes our Draw() function automatically without our intervention). A state variable lets you restrict messages: in our game, the WM_PEN_DOWN message is ignored if the game is over, while in another game you might want to restrict access to certain parts of the program during play.

Again, while Tic-Tac-Toe requires little in the way of state information, I've added it to show how it can be used, since I recommend it for your projects. Simple put, define your states in an enum somewhere, and create a variable that uses it:
  enum e_state
  {
    STATE_GAME_START,
    STATE_GAME_OVER,
  } m_state;
Set the variable immediately to a known value, and test as necessary to prevent unwanted interactions.

Previous Section
Next Section

Copyright © 2001-2006 ebmDevMag.com - Legal Notice