Yet Another Multiple States System

From Pico-8 Wiki
Jump to navigation Jump to search

Description

This will give you an easy way to keep the code separate for your game's different states (such as menu screen, gameplay, and game over screen). It's easy to manage, easy to add to, and easy to understand again when you come back to your code months later and want to figure out what does what.

This is a different method of achieving the same result as the Multiple States System guide.

Instructions

The basic idea is that alongside the built-in _init(), _update(), and _draw() functions, you create a different set of init(), update(), and draw() functions for each state you need in your game. This system relies on the useful fact that Lua variables can hold function names.

For this example, we'll start with the menu state, and then add the game state so you can see how easy it is to add new states. To create your game's menu state, write the following:

function _init()
 menu_init()
end

function _update()
 update()
end

function _draw()
 draw()
end


function menu_init()
 update=menu_update
 draw=menu_draw
end

function menu_update()
end

function menu_draw()
end

Adding Another State

Now if you want to add a game state, you just add the following three functions:

function game_init()
 update=game_update
 draw=game_draw
end

function game_update()
end

function game_draw()
end

Switching States

To switch to the game state, all you need to do is call game_init(). For example, the menu's menu_update() function might look like this:

function menu_update()
 if (btn(4)) game_init()
end

When the game is over, you could just call menu_init() to go back to the menu.

Further Tweaks

Since you won't ever be doing much with the built-in game loop functions, you can optionally condense them down into the following 3 lines of code:

 function _init() menu_init() end
 function _update() update() end
 function _draw() draw() end

(This just takes up less space in the editor. It doesn't actually do anything different)