Skip to content

Instantly share code, notes, and snippets.

@drhayes
Created March 22, 2019 17:11
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 drhayes/340fbc7f967b35dbc462efd5f187619d to your computer and use it in GitHub Desktop.
Save drhayes/340fbc7f967b35dbc462efd5f187619d to your computer and use it in GitHub Desktop.
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