Simple game state management / switching
Simple state manager
This demo shows how to create and manage really simple game state switcher.
It works by changing a global variable
state that points to any one of a number of
object .. end state blocks.
Each state block is setup up with these functions:
init() go() update() draw()
By changing the global
state variable it is easy to switch to any other state during runtime.
Here is a visual overview of the basics behind the program flow/state switching.
In this first set up the 'state' is set to point to the titlepage object. During the main loop the titepages
draw() are called.
Now, according to the code here, when SPACEBAR is pressed the 'state' is set to point to the game object.
From now on, during the main loop the games
draw() are now called.
In this demo a state block is switched via:
newstate is the name of state block that you want to take control of.
SwitchState(titlepage) // switch to the titlepage state SwitchState(maingame) // swith to the maingame state
When a state is switched via the above function its
go() function is also called.
This makes it easier to manage what you want to do whenever a state is revisited again.
Such as reset sprites, variables, and so on ..
The main game is typically set up like this. Note how all states are initiallized at the start
init = function() titlepage.init() // initialize the titlepage state block maingame.init() // initialize the maingame state block // .. Contine initializing all remaing state blocks state=titlepage // set state to one of the blocks end update = function() state.update() // Call update() function in the active state() end draw = function() state.draw() // Call draw() function in the active state() end
Let's suppose the active state is the titlepage code block.
update() loop you can switch to another state like so:
update=function() if keyboard.press.SPACE then SwitchState(maingame) end end
Likewise from the maingame block you can switch around to any other code block:
update=function() if keyboard.press.P then SwitchState(pausegame) end end
The main game loop just constantly calls
whatever block the
state variable is pointing to gets updated and drawn during runtime.
See if you can make a
gameoverstate block that is called when the sprite leaves the screen,
Continuing from the above challenge offer the option to play again or return to the title page.
How about a
gamepausedstate block when P is pressed?
How would you create a
universalcode block that gets called all of the time, regardless of which state is active? Hint: What is the main loop doing all of the time?