Skip to content

Instantly share code, notes, and snippets.

@drhayes

drhayes/brain.lua

Created Mar 22, 2019
Embed
What would you like to do?
An old coroutine-based AI
local lume = require 'lib/lume'
local Brain = {}
local currentTime = 0
local timeWaits = {}
local animWaits = {}
local function waitSeconds(secs)
local co = coroutine.running()
timeWaits[co] = currentTime + secs
return coroutine.yield(co)
end
local function waitForAnimation(anim)
local co = coroutine.running()
animWaits[anim] = co
return coroutine.yield(co)
end
function Brain.create(f, sprite)
local f_clone = loadstring(string.dump(f))
setfenv(f_clone, {
sprite = sprite,
waitSeconds = waitSeconds,
waitForAnimation = waitForAnimation,
-- Useful globals...
game = sprite.game,
print = print,
inspect = inspect,
math = math,
lume = lume
})
local co = coroutine.create(f_clone)
local okay, msg = coroutine.resume(co)
if not okay then
print('Error in Brain.create', msg)
end
end
function Brain.update(dt)
currentTime = currentTime + dt
local cos = {}
for co, wakeupTime in pairs(timeWaits) do
if wakeupTime < currentTime then
table.insert(cos, co)
end
end
for _, co in ipairs(cos) do
timeWaits[co] = nil
local okay, msg = coroutine.resume(co)
if not okay then
print('Error in Brain.update', msg)
end
end
end
function Brain.animationComplete(anim)
anim:pauseAtEnd()
local co = animWaits[anim]
if co then
animWaits[anim] = nil
local okay, msg = coroutine.resume(co)
if not okay then
print('Error in Brain.animationComplete', msg)
end
end
end
return Brain
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment