-- Required control rate.
control_rate = 2

-- Required "control" function.
function control()
  if ai.taskname() == "none" then
    ai.pushtask(0, "fly")
  end
end

-- Required "attacked" function.
function attacked(attacker)
  task = ai.taskname()
  if task ~= "attack" and task ~= "runaway" then
    -- Let's have some taunts.
    taunt(attacker)

    -- Now pilot fights back.
    ai.pushtask(0, "attack", attacker)
  elseif task == "attack" then
    if ai.targetid() ~= attacker then
      ai.pushtask(0, "attack", attacker)
    end
  end
end

-- Taunts.
function taunt(target)
  num = ai.rnd(0,4)
  if num == 0 then msg = "You will never kill me!"
  elseif num == 1 then msg = "DIE!"
  elseif num == 2 then msg = "You won't survive!"
  elseif num == 3 then msg = "I hate you!"
  end
  if msg then ai.comm(attacker, msg) end
end

-- Runs away.
function runaway()
  target = ai.targetid()

  -- Make sure pilot exists.
  if not ai.exists(target) then
    ai.poptask()
    return
  end

  dir = ai.face(target, 1)
  ai.accel()
end

-- Attack
function attack()
  target = ai.targetid()

  -- Make sure target exists.
  if not ai.exists(target) then
    ai.poptask()
    return
  end

  dir = ai.face(target)
  dist = ai.dist(ai.pos(target))
  second = ai.secondary()

  if ai.secondary() == "Launcher" then
    ai.settarget(target)
    ai.shoot(2)
  end

  if ai.parmour() < 70 then
    ai.poptask()
    ai.pushtask(0, "runaway", target)
  elseif dir < 10 and dist > 300 then
    ai.accel()
  elseif dir < 10 and dist < 300 then
    ai.shoot()
  end
end

-- Fly to the player.
function fly()
  target = player
  dir = ai.face(target)
  dist = ai.dist(ai.pos(target))
  if dir < 10 and dist > 300 then
    ai.accel()
  end
end