Hello,
this is example (as requested on lua-l) of using coroutines for easy logic programming, so your character logic is written as a sequence of commands even if they are executed in parallel. It's easy to create turtle (LOGO-like) graphics then. Check the source code (by unzipping the attached file).
Using coroutines for AI
Using coroutines for AI
- Attachments
-
turtle.love- (999 Bytes) Downloaded 442 times
My lovely code lives at GitHub: http://github.com/miko/Love2d-samples
Re: Using coroutines for AI
Oh yeah, that's a great use of coroutines. It certainly simplifies a lot of the more complex things that you'd want to do. Here's a snippet of code that I use as a mixin for my AI classes:
About the only limitation I can see of it is that there's very little introspection of what goes on inside the coroutine functions. Like if you wanted to change what gets drawn in the draw function, the coroutine has to set a flag, a state variable, or otherwise signal that something needs to be drawn with explicit code.
Code: Select all
local Actor = {}
function Actor:cowrap(func)
self.cothread = coroutine.create(function() func(self) end)
end
function Actor:corun(dt)
local err, msg = coroutine.resume(self.cothread, dt)
if err == false then
error(debug.traceback(self.cothread, msg))
end
return (coroutine.status(self.cothread)=="dead")
end
function Actor:cowait(secs)
repeat
local dt = coroutine.yield(true)
if not secs then
self.codt = 0
return dt
end
self.codt = (self.codt or 0) + dt
until self.codt >= secs
self.codt = self.codt - secs
return secs
end
Re: Using coroutines for AI
I would (and did in the original example) use coroutines only to change the object's state, not for drawing, as you have (usually) no control of the order in which the coroutines will get called. The drawing should be done only within one thread of execution (the "main" thread, without using coroutines) to be safe, based on something like global list of objects to draw.Inny wrote:Like if you wanted to change what gets drawn in the draw function, the coroutine has to set a flag, a state variable, or otherwise signal that something needs to be drawn with explicit code.
My lovely code lives at GitHub: http://github.com/miko/Love2d-samples
Who is online
Users browsing this forum: No registered users and 18 guests