Using coroutines for AI

Showcase your libraries, tools and other projects that help your fellow love users.
Post Reply
User avatar
miko
Party member
Posts: 410
Joined: Fri Nov 26, 2010 2:25 pm
Location: PL

Using coroutines for AI

Post by miko »

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).
Attachments
turtle.love
(999 Bytes) Downloaded 442 times
My lovely code lives at GitHub: http://github.com/miko/Love2d-samples
User avatar
Inny
Party member
Posts: 652
Joined: Fri Jan 30, 2009 3:41 am
Location: New York

Re: Using coroutines for AI

Post by Inny »

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:

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
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.
User avatar
miko
Party member
Posts: 410
Joined: Fri Nov 26, 2010 2:25 pm
Location: PL

Re: Using coroutines for AI

Post by miko »

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.
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.
My lovely code lives at GitHub: http://github.com/miko/Love2d-samples
Post Reply

Who is online

Users browsing this forum: No registered users and 18 guests