Skip to content
Download

5. Score and lives

Score and lives are used by several objects and live in a shared file. Right-click the src folder › New script…

src/game.lua
local game = {
score = 0,
lives = 3,
}
return game

On Enemy, create the variable pontos, of type integer, with the value 100. In code, load the state and add in kill:

objects/Enemy.lua
local game = require("src.game")
function kill(self)
if not self:exists() then return end
game.score = game.score + self.pontos
self:destroy()
end

On Player: touching an enemy takes a life and gives 90 steps of invincibility, during which the ship blinks.

objects/Player.lua
local game = require("src.game")
function onSpawn(self)
self.animSpeed = 0.2
self.podeAtirar = true
self.invencivel = 0
self:onCollide("Enemy", function(enemy)
if self:hurt() then enemy:destroy() end
end)
end
function onUpdate(self)
-- ...
if self.invencivel > 0 then self.invencivel = self.invencivel - 1 end
end
function onRender(self)
if self.invencivel > 0 and (self.invencivel // 4) % 2 == 0 then return end
self:drawSelf()
end
function hurt(self)
if self.invencivel > 0 or not self:exists() then return false end
game.lives = game.lives - 1
if game.lives <= 0 then
self:destroy()
else
self.invencivel = 90
end
return true
end
  • hurt returns false while the ship is invincible; only then does the enemy stay alive.
  • onRender replaces the default drawing: it skips some steps so the ship blinks and calls drawSelf on the others.

Create the object Hud, with no sprite, and drag it into the room Main.

objects/Hud.lua
local game = require("src.game")
function onRenderGui(self)
drawText(string.format("PONTOS %05d", game.score), 4, 4)
drawText("VIDAS " .. game.lives, 4, 14, colors.yellow)
end

onRenderGui draws in screen coordinates, on top of everything. A score display built in the editor, with no drawing code, is in HUD and pause menu.

Play. Each enemy is worth 100 points; touching one takes a life and the ship blinks. With no lives left, the ship disappears.

Next part: 6. Sound