Game State in PICO-8

PICO-8 is a fantastic programming environment and the new tabs feature really helps divide up your code.

One area that can be difficult for new programmers is game state.  How do you know when you should be displaying the menu or game over?  It is difficult to do this using conditional statements as you end up with a long series of IF-THEN statements littering your code.

A better way is to make use of the ability to store a function within a variable held in a table.

As you know, PICO-8 has three important protected functions that a program requires (well, 2 really as you don’t have to use _init()).

function _init()


function _update()


function _draw()


The problem comes with trying to stuff all your code into _update() and _draw().

What I like to do is declare a table that will contain the functions required to control the game.  I declare a table called game={} and set the _update and _draw functions to perform whatever actions are stored in the variables upd and drw.

[Update – Thanks to @LazyDevsAcademy for pointing out that it would save tokens to simply have gameupd() and gamedrw() as variables rather than having game().]

state game={}

function _update()

function _draw()

And then, in the next few tabs I create a function which will assign the update and draw functions to the two variables game.upd and game.drw.

Here is an example for the splash screen state.

function show_splash()
  game.upd = splash_screen_update
  game.drw = splash_screen_draw

function splash_screen_update()
  --update the splash screen

  --change to the next state
  --when ready

function splash_screen_draw()
  --draw the splash screen

show_splash() can be called from anywhere in code and when it is it will set the game.drw and game.upd variables to the functions splash_screen_update() and splash_screen_draw(). Remember, these variables are referenced in our _draw() and _update functions and so PICO-8 will run the splash code as though it was the code within the draw and update routines.  By having multiple combinations of the show_foo() function to set the update and draw variables you can have multiple game states with minimal effort.

I place each one in a separate tab and also have a tab for general functions and objects and I find i gives a really easy way to keep track of my code.  I also have a standard tab of splash screen code that can be pasted in to every project to give me the same splash screen for every game.

I have attached a basic cart that has all the tabs arranged with game states for splash, menu, game and game over states.  Feel free to download (basic.p8) it and use it for your projects.

Happy coding!

You May Also Like

About the Author: Doc Robs

Leave a Reply

Your email address will not be published. Required fields are marked *