Simple game state management / switching
Simple state manager
https://microstudio.dev/i/JimB007/simplestatemanager/
About
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 ofobject .. 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 update()
and 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 update()
and draw()
are now called.
In this demo a state block is switched via:
SwitchState(newstate)
newstate
is the name of state block that you want to take control of.
For example
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 ..
Main loop
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
Program flow
Let's suppose the active state is the titlepage code block.
In it's 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 state.update()
and state.draw()
so,
whatever block the state
variable is pointing to gets updated and drawn during runtime.
Challenges
See if you can make a
gameover
state 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
gamepaused
state block when P is pressed?How would you create a
universal
code 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?