Using the implementation to find a path

Now that the path-finding implementation is complete, it's time to call it for any enemy who isn't currently doing something.

Getting ready

Open the file monster.lua and find the nested function called idle.

Getting on with it

The idle function does nothing right now; it just waits forever.

Monitoring while idle

Functions in these AI controllers tend to be very high-level and abstract. We'll use a provided iterator to look at each of the surrounding spaces within a certain distance:

  function idle()
    while wait() do
      for space in surroundings(4) do
      end
    end
  end

For each nearby space, we'll check its contents:

    while wait() do
      for space in surroundings(4) do
        for _, content in ipairs(space.Features) do
        end
      end
    end

If anything in the space is a character with a different allegiance, or faction, it's time to chase after it and attack:

      for space in surroundings(4) do
        for _, content in ipairs(space.Features) do
          if content.Character and content.Alleigance ~= self.Alleigance then
            return hunt(content)
          end
        end
      end

Responding with pursuit

Add another function next to idle:

  local idle, hunt
  function hunt(quarry)
  end
  function idle()

These enemies are relentless and never stop chasing you due to the following code:

  function hunt(quarry)
    while true do
    end
  end

A hunting enemy checks whether its quarry is adjacent to it:

    while true do
      local dX, dY = location()
      dX, dY = dX - quarry.Location.x, dY - quarry.Location.y
      if math.abs(dX + dY) == 1 and dX * dY == 0 then
      end
    end

If so, the monster attacks (this feature isn't actually implemented yet):

      dX, dY = dX - quarry.Location.x, dY - quarry.Location.y
      if math.abs(dX + dY) == 1 and dX * dY == 0 then
        attack(quarry)
      end

Otherwise, the monster identifies the next step in getting to that point, and starts moving there. If the space is unavailable, step returns false, and the monster waits:

      if math.abs(dX + dY) == 1 and dX * dY == 0 then
        attack(quarry)
      else
        local proceed = path(location(), quarry.Location)
        if proceed then
          if not step(proceed) then wait() end
        end
      end

What did we do?

We tracked which computer characters are currently in the middle of an action, and when they're not already occupied with an attack or a movement, we've used this path-finding tool to select a course for them to follow to guarantee that they remain a threat to any player who stands and waits.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.17.20