State machine and enterFrame

Hi,

I’m new to AS/Flash but have an old-school background (C, assembler…).

First, if you’re writing a simple game and have a state machine that is called every frame to handle attract mode, gameplay, game over states etc., does the AS/pseudocode code below basically make sense in the AS world? I’ve read a little of Jeff Fulton and others that talk about FSMs and function-reference state machines, but it would be good to get some comment from people here.

Second, if the initgame() function is part of the state machine, it has to complete within one frame, else will get called again before it’s finished. But initgame functions can be lengthy - setting up graphics, initiating landscapes, maybe doing procedural generation, etc. By their nature they’re called once as needed, not every frame, and are framerate-independent. But if they’re part of the state machine, they’re tied to the framerate. How to handle that basic dichotomy? How is it possible to perform the initgame() function outside the framerate-bound state machine, or else to guarantee that the enterFrame event won’t trigger re-entrance?


public function Main():void {
   public var state:int=1;
   initprogram();
   addEventListener(Event.ENTER_FRAME,onEnterFrame);
}

public function onEnterFrame(e:Event):void {
   switch (state) {
      case 1: attractmode();
      case 2: initgame();
      case 3: playgame();
      case 4: gameover();
}

public function attractmode():void {
   print("press a key to start");
   if (keypressed()) state=2;
}

public function initgame():void {
   for (i=0;i<twenty trillion;i++) {
      do hard, slow sums;
   }
   state=3;
}