IdleHunt = function(actor)
	Trigger.OnIdle(actor, function(a)
		if a.IsInWorld then
			a.Hunt()
		end
	end)
	Trigger.OnKilled(actor, function()
		if Utils.RandomInteger(0,10) <= 8 then
			New_Ufo = Actor.Create("ufo", true, { Owner = Creeps, Location = CPos.New( Map.BottomRight.X / 2048.0 + 0.5 + Utils.RandomInteger(-5,5) , Map.BottomRight.Y / 2048.0 + 0.5 + Utils.RandomInteger(-5,5) ) })
			IdleHunt(New_Ufo)
		end
	end)
end

next=60

function doUfo()

	Trigger.AfterDelay(DateTime.Seconds(next), function()

		New_Ufo = Actor.Create("ufo", true, { Owner = Creeps, Location = CPos.New( Map.BottomRight.X / 2048.0 + 0.5 + Utils.RandomInteger(-5,5) , Map.BottomRight.Y / 2048.0 + 0.5 + Utils.RandomInteger(-5,5) ) })
		Loc = CPos.New( Utils.RandomInteger(1,Map.BottomRight.X / 1024.0) , Utils.RandomInteger(1,Map.BottomRight.Y / 1024.0) )
		New_Ufo.Move(Loc)
		IdleHunt(New_Ufo)

		Ufos = Map.ActorsInBox(Map.TopLeft, Map.BottomRight, function(actor)
			return actor.Type == "ufo" and actor.Owner.InternalName == "Creeps"
		end)
		Utils.Do(Ufos, function(Ufo)
			if Utils.RandomInteger(0,3) == 1 then
				Loc = CPos.New( Utils.RandomInteger(1,Map.BottomRight.X / 1024.0) , Utils.RandomInteger(1,Map.BottomRight.Y / 1024.0) )
				Ufo.Stop(Loc)
				Ufo.Move(Loc)
			end

			--IdleHunt(Ufo)
		end)
		if (next>10) then
			next = next - 2
		end
		doUfo()
    end)
end

Creeps = Player.GetPlayer("Creeps") 

function tablelength(T)
	local count = 0
	for _ in pairs(T) do count = count + 1 end
	return count
end

WorldLoaded = function()

	playersingame = {"Multi0","Multi1","Multi2","Multi3","Multi4","Multi5","Multi6","Multi7","Multi8","Multi9","Multi10","Multi11","Multi12","Multi13","Multi14","Multi15","Multi16","Multi17"} -- Table of Potential Players
	activeplayers = {}    -- Table for Active Players
	ufos_on = false
	z = 1
	playersingamecount = tablelength(playersingame) 
	for i = playersingamecount,1,-1 do 
		playername = playersingame[i]
		
		if (Player.GetPlayer(playername) ~= nil) then
			playerinfo = Player.GetPlayer(playername)
			activeplayers[z] = Player.GetPlayer(playername)
			z = z + 1
			if playerinfo.HasPrerequisites({"ufos_on"}) then
				ufos_on = true
			end
		end

	end
	


	if ufos_on == true then
		Trigger.AfterDelay(DateTime.Seconds(60), function()
			doUfo()
		end)
        --Media.DisplayMessage ("Ufos = True", "PMG", HSLColor.Red)
    --else
        --Media.DisplayMessage ("Ufos = False", "PMG", HSLColor.Red)
	end


end