Skip to content
Download

7. Game over

  1. Right-click the rooms folder › New room…, named GameOver.

  2. Create the object GameOverScreen, with no sprite, and drag it into the room GameOver.

  3. Under Input actions, create confirmar (Enter, Pad:Start) and sair (Escape, picked from the Key list, and Pad:Back).

In the state file, one function that centers text and another that restarts the game:

src/game.lua
function game.centeredX(text, screenWidth)
return (screenWidth - #text * 8) / 2
end
function game.newGame()
game.score = 0
game.lives = 3
goTo("Main")
end
return game

On Player, in hurt, when the lives run out:

objects/Player.lua
if game.lives <= 0 then
goTo("GameOver")
self:destroy()
objects/GameOverScreen.lua
local game = require("src.game")
function onUpdate(self)
if pressed("confirmar") then game.newGame() end
if pressed("sair") then quit() end
end
function onRenderGui(self)
local tela = roomWidth()
local titulo = "FIM DE JOGO"
local pontos = "PONTOS " .. game.score
local denovo = "ENTER JOGAR DE NOVO"
local sair = "ESC SAIR"
drawText(titulo, game.centeredX(titulo, tela), 60, colors.red)
drawText(pontos, game.centeredX(pontos, tela), 85)
drawText(denovo, game.centeredX(denovo, tela), 120)
drawText(sair, game.centeredX(sair, tela), 135, Color(150, 150, 150))
end
  • pressed is true only on the step the action was pressed: one press, one action.
  • goTo switches rooms at the end of the frame; the instances of the current room are destroyed.
  • C++: outside an object, the room switch is brasa::goToScene.

Play. After losing the three lives, the room GameOver shows the score. Enter restarts; Esc quits.