Skip to content

Instantly share code, notes, and snippets.

@mkosler
Created March 23, 2013 05:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkosler/5226586 to your computer and use it in GitHub Desktop.
Save mkosler/5226586 to your computer and use it in GitHub Desktop.
Manager
-- Possible topic:
-- - The require statement
local Manager = require 'manager'
-- Possible topic:
-- - Object-oriented programming
local Ball = Class{}
function Ball:init(x, y, r)
self.x = x
self.y = y
self.r = r
self.vx = math.random(50, 100)
self.vy = math.random(50, 100)
Manager.add(self)
end
function Ball:update(dt)
if not (0 < self.x and self.x < love.graphics.getWidth()) then
self.vx = -self.vx
end
if not (0 < self.y and self.y < love.graphics.getHeight()) then
self.vy = -self.vy
end
self.x = self.x + (self.vx * dt)
self.y = self.y + (self.vy * dt)
end
function Ball:draw()
love.graphics.setColor(0, 255, 0)
love.graphics.circle('fill', self.x, self.y, self.r)
end
return Ball
Class = require 'class'
local Manager = require 'manager'
local Ball = require 'ball'
local Paddle = require 'paddle'
function love.load()
for i = 1, 100 do
Ball(
math.random(love.graphics.getWidth()),
math.random(love.graphics.getHeight()),
math.random(5, 10))
Paddle(
math.random(love.graphics.getWidth()),
math.random(love.graphics.getHeight()),
math.random(5, 10),
math.random(5, 10))
end
end
function love.update(dt)
Manager.map('update', dt)
end
function love.draw()
Manager.map('draw')
end
local _objects = {}
-- Possible topic:
-- - Runtime benefits of _objects[o] = true over table.insert(_objects, o)
local function add(o)
_objects[o] = true
end
local function remove(o)
_objects[o] = nil
end
-- Possible topic:
-- - The vararg
-- - v[f](v, ...) : Why did I do it this way?
local function map(f, ...)
for v,_ in pairs(_objects) do
if v[f] then v[f](v, ...) end
end
end
-- Possible topic
-- - The module
return {
add = add,
remove = remove,
map = map,
}
local Manager = require 'manager'
local Paddle = Class{}
function Paddle:init(x, y, w, h)
self.x = x
self.y = y
self.w = w
self.h = h
self.vy = math.random(50, 100)
Manager.add(self)
end
function Paddle:update(dt)
if not (0 < self.y and self.y < love.graphics.getHeight()) then
self.vy = -self.vy
end
self.y = self.y + (self.vy * dt)
end
function Paddle:draw()
love.graphics.setColor(255, 0, 0)
love.graphics.rectangle('fill', self.x, self.y, self.w, self.h)
end
return Paddle
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment