TTT Detective Turtle Grenade: Cant Fix This Bug By Meself!

So for my first coding project i decided to make a TTT turtle Grenade for Detectives. it will spawn flying turtles that follow the thrower, and upon that thrower being harmed by someone, attack said someone.

What i am having problems with is that only one of the turtles spawned acts properly. they all have the like relationship towards the player, but all but one just act like a regular manhack who doesnt hurt me. the one that does work works great though.
even if i spawn a new bunch, the one that previously worked acts like the rest of em, and one from the new batch works.

i know that there are a couple errors in here, i love coding on my own so i just want this one thing fixed while i work on it more. The other thing i might like fixed is the yield hook, i cant get it to work.

THANKS!

ttt_Dturtlenade_proj:


 if SERVER then
   AddCSLuaFile("shared.lua")
end

ENT.Type = "anim"
ENT.Base = "ttt_basegrenade_proj"

ENT.Model = Model("models/props/de_tides/vending_turtle.mdl")

--Change these values to modify damage proporties
ENT.ExplosionDamage = 0
ENT.ExplosionRadius = 0
ENT.TurtleCount 	= 2

TurtleNPCClass 		= "npc_manhack"
TurtleInnocentDamage  = 0
TurtleTraitorDamage   = 15

AccessorFunc( ENT, "radius", "Radius", FORCE_NUMBER )
AccessorFunc( ENT, "dmg", "Dmg", FORCE_NUMBER )

function ENT:Initialize()
   if not self:GetRadius() then self:SetRadius(256) end
   if not self:GetDmg() then self:SetDmg(0) end
	--print(self:GetThrower())
   self.BaseClass.Initialize(self)

	local phys = self:GetPhysicsObject()
	if phys:IsValid() then phys:SetMass(350) end

end

function ENT:Explode(tr)
--self:GetThrower())
--print("hi")
Friend = self:GetThrower()
--[[print(Friend)
print(player.GetByID(1))
if Friend == player.GetByID(1) then print("YES") end ]]
   if SERVER then
      self.Entity:SetNoDraw(true)
      self.Entity:SetSolid(SOLID_NONE)

	  local pos = self.Entity:GetPos()

      -- pull out of the surface
      if tr.Fraction != 1.0 then
         self.Entity:SetPos(tr.HitPos + tr.HitNormal * 0.6)
      end

      --[[if util.PointContents(pos) == CONTENTS_WATER then
         self:Remove()
         return
      end]]--

      local effect = EffectData()
      effect:SetStart(pos)
      effect:SetOrigin(pos)
      effect:SetScale(self.ExplosionRadius * 0.3)
      effect:SetRadius(self.ExplosionRadius)
      effect:SetMagnitude(self.ExplosionDamage)

      if tr.Fraction != 1.0 then
         effect:SetNormal(tr.HitNormal)
      end

      util.Effect("Explosion", effect, true, true)

      util.BlastDamage(self, self:GetThrower(), pos, self.ExplosionRadius,self.ExplosionDamage)--self.ExplosionRadius, self.ExplosionDamage)

      self:SetDetonateExact(0)

	     for i=1,self.TurtleCount do
			local spos = pos+Vector(math.random(-75,75),math.random(-75,75),math.random(0,50))
			local contents = util.PointContents( spos )
			local _i = 0
			while i < 10 and (contents == CONTENTS_SOLID or contents == CONTENTS_PLAYERCLIP) do
				_i = 1 + i
				spos = pos+Vector(math.random(-125,125),math.random(-125,125),math.random(-50,50))
				contents = util.PointContents( spos )
			end

			local headturtle = SpawnNPC(self:GetThrower(),spos, TurtleNPCClass)

			headturtle:SetNPCState(2)
			--timer.Create("timer1", 10, 1, function() headturtle:SetPos(Vector(Friend:GetPos())) end)


			local turtle = ents.Create("prop_dynamic")
			turtle:SetModel("models/props/de_tides/vending_turtle.mdl")
			turtle:SetPos(spos)
			turtle:SetAngles(Angle(0,-90,0))
			turtle:SetParent(headturtle)
			--turtle:AddEntityRelationship(Friend, D_LI, 99 )

			--headturtle:SetCollisionGroup(COLLISION_GROUP_WEAPON)

			headturtle:SetNWEntity("Thrower", self:GetThrower())
			--headturtle:SetName(self:GetThrower():GetName())
			headturtle:SetNoDraw(true)
			headturtle:SetHealth(1000)
			--headturtle:AddEntityRelationship(Friend, D_LI, 99 )
			print("yep, made it here")
		end

      self:Remove()
   else

      local spos = self.Entity:GetPos()
      local trs = util.TraceLine({start=spos + Vector(0,0,64), endpos=spos + Vector(0,0,-128), filter=self})
      util.Decal("Scorch", trs.HitPos + trs.HitNormal, trs.HitPos - trs.HitNormal)

      self:SetDetonateExact(0)
   end
--print(Friend)
end

--From: gamemodes\sandbox\gamemode\commands.lua
--TODO: Adjust for TTT.
function SpawnNPC( Player, Position, Class )
--print(Friend)
Attacked = false
	local NPCList = list.Get( "NPC" )
	local NPCData = NPCList[ Class ]

	-- Don't let them spawn this entity if it isn't in our NPC Spawn list.
	-- We don't want them spawning any entity they like!
	if ( !NPCData ) then
		if ( IsValid( Player ) ) then
			Player:SendLua( "Derma_Message( \"Sorry! You can't spawn that NPC!\" )" );
		end
	return end

	local bDropToFloor = false

	--
	-- This NPC has to be spawned on a ceiling ( Barnacle )
	--
	if ( NPCData.OnCeiling && Vector( 0, 0, -1 ):Dot( Normal ) < 0.95 ) then
		return nil
	end

	if ( NPCData.NoDrop ) then bDropToFloor = false end

	--
	-- Offset the position
	--


	-- Create NPC
	local NPC = ents.Create( NPCData.Class )

	if ( !IsValid( NPC ) ) then return end

	--NPC:AddEntityRelationship(player.GetByID(1), D_LI, 99 )
	NPC:SetPos( Position )

	--
	-- This NPC has a special model we want to define
	--
	if ( NPCData.Model ) then
		NPC:SetModel( NPCData.Model )
	end

	--
	-- Spawn Flags
	--
	local SpawnFlags = bit.bor( SF_NPC_FADE_CORPSE, SF_NPC_ALWAYSTHINK)
	if ( NPCData.SpawnFlags ) then SpawnFlags = bit.bor( SpawnFlags, NPCData.SpawnFlags ) end
	if ( NPCData.TotalSpawnFlags ) then SpawnFlags = NPCData.TotalSpawnFlags end
	NPC:SetKeyValue( "spawnflags", SpawnFlags )

	--
	-- Optional Key Values
	--
	if ( NPCData.KeyValues ) then
		for k, v in pairs( NPCData.KeyValues ) do
			NPC:SetKeyValue( k, v )
		end
	end

	--
	-- This NPC has a special skin we want to define
	--
	if ( NPCData.Skin ) then
		NPC:SetSkin( NPCData.Skin )
	end

	--
	-- What weapon should this mother be carrying
	--

	NPC:Spawn()
	NPC:Activate()
	--NPC:UseFollowBehavior( )
	print(Player)
	NPC:AddRelationship("npc D_NU 99")
	NPC:AddEntityRelationship(Player, D_LI, 99 )
	--NPC:SetCollisionGroup( 5 )
	--NPC:CapabilitiesClear( )
   -- NPC:CapabilitiesAdd(CAP_MOVE_FLY )
	--NPC:CapabilitiesAdd(CAP_TURN_HEAD )


	NPC:SetTarget(Player)
	--NPC:NavSetGoalTarget( Player, Vector(0,0,0))
	print("1")
	--Player.GetPos()
timer.Create( "my_timer", 1, 0,
	function()
		MsgN("Hi")
		if Attacked then-- NPC:GetTarget() ~= Player or if
			print("Master attacked")
			print(NPC:GetTarget())
			if not NewAttacker:IsValid() then
						print("yay we did it")
						local NewAttacker = nil
						NPC:SetHealth(NPC:GetMaxHealth() )
						Attacked = false
						NPC:SetSchedule(SCHED_RUN_RANDOM)
			end
		end
		if not Player:Alive() then
			Player:ChatPrint("TURTLES: MASTER NOOOO!!!!")
			NPC:SetSchedule(SCHED_FALL_TO_GROUND)
			NPC:Ignite( 100, 0 )
			NPC:TakeDamage(100, NewAttacker, NewAttacker)
		end
		print(Attacked)
		print(NPC:GetTarget())
		if not Attacked then
			NPC:StopMoving( )
			NPC:SetLastPosition( Player:GetPos() )
			if NPC:GetTarget() == Player then else
				print("back to master")
				NPC:SetTarget(Player)
			end
			print(NPC:GetTarget( ))
			NPC:SetSchedule(SCHED_TARGET_CHASE)
	--NPC:SetPos( Player:GetPos())
	--NPC:NavSetGoal( Vector(10,10,10))
			NPC:SetArrivalSpeed(50)
			print(NPC:GetPathTimeToGoal( ))
	--coroutine.wait(5)
		end
	end )

function defended( victim, inflictor, attacker )
if Attacked then
 if ( victim == NewAttacker ) then
	local Attacked = false
	Player:ChatPrint("TURTLES: DEFENDED MASTER!!!!")
	NPC:ClearEnemyMemory()
	NPC:TaskComplete()
	NPC:SetSchedule(SCHED_VICTORY_DANCE)
 end
end
end

hook.Add("PlayerDeath", "Dturtle defended", defended)

function yield(player, strtext, bTeamOnly, bPlayerIsDead )
if player == Player then
print("yes")
if strText == "No." then
 		NPC:ClearEnemyMemory()
		NPC:ClearGoal()
		local Attacked = false
		Player:ChatPrint("TURTLES: SORRY MASTER!")
end
else print("no")
end
end
hook.Add("OnPlayerChat", "DTurtle Yield", yield)
function Follow()

    print("YAY")
	NPC:NavSetGoal( Player.GetPos())
	NPC:SetArrivalSpeed(5000)
end

function defend(victim, attacker)
if victim == Player then
Player:ChatPrint("TURTLES: DEFEND MASTER!!!!")
Attacked = true
NewAttacker = attacker
 --if ( NewAttacker:IsPlayer() ) then
		--NPC:FoundEnemySound( )
		--NPC:AddEffects( EF_ITEM_BLINK | EF_BRIGHTLIGHT )
		NPC:ClearEnemyMemory()
		NPC:ClearGoal()
		NPC:SetEnemy(NewAttacker)
		NPC:SetTarget(NewAttacker)
		NPC:SetNPCState(4)
		--print(NPC:GetTarget( ))
		NPC:SetSchedule( SCHED_TARGET_CHASE )
		NPC:AddEntityRelationship(NewAttacker, D_HT, 99)
		NPC:SetArrivalSpeed(5000)
		print(NPC:GetEnemy( ))
		print(NPC:GetNPCState( ))
		print(NPC:GetTarget())
-- end
end
end
hook.Add("PlayerHurt", "Dturtle defend", defend)
hook.Add("NPC:PhysicsCollide", "Dturtle Follow master", Follow)
	if ( bDropToFloor && !NPCData.OnCeiling ) then
		NPC:DropToFloor()
	end

	return NPC
end

if SERVER and GetConVarString("gamemode") == "terrortown" then
function TurtleNadeDamage(victim, dmg)
	local attacker = dmg:GetAttacker()

--[[
	if attacker:IsValid() and attacker:IsNPC() and attacker:GetClass() == TurtleNPCClass then
		if victim:IsTraitor() == true  then
			dmg:SetAttacker(attacker:GetNWEntity("Thrower"))
			dmg:SetDamage(TurtleTraitorDamage)
		else
			dmg:SetDamage(TurtleInnocentDamage)
		end
	end
--]]
	--Annoyingly complex check to make the headcrab ragdolls invisible
	if victim:GetClass() == TurtleNPCClass then
		dmg:SetDamageType(DMG_REMOVENORAGDOLL)
		--Odd behaviour occured when killing turtles with the 'crowbar'
		--Extra steps had to be taken to reliably hide the ragdoll.
		if dmg:GetInflictor():GetClass() == "weapon_zm_improvised" then
			local turtle = ents.Create("prop_physics")
			turtle:SetModel("models/props/de_tides/vending_turtle.mdl")
			turtle:SetPos(victim:GetPos())
			turtle:SetAngles(victim:GetAngles() + Angle(0,-90,0))
			turtle:SetColor(Color(128,128,128,255))
			turtle:SetCollisionGroup(COLLISION_GROUP_WEAPON)
			turtle:Spawn()
			turtle:Activate()

			local phys = turtle:GetPhysicsObject()
			if !(phys && IsValid(phys)) then turtle:Remove() end

			victim:SetNoDraw(false)
			victim:SetColor(Color(255,2555,255,1))
			--victim:SetRenderMode(RENDER_TRANSALPHA)

			victim:Remove()
		end
		if dmg:GetDamageType() == DMG_DROWN then
			dmg:SetDamage(0)
		end
		if (victim:Health() - dmg:GetDamage()) < 980 then
			local turtle = ents.Create("prop_physics")
			turtle:SetModel("models/props/de_tides/vending_turtle.mdl")
			turtle:SetPos(victim:GetPos())
			turtle:SetAngles(victim:GetAngles() + Angle(0,-90,0))
			turtle:SetColor(Color(128,128,128,255))
			turtle:SetCollisionGroup(COLLISION_GROUP_WEAPON)
			turtle:Spawn()
			turtle:Activate()

			local phys = turtle:GetPhysicsObject()
			if !(phys && IsValid(phys)) then turtle:Remove() end

			victim:Remove()
		end
	end
end

hook.Add("EntityTakeDamage","TurtlenadeDmgHandle",TurtleNadeDamage)
end


ttt_weapon_Dturtlenade:


resource.AddFile("materials/VGUI/ttt/icon_tl_turtle.vmt")

if SERVER then
   AddCSLuaFile( "shared.lua" )
end

SWEP.Base				= "weapon_tttbasegrenade"

SWEP.Kind = WEAPON_EQUIP2
SWEP.WeaponID = AMMO_MOLOTOV

SWEP.HoldType			= "grenade"
--[[
SWEP.CanBuy = { ROLE_TRAITOR }
SWEP.InLoadoutFor = nil
SWEP.LimitedStock = true
SWEP.AllowDrop = true
SWEP.IsSilent = false
SWEP.NoSights = true
]]--

SWEP.ViewModel			= "models/weapons/v_eq_flashbang.mdl"
SWEP.WorldModel			= "models/props/de_tides/vending_turtle.mdl"
SWEP.Weight				= 5
SWEP.AutoSpawnable      = false
-- really the only difference between grenade weapons: the model and the thrown
-- ent.

if CLIENT then
   -- Path to the icon material
   	SWEP.PrintName	 = "Detective Turtle Grenade"
	SWEP.Slot		 = 7

	if file.Exists("materials/VGUI/ttt/icon_tl_turtle.vmt", "GAME") then
		SWEP.Icon = "VGUI/ttt/icon_tl_turtle"
	else
		SWEP.Icon = "VGUI/ttt/icon_nades"
	end
   -- Text shown in the equip menu
	SWEP.EquipMenuData = {


		type = "Weapon",
		desc = "Turtle Grenade.
 Releases several hostile turtles on detonation."
   };
    function SWEP:DrawWorldModel()
		--self:DrawModel()
		local ply = self.Owner
		local pos = self.Weapon:GetPos()
		local ang = self.Weapon:GetAngles()
		if ply:IsValid() then
			local bone = ply:LookupBone("ValveBiped.Bip01_R_Hand")
			if bone then
				pos,ang = ply:GetBonePosition(bone)
			end
		else
			self.Weapon:DrawModel() --Draw the actual model when not held.
			return
		end
		if self.ModelEntity:IsValid() == false then
			self.ModelEntity = ClientsideModel(self.WorldModel)
			self.ModelEntity:SetNoDraw(true)
		end

		self.ModelEntity:SetModelScale(1,0)
		self.ModelEntity:SetPos(pos)
		self.ModelEntity:SetAngles(ang+Angle(0,0,180))
		self.ModelEntity:DrawModel()
	end
	function SWEP:ViewModelDrawn()
		local ply = self.Owner
		if ply:IsValid() and ply == LocalPlayer() then
			local vmodel = ply:GetViewModel()
			local idParent = vmodel:LookupBone("v_weapon.Flashbang_Parent")
			local idBase = vmodel:LookupBone("v_weapon")
			if not vmodel:IsValid() or not idParent or not idBase then return end --Ensure the model and bones are valid.
			local pos, ang = vmodel:GetBonePosition(idParent)
			local pos1, ang1 = vmodel:GetBonePosition(idBase) --Rotations were screwy with the parent's angle; use the models baseinstead.

			if self.ModelEntity:IsValid() == false then
				self.ModelEntity = ClientsideModel(self.WorldModel)
				self.ModelEntity:SetNoDraw(true)
			end

			self.ModelEntity:SetModelScale(0.5,0)
			self.ModelEntity:SetPos(pos-ang1:Forward()*1.25-ang1:Up()*1.25+2.3*ang1:Right())
			self.ModelEntity:SetAngles(ang1)
			self.ModelEntity:DrawModel()
		end
	end
end

function SWEP:GetGrenadeName()
   return "ttt_Dturtlenade_proj"
end

--Taken from base grenade
function SWEP:Initialize()
   if self.SetWeaponHoldType then
      self:SetWeaponHoldType(self.HoldNormal)
   end

   self:SetDeploySpeed(self.DeploySpeed)

   self:SetDetTime(2)
   self:SetThrowTime(0)
   self:SetPin(true)

   self.was_thrown = false
   if CLIENT then
	self.ModelEntity = ClientsideModel(self.WorldModel)
	self.ModelEntity:SetNoDraw(true)
   end
end

function SWEP:OnRemove()
   if CLIENT and IsValid(self.Owner) and self.Owner == LocalPlayer() and self.Owner:Alive() then
      RunConsoleCommand("use", "weapon_ttt_unarmed")
   end

   if CLIENT then
   self.ModelEntity:Remove()
   end
end


THANKS GUYS!

found
[lua]Lua Error: [ERROR] gamemodes/terrortown/entities/entities/ttt_dturtlenade_proj/shared.lua:290: Tried to use a NULL entity! 1. ClearEnemyMemory - [C]:-1 2. fn - gamemodes/terrortown/entities/entities/ttt_dturtlenade_proj/shared.lua:290 3. unknown - addons/ulib/lua/ulib/shared/hook.lua:183[/lua]
and
[lua]Lua Error: [ERROR] gamemodes/terrortown/entities/entities/ttt_dturtlenade_proj/shared.lua:214: Tried to use a NULL entity! 1. GetTarget - [C]:-1 2. unknown - gamemodes/terrortown/entities/entities/ttt_dturtlenade_proj/shared.lua:214[/lua]

i know about those, i will fix them later.

[editline]27th February 2014[/editline]

The other problem i am having is that they are targeting players.

Aren’t they supposed to? :v:

Not until the detective is attacked. They randomly attack players when they shouldn’t.

At this point they spawn, will defend their master, but they harm anything they touch and dont follow him. still onl able to get one to work too. ive lost almost all patience on this project, please help.


 if SERVER then
   AddCSLuaFile("shared.lua")
end

ENT.Type = "anim"
ENT.Base = "ttt_basegrenade_proj"

ENT.Model = Model("models/props/de_tides/vending_turtle.mdl")

--Change these values to modify damage proporties
ENT.ExplosionDamage = 0
ENT.ExplosionRadius = 0
ENT.TurtleCount 	= 1

TurtleNPCClass 		= "npc_manhack"
TurtleInnocentDamage  = 15
TurtleTraitorDamage   = 20
TurtleDetectiveDamage = 0

AccessorFunc( ENT, "radius", "Radius", FORCE_NUMBER )
AccessorFunc( ENT, "dmg", "Dmg", FORCE_NUMBER )

function ENT:Initialize()
   if not self:GetRadius() then self:SetRadius(256) end
   if not self:GetDmg() then self:SetDmg(0) end
	--print(self:GetThrower())
   self.BaseClass.Initialize(self)

	local phys = self:GetPhysicsObject()
	if phys:IsValid() then phys:SetMass(350) end

end



function ENT:Explode(tr)
--self:GetThrower())
--print("hi")
Friend = self:GetThrower()
--[[print(Friend)
print(player.GetByID(1))
if Friend == player.GetByID(1) then print("YES") end ]]
   if SERVER then
      self.Entity:SetNoDraw(true)
      self.Entity:SetSolid(SOLID_NONE)

	  local pos = self.Entity:GetPos()

      -- pull out of the surface
      if tr.Fraction != 1.0 then
         self.Entity:SetPos(tr.HitPos + tr.HitNormal * 0.6)
      end

      --[[if util.PointContents(pos) == CONTENTS_WATER then
         self:Remove()
         return
      end]]--

      local effect = EffectData()
      effect:SetStart(pos)
      effect:SetOrigin(pos)
      effect:SetScale(self.ExplosionRadius * 0.3)
      effect:SetRadius(self.ExplosionRadius)
      effect:SetMagnitude(self.ExplosionDamage)

      if tr.Fraction != 1.0 then
         effect:SetNormal(tr.HitNormal)
      end

      util.Effect("Explosion", effect, true, true)

      util.BlastDamage(self, self:GetThrower(), pos, self.ExplosionRadius,self.ExplosionDamage)--self.ExplosionRadius, self.ExplosionDamage)

      self:SetDetonateExact(0)

	     for i=1,self.TurtleCount do
			local spos = pos+Vector(math.random(-75,75),math.random(-75,75),math.random(0,50))
			local contents = util.PointContents( spos )
			local _i = 0
			while i < 10 and (contents == CONTENTS_SOLID or contents == CONTENTS_PLAYERCLIP) do
				_i = 1 + i
				spos = pos+Vector(math.random(-125,125),math.random(-125,125),math.random(-50,50))
				contents = util.PointContents( spos )
			end

			local headturtle = SpawnNPC(self:GetThrower(),spos, TurtleNPCClass)

			headturtle:SetNPCState(2)
			--timer.Create("timer1", 10, 1, function() headturtle:SetPos(Vector(Friend:GetPos())) end)


			local turtle = ents.Create("prop_dynamic")
			turtle:SetModel("models/props/de_tides/vending_turtle.mdl")
			turtle:SetPos(spos)
			turtle:SetAngles(Angle(0,-90,0))
			turtle:SetParent(headturtle)
			--turtle:AddEntityRelationship(Friend, D_LI, 99 )

			--headturtle:SetCollisionGroup(COLLISION_GROUP_WEAPON)

			headturtle:SetNWEntity("Thrower", self:GetThrower())
			--headturtle:SetName(self:GetThrower():GetName())
			headturtle:SetNoDraw(true)
			headturtle:SetHealth(1000)
			--headturtle:AddEntityRelationship(Friend, D_LI, 99 )
			print("yep, made it here")
		end

      self:Remove()
   else

      local spos = self.Entity:GetPos()
      local trs = util.TraceLine({start=spos + Vector(0,0,64), endpos=spos + Vector(0,0,-128), filter=self})
      util.Decal("Scorch", trs.HitPos + trs.HitNormal, trs.HitPos - trs.HitNormal)

      self:SetDetonateExact(0)
   end
--print(Friend)
end
--From: gamemodes\sandbox\gamemode\commands.lua
--TODO: Adjust for TTT.


function SpawnNPC( Player, Position, Class )
--for i = 1 ,2 do
--print(Friend)
Attacked = false
TurtleSpawn = true
FirstAttack = true
	local NPCList = list.Get( "NPC" )
	local NPCData = NPCList[ Class ]

	-- Don't let them spawn this entity if it isn't in our NPC Spawn list.
	-- We don't want them spawning any entity they like!
	if ( !NPCData ) then
		if ( IsValid( Player ) ) then
			Player:SendLua( "Derma_Message( \"Sorry! You can't spawn that NPC!\" )" );
		end
	return end

	local bDropToFloor = false

	--
	-- This NPC has to be spawned on a ceiling ( Barnacle )
	--
	if ( NPCData.OnCeiling && Vector( 0, 0, -1 ):Dot( Normal ) < 0.95 ) then
		return nil
	end

	if ( NPCData.NoDrop ) then bDropToFloor = false end

	--
	-- Offset the position
	--


	-- Create NPC
	local NPC = ents.Create( NPCData.Class )
	--local NPC2 = NPC
	--print(NPC2)

	if ( !IsValid( NPC ) ) then return end

	--NPC:AddEntityRelationship(player.GetByID(1), D_LI, 99 )
	NPC:SetPos( Position )

	--
	-- This NPC has a special model we want to define
	--
	if ( NPCData.Model ) then
		NPC:SetModel( NPCData.Model )
	end

	--
	-- Spawn Flags
	--
	local SpawnFlags = bit.bor( SF_NPC_FADE_CORPSE, SF_NPC_ALWAYSTHINK)
	if ( NPCData.SpawnFlags ) then SpawnFlags = bit.bor( SpawnFlags, NPCData.SpawnFlags ) end
	if ( NPCData.TotalSpawnFlags ) then SpawnFlags = NPCData.TotalSpawnFlags end
	NPC:SetKeyValue( "spawnflags", SpawnFlags )

	--
	NPC:SetKeyValue( "Squad Name" , "player_squad" )
	--
	if ( NPCData.KeyValues ) then
		for k, v in pairs( NPCData.KeyValues ) do
			NPC:SetKeyValue( k, v )
		end
	end

	--
	-- This NPC has a special skin we want to define
	--
	if ( NPCData.Skin ) then
		NPC:SetSkin( NPCData.Skin )
	end

	--
	-- What weapon should this mother be carrying
	--

	NPC:Spawn()
	NPC:SetColor(50, 50, 255, 255)
	NPC:Activate()
	print(Player)
	for k, v in pairs(player.GetAll()) do
	NPC:AddEntityRelationship(v, D_LI, 50 )
	print(v:Nick().. ": " ..NPC:Disposition(v))
	end
    NPC:AddEntityRelationship(Player, D_LI, 99 )

	function NoTurtleHomicide(ply, hitgroup, dmginfo)
	if not TurtleAttack then
	if dmginfo:GetAttacker() == NPC then
	PLayer:ChatPrint(TurtleAttack)
      dmginfo:SetDamage (0)
	end
	elseif TurtleAttack then
      if dmginfo:GetAttacker() == NPC then
   if NPC:GetTarget() ~= ply then
      dmginfo:SetDamage (0)
	else dmginfo:SetDamage (20) end
	end
   end
end

hook.Add("ScalePlayerDamage","DT NoHomicide",NoTurtleHomicide)

timer.Create( "my_timer", 1, 0,
	function()
		 if not Attacked then
		 --NPC:GetTarget()IsValid() then
		 --Player:ChatPrint("Turtles: " ..NPC:GetTarget()) end
		 TurtleAttack = false
		 NPC:ClearEnemyMemory()
		 NPC:ClearSchedule()
		 NPC:SetSchedule(SCHED_NPC_FREEZE)
		 NPC:SetNPCState(1)
		 end
		if Attacked then-- NPC:GetTarget() ~= Player or if
			if NPC:GetTarget() ~= nil then
			print("Master attacked by " ..NPC:GetTarget( ))
			 Player:ChatPrint("Turtles Attacking: " ..NPC:GetTarget() ) end
			if not NewAttacker:IsValid() then
						print("yay we did it")
						local NewAttacker = nil
						NPC:SetHealth(NPC:GetMaxHealth() )
						Attacked = false
						NPC:SetSchedule(SCHED_RUN_RANDOM)
			end
		end
		if not Player:Alive() then
			TurtleAttack = false
			Player:ChatPrint("TURTLES: MASTER NOOOO!!!!")
			NPC:SetSchedule(SCHED_FALL_TO_GROUND)
			local explode = ents.Create( "env_explosion" )
	explode:SetPos( NPC:GetPos() )
	explode:SetOwner( <PLAYER> )
	explode:Spawn()
	explode:SetKeyValue( "iMagnitude", "75" ) //the magnitude
			NPC:Ignite( 100, 0 )
			NPC:TakeDamage(100, NewAttacker, NewAttacker)
			TurtleSpawn = false
		end
		print(Attacked)
		print(NPC:GetTarget())
		if not Attacked then
		TurtleAttack = false
			NPC:StopMoving( )
			NPC:SetLastPosition( Player:GetPos() )
			--NPC:SetSchedule(SCHED_TARGET_CHASE)
	--NPC:SetPos( Player:GetPos())
	--NPC:NavSetGoal( Vector(10,10,10))
	--coroutine.wait(5)
		end
	end )

function defended( victim, inflictor, attacker )
if Attacked then
 if ( victim == NewAttacker ) then
 TurtleAttack = false
	Attacked = false
	Player:ChatPrint("TURTLES: DEFENDED MASTER!!!!")
	NPC:ClearEnemyMemory( )
	NPC:TaskComplete( )
	NPC:SetSchedule(SCHED_VICTORY_DANCE)
 end
end
end

hook.Add("PlayerDeath", "Dturtle defended", defended)


function yield( ply, text, public )
local public = true
if ply == Player then
Player:ChatPrint("yes")
if text == "No." then
		TurtleAttack = false
 		NPC:ClearEnemyMemory()
		NPC:ClearGoal()
		Attacked = false
		Player:ChatPrint("TURTLES: SORRY MASTER!")
end
else print("no")
end
end


hook.Add("PlayerSay", "DTurtle Yield", yield)


function defend(victim, attacker)
if TurtleSpawn then
if victim == Player then
Player:ChatPrint("TURTLES: DEFEND MASTER!!!!")
Attacked = true
TurtleAttack = true
NewAttacker = attacker
 --if ( NewAttacker:IsPlayer() ) then
		--NPC:FoundEnemySound( )
		--NPC:AddEffects( EF_ITEM_BLINK | EF_BRIGHTLIGHT )
if NPC:IsValid() then
	if not FirstAttack then
		NPC:ClearEnemyMemory()
		NPC:ClearGoal()
	end
		NPC:SetEnemy(NewAttacker)
		--NPC:SetTarget(NewAttacker)
		NPC:SetNPCState(4)
		--print(NPC:GetTarget( ))
		NPC:SetSchedule( SCHED_TARGET_CHASE )
		NPC:AddEntityRelationship(NewAttacker, D_HT, 99)
		NPC:SetArrivalSpeed(5000)
		print(NPC:GetEnemy( ))
		print(NPC:GetNPCState( ))
		print(NPC:GetTarget())
		FirstAttack = false
end
-- end
end
end
end

hook.Add("PlayerHurt", "Dturtle defend", defend)

---hook.Add("NPC:PhysicsCollide", "Dturtle Follow master", Follow)
	if ( bDropToFloor && !NPCData.OnCeiling ) then
		NPC:DropToFloor()
	end

	return NPC
end

if SERVER and GetConVarString("gamemode") == "terrortown" then
function TurtleNadeDamage(victim, dmg)
	local attacker = dmg:GetAttacker()

--[[
	if attacker:IsValid() and attacker:IsNPC() and attacker:GetClass() == TurtleNPCClass then
		if victim:IsTraitor() == true  then
			dmg:SetAttacker(attacker:GetNWEntity("Thrower"))
			dmg:SetDamage(TurtleTraitorDamage)
		else
			dmg:SetDamage(TurtleInnocentDamage)
		end
	end
--]]
	--Annoyingly complex check to make the headcrab ragdolls invisible
	if victim:GetClass() == TurtleNPCClass then
		dmg:SetDamageType(DMG_REMOVENORAGDOLL)
		--Odd behaviour occured when killing turtles with the 'crowbar'
		--Extra steps had to be taken to reliably hide the ragdoll.
		if dmg:GetInflictor():GetClass() == "weapon_zm_improvised" then
			local turtle = ents.Create("prop_physics")
			turtle:SetModel("models/props/de_tides/vending_turtle.mdl")
			turtle:SetPos(victim:GetPos())
			turtle:SetAngles(victim:GetAngles() + Angle(0,-90,0))
			turtle:SetColor(Color(128,128,128,255))
			turtle:SetCollisionGroup(COLLISION_GROUP_WEAPON)
			turtle:Spawn()
			turtle:Activate()

			local phys = turtle:GetPhysicsObject()
			if !(phys && IsValid(phys)) then turtle:Remove() end

			victim:SetNoDraw(false)
			victim:SetColor(Color(255,2555,255,1))
			--victim:SetRenderMode(RENDER_TRANSALPHA)

			victim:Remove()
		end
		if dmg:GetDamageType() == DMG_DROWN then
			dmg:SetDamage(0)
		end
		if (victim:Health() - dmg:GetDamage()) < 980 then
			local turtle = ents.Create("prop_physics")
			turtle:SetModel("models/props/de_tides/vending_turtle.mdl")
			turtle:SetPos(victim:GetPos())
			turtle:SetAngles(victim:GetAngles() + Angle(0,-90,0))
			turtle:SetColor(Color(128,128,128,255))
			turtle:SetCollisionGroup(COLLISION_GROUP_WEAPON)
			turtle:Spawn()
			turtle:Activate()

			local phys = turtle:GetPhysicsObject()
			if !(phys && IsValid(phys)) then turtle:Remove() end

			victim:Remove()
		end
	end
end
hook.Add("EntityTakeDamage","TurtlenadeDmgHandle",TurtleNadeDamage)
end


they still harm everything they touch though, and arent blue like i had tried to make them. i am out of ideas for this, please help!