Tuesday 17 April 2012

Game States Part 2

The reason the last couple of posts interrupted the addition of game states was to make some of the code more portable.

We have now made the selection variables global so that the parts of the program that use them can be moved out of the main loop and into functions.

Remember variables used in functions are local to that function, unless declared as global, and the same is true of the main loop.

If you do a quick scan of the code now, you will see that only two variables remain that are not global.
  • imageRef - which holds the finger image reference
  • spriteRef - which holds the finger sprite reference
These are not intended for the finished project so can stay that way.

Everything else can now be moved around to suite our needs without causing any problems.  Hopefully.

The pointer position is recorded by the loopStart() function, it is only the handling of the results that remain in the main loop.

As this portion of code will only be used when a game is under way, it needs to be moved into the block of code which deals with that game state.

To do this we move the entire block, from if getPointerPressed() > 0 to just before setSpritePosition( spriteRef , PointDX() , PointDY() ), into a new function checkGamePointer().

Then add a line just after // Running Code, which calls this function.

Now move all the print statements from printc( "Phy: " ... down to just before the sync() command, into a new function PrintDiagnostics().

Then put in their place a line which calls this function.

This will leave the main block looking like this.
// Main Loop
do
   LoopStart()
   select GameState()
      case STATE_SETUP
         // Setup Code
      endcase
      case STATE_INTRO
         // Intro Code
      endcase
      case STATE_DEMO
         // Demo Code
      endcase
      case STATE_MENU
         // Menu Code
      endcase
      case STATE_RUNNING
         // Running Code
         checkGamePointer()
      endcase
   endselect

   setSpritePosition( spriteRef , PointDX() , PointDY() )

   PrintDiagnostics()
   sync()
loop
Which is pretty compact.  Now the Game will run as before, printing the information showing the screen size and pointer position, however clicking on the Objects word at the bottom will have no effect.

This is because the game state is set so that the game is not processing the pointer.

To test is still works ok, we add the following line just after //Setup Code in the STATE_SETUP block of the select structure.
setGameState( STATE_RUNNING )
This changes the game state to STATE_RUNNING so that the pointer will respond again.

2 comments: