Created
March 22, 2019 17:13
-
-
Save drhayes/b658fb2cead7f13d0c9bf5ba7e78d9d8 to your computer and use it in GitHub Desktop.
An old, busted version of coroutine-based AI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local Brain = {} | |
local currentTime = 0 | |
local timeWaits = {} | |
local animWaits = {} | |
local yields = {} | |
local function yield() | |
local co = coroutine.running() | |
yields[co] = true | |
return coroutine.yield(co) | |
end | |
local function waitSeconds(secs) | |
local co = coroutine.running() | |
timeWaits[co] = currentTime + secs | |
coroutine.yield(co) | |
end | |
local function waitForAnimation(anim) | |
local co = coroutine.running() | |
animWaits[anim] = co | |
coroutine.yield(co) | |
end | |
local function waitForSignal(signalName) | |
local co = coroutine.running() | |
local function waiter(a, b, c, d, e, f) | |
Signal.remove(signalName, waiter) | |
coroutine.resume(co, a, b, c, d, e, f) | |
end | |
Signal.register(signalName, waiter) | |
coroutine.yield(co) | |
end | |
function Brain.clear() | |
timeWaits = {} | |
animWaits = {} | |
yields = {} | |
end | |
function Brain.create(f, target) | |
local env = { | |
target = target, | |
waitSeconds = waitSeconds, | |
waitForAnimation = waitForAnimation, | |
waitForSignal = waitForSignal, | |
yield = yield, | |
random = love.math.random, | |
media = media, | |
-- Useful globals... | |
game = game, | |
Camera = Camera, | |
print = print, | |
inspect = inspect, | |
math = math, | |
lume = lume, | |
flux = flux, | |
Signal = Signal, | |
TEsound = TEsound | |
} | |
local co = coroutine.create(f) | |
local okay, msg = coroutine.resume(co, env) | |
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 | |
for co,_ in pairs(yields) do | |
yields[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