added the demo files

This commit is contained in:
Enrique García Cota 2012-01-29 13:03:33 +01:00
commit 333b25c40c
5 changed files with 394 additions and 0 deletions

17
README.textile Normal file
View File

@ -0,0 +1,17 @@
h1. beholder.lua demo
This is a demo of the beholder.lua library. It shows how the library can be used to capture and manage different kinds of events.
The demo requires "LÖVE":http://love2d.org
h2. Instructions
* Download and install LÖVE
* Download/uncompress this repo to a folder
* Execute with LÖVE
<pre>
cd folder/where/this/repo/is
love .
</pre>

BIN
beholder-demo.love Executable file

Binary file not shown.

141
beholder.lua Executable file
View File

@ -0,0 +1,141 @@
-- beholder.lua - v1.0.1 (2011-11)
-- Copyright (c) 2011 Enrique García Cota
-- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN callback OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
local function copy(t)
local c={}
for i=1,#t do c[i]=t[i] end
return c
end
-- private Node class
local Node = {
_nodesById = setmetatable({}, {__mode="k"})
}
function Node:new()
local node = { callbacks = {}, children = setmetatable({}, {__mode="k"}) }
return setmetatable( node, { __index = Node } )
end
function Node:findById(id)
return self._nodesById[id]
end
function Node:findOrCreateChild(key)
self.children[key] = self.children[key] or Node:new()
return self.children[key]
end
function Node:findOrCreateDescendant(keys)
local node = self
for i=1, #keys do
node = node:findOrCreateChild(keys[i])
end
return node
end
function Node:invokeCallbacks(params)
local counter = 0
for _,callback in pairs(self.callbacks) do
callback(unpack(params))
counter = counter + 1
end
return counter
end
function Node:invokeAllCallbacksInSubTree(params)
local counter = self:invokeCallbacks(params)
for _,child in pairs(self.children) do
counter = counter + child:invokeAllCallbacksInSubTree(params)
end
return counter
end
function Node:invokeCallbacksFromPath(path)
local node = self
local params = copy(path)
local counter = node:invokeCallbacks(params)
for i=1, #path do
node = node.children[path[i]]
if not node then break end
table.remove(params, 1)
counter = counter + node:invokeCallbacks(params)
end
return counter
end
function Node:addCallback(callback)
local id = {}
self.callbacks[id] = callback
Node._nodesById[id] = self
return id
end
function Node:removeCallback(id)
self.callbacks[id] = nil
Node._nodesById[id] = nil
end
-- beholder private functions
local function falseIfZero(n)
return n > 0 and n
end
local function checkSelf(self, methodName)
assert(type(self)=="table" and self._root, "Use beholder:" .. methodName .. " instead of beholder." .. methodName)
end
local function extractEventAndCallbackFromParams(params)
assert(#params > 0, "beholder:observe requires at least one parameter - the callback. You usually want to use two, i.e.: beholder:observe('EVENT', callback)")
local callback = table.remove(params, #params)
return params, callback
end
local function initialize(self)
self._root = Node:new()
end
------ Public interface
local beholder = {}
function beholder:observe(...)
checkSelf(self, 'observe')
local event, callback = extractEventAndCallbackFromParams({...})
return self._root:findOrCreateDescendant(event):addCallback(callback)
end
function beholder:stopObserving(id)
checkSelf(self, 'stopObserving')
local node = Node:findById(id)
if not node then return false end
node:removeCallback(id)
return true
end
function beholder:trigger(...)
checkSelf(self, 'trigger')
return falseIfZero( self._root:invokeCallbacksFromPath({...}) )
end
function beholder:triggerAll(...)
checkSelf(self, 'triggerAll')
return falseIfZero( self._root:invokeAllCallbacksInSubTree({...}) )
end
function beholder:reset()
checkSelf(self, 'reset')
initialize(self)
end
initialize(beholder)
return beholder

3
love.conf Executable file
View File

@ -0,0 +1,3 @@
function love.conf(t)
t.console = true
end

233
main.lua Executable file
View File

@ -0,0 +1,233 @@
beholder = require 'beholder'
local directions = {
up = {dx = 0, dy = -1},
down = {dx = 0, dy = 1},
left = {dx = -1, dy = 0},
right = {dx = 1, dy = 0}
}
function startMoving(entity, direction)
entity.want[direction] = true
end
function stopMoving(entity, direction)
if not direction then
entity.want = {}
else
entity.want[direction] = nil
end
end
function pause(entity)
entity.paused = true
end
function unpause(entity)
entity.paused = false
end
function move(entity, dt)
if not entity.paused then
for dir,delta in pairs(directions) do
if entity.want[dir] then
entity.x = entity.x + delta.dx * entity.speed
entity.y = entity.y + delta.dy * entity.speed
end
end
end
end
function checkCollision(a,b)
local ax1, ay1, ax2, ay2 = a.x, a.y, a.x+16, a.y+16
local bx1, by1, bx2, by2 = b.x, b.y, b.x+16, b.y+16
if ax1 < bx2 and ax2 > bx1 and ay1 < by2 and ay2 > by1 then
beholder:trigger("COLLISION", a, b)
beholder:trigger("COLLISION", b, a)
end
end
function draw(entity)
love.graphics.setColor(unpack(entity.color))
love.graphics.rectangle("line", entity.x, entity.y, 16, 16)
end
function relativePosition(entity)
local position = {}
local dx = entity.target.x - entity.x
local dy = entity.target.y - entity.y
table.insert(position, dy > 0 and 'down' or dy < 0 and 'up')
table.insert(position, dx > 0 and 'right' or dx < 0 and 'left')
return position
end
function chooseDirection(entity)
if entity.target then
stopMoving(entity)
for _,dir in ipairs(relativePosition(entity)) do
startMoving(entity, dir)
end
end
end
function all(collection, f,...)
for i=#collection,1,-1 do
f(collection[i], ...)
end
end
function allWithIndex(collection, f)
for i=#collection,1,-1 do
f(collection[i], i, collection)
end
end
function removeIfDead(entity, id, collection)
if entity.dead then table.remove(collection, id) end
end
function gameOver()
print("braains")
beholder:reset()
love.event.push('q')
end
entities, zombies = {},{}
function createPlayer()
player = {
x = 400,
y = 300,
want={},
color = {200,200,50},
speed = 2
}
setmetatable(player, {__tostring = function(t) return 'player' end})
for dir,_ in pairs(directions) do
beholder:observe("KEYPRESSED", dir, function() startMoving(player, dir) end)
beholder:observe("KEYRELEASED", dir, function() stopMoving(player, dir) end)
end
beholder:observe("KEYPRESSED", " ", activateMine)
beholder:observe("COLLISION", player, gameOver)
table.insert(entities, player)
end
function createZombie()
local zombie = {
x = math.random(20,780),
y = math.random(20,580),
want = {},
color = {50,150,50},
speed = math.max(math.random()/2, 0.4),
target = player
}
setmetatable(zombie, {__tostring = function(t) return 'zombie' end})
table.insert(zombies, zombie)
table.insert(entities, zombie)
end
function createMine()
mine = {
x = player.x,
y = player.y,
want = {},
color = {100,100,200},
speed = 0
}
setmetatable(mine, {__tostring = function(t) return 'mine' end})
beholder:observe("COLLISION", mine, function(zombie)
if not mine.exploded then
mine.exploded = true
mine.color = {50,50,50}
zombie.dead = true
beholder:trigger("KILLED", zombie)
end
end)
table.insert(entities, mine)
end
function activateMine()
if mine.exploded then
mine.exploded = false
mine.color = {100,100,200}
mine.x,mine.y = player.x, player.y
end
end
function love.update(dt)
all(zombies,chooseDirection)
all(entities,move)
all(zombies,checkCollision,player)
all(zombies,checkCollision,mine)
allWithIndex(zombies, removeIfDead)
allWithIndex(entities, removeIfDead)
end
function love.draw()
all(entities,draw)
love.graphics.setColor(255,255,255)
love.graphics.print("Last pressed key: " .. lastPressedKey, 0, 580)
end
function love.keypressed(key)
beholder:trigger("KEYPRESSED", key)
end
function love.keyreleased(key)
beholder:trigger("KEYRELEASED", key)
end
function love.load()
math.randomseed(os.time())
local zombieCount = 20
local killCount = 0
createPlayer()
createMine()
for i=1,zombieCount do
createZombie()
end
beholder:observe(print) -- print every event on the terminal
-- prints the last pressed key on the screen
lastPressedKey = "<none yet>"
beholder:observe("KEYPRESSED", function(key)
lastPressedKey = key
end)
-- binds escape to the gameOver function (quit game)
beholder:observe("KEYPRESSED", "escape", gameOver)
-- handle pause
beholder:observe("KEYPRESSED", "pause", function()
all(entities, pause)
local id
id = beholder:observe("KEYPRESSED", function()
all(entities, unpause)
beholder:stopObserving(id)
end)
end)
-- victor is triggered if enough kills are done
beholder:observe("KILLED", function()
killCount = killCount + 1
if killCount == zombieCount then
print("You win!")
beholder:reset()
love.event.push('q')
end
end)
end