Game Development with LÖVE
Prerequisites: Object-oriented programming
LÖVE (love2d.org) is a free framework for 2D games in Lua. It handles graphics, sound, input, and physics; you write the game logic in callbacks.
The game loop
-- illustrative
-- main.lua — run with: love .
local player = {x = 400, y = 300, speed = 200, size = 20}
local coins = {}
local score = 0
function love.load()
love.window.setTitle("Coin Collector")
math.randomseed(os.time())
for _ = 1, 5 do
table.insert(coins, {x = math.random(20, 780), y = math.random(20, 580)})
end
end
function love.update(dt) -- dt: seconds since last frame
if love.keyboard.isDown("left") then player.x = player.x - player.speed * dt end
if love.keyboard.isDown("right") then player.x = player.x + player.speed * dt end
if love.keyboard.isDown("up") then player.y = player.y - player.speed * dt end
if love.keyboard.isDown("down") then player.y = player.y + player.speed * dt end
for i = #coins, 1, -1 do
local c = coins[i]
if math.abs(c.x - player.x) < player.size and math.abs(c.y - player.y) < player.size then
table.remove(coins, i)
score = score + 1
end
end
end
function love.draw()
love.graphics.setColor(1, 0.8, 0)
for _, c in ipairs(coins) do love.graphics.circle("fill", c.x, c.y, 8) end
love.graphics.setColor(0.3, 0.7, 1)
love.graphics.rectangle("fill", player.x - 10, player.y - 10, 20, 20)
love.graphics.setColor(1, 1, 1)
love.graphics.print("Score: " .. score, 10, 10)
end
love.loadruns once at the start;love.update(dt)andlove.drawrun every frame (usually 60 times per second).- Multiplying speeds by
dtmakes movement independent of frame rate. - Other callbacks handle input events:
love.keypressed(key),love.mousepressed(x, y, button).
Structuring a larger game
- Game states — menu, playing, paused, game over — each a module
with its own
update/draw(the hump.gamestate library helps). - Entities as classes (see the OOP lessons) with
update(dt)anddraw()methods, kept in a list. - Libraries —
bump.lua(collision),anim8(sprite animation),hump.timer(tweens and delays), andlove.physics(Box2D). - Distribution — zip the folder as a
.lovefile, or fuse it with the LÖVE executable for Windows, macOS, Linux, Android, and iOS.
Other Lua game engines include Defold (a full editor, used for commercial mobile games), Solar2D, and PICO-8 (a "fantasy console" using a Lua subset).