Skip to content

Instantly share code, notes, and snippets.

@afk-mario
Last active November 21, 2018 06:43
Show Gist options
  • Save afk-mario/38be1e14cafbdf567bb8e3c0c24f146f to your computer and use it in GitHub Desktop.
Save afk-mario/38be1e14cafbdf567bb8e3c0c24f146f to your computer and use it in GitHub Desktop.
Pico 8 state machine for game screens.
function _draw()
-- manda a llamar la funcion
-- draw correspondiente al estado
if state == states.menu then
draw_menu()
elseif state == states.game then
draw_game()
elseif state == states.over then
draw_over()
end
end
-- dibuja el fondo del menu
-- el titulo del estado
-- y las instruciones
function draw_menu()
rectfill(0, 0, 128, 128, 2)
print(title, 2, 2, 7)
print("press ❎", 50, 62, 7)
end
-- dibuja el fondo del estado
-- dibuja el titulo del estado
-- dibuja la cantidad de vidas
-- restantes del jugador
function draw_game()
rectfill(0, 0, 128, 128, 3)
print(title, 2, 2, 7)
print("♥ " .. p.l, 128 - 20, 2, 7)
spr(p.s, p.x, p.y)
end
-- dibuja el fonde cuando acaba el juego
-- dibuja el titulo del estado
-- dibuja las instrucciones
function draw_over()
rectfill(0, 0, 128, 128, 4)
print(title, 40, 62, 7)
print("press ❎", 50, 72, 7)
end
function _init()
-- limpiamos la pantalla
cls()
-- inicializamos nuestros estados
init_state()
-- seteamos al estado de menu
set_state(states.menu)
end
function init_state()
states = {
menu = 1,
game = 2,
over = 3,
}
end
-- maneja la transicion entre
-- estados
function set_state(s)
state = s
if state == states.menu then
init_menu()
elseif state == states.game then
init_game()
elseif state == states.over then
init_over()
end
end
function init_menu()
title = "main menu"
end
function init_game()
title = "game"
init_player()
end
function init_over()
title = "game over :<"
end
function init_player()
-- inicializamos el jugador
p = {}
p.x = 64
p.y = 64
p.s = 0
p.dx = 1
p.dy = 1
p.l = 3
end
function _update()
-- dependiendo del estado activo
-- se manda a llamar la funcion
-- relacionada
if state == states.menu then
update_menu()
elseif state == states.game then
update_game()
elseif state == states.over then
update_over()
end
end
-- si el jugador presiona ❎
-- cambia del estado menu a juego
function update_menu()
if btnp(❎) then
set_state(states.game)
end
end
-- maneja el movimiento del jugador
-- y le quita una vida cada vez
-- que presiona ❎
function update_game()
if btn(⬅️) then
p.x -= p.dx
end
if btn(➡️) then
p.x += p.dx
end
if btn(⬆️) then
p.y -= p.dy
end
if btn(⬇️) then
p.y += p.dy
end
if btnp(❎) then
p.l -= 1
if p.l <= 0 then
set_state(states.over)
end
end
end
-- si presiona ❎ cambia al estado
-- de menu
function update_over()
if btnp(❎) then
set_state(states.menu)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment