ID:1956780
 
(See the best response by Kozuma3.)
Code:
    zombie
New()
src.blood = 500
src.AI()
proc
AI()
while(src)
for(var/mob/player/M in view(0))
sleep(50)
var/dmg = rand(50,200)
M.blood -= dmg


Problem description:
Can anybody give me a tip on why this piece of code is lagging my entire project?
Whenever I disable it the game runs just fine, but with it, it's like running Crisis 3 on a 1980 laptop

Is the loop running infinitely and thus lagging the game ?

You're not only creating an infinite loop for every zombie mob you place on the map, but your for() loop won't ever return much, 0 tiles would be the same tile the mob is on.

Ideally, when doing AI you'd do something that causes the AI to trigger when players move into view, as opposed to having them constantly checking for targets.
Your loop needs a proper delay, as the sleep() inside that for() loop isn't the right way to do it.

Secondly, I'm not even sure what the point of that for() loop is, but I'm guessing it'd be better off somewhere else and not in the AI loop.

Lastly, your zombie/New() should be calling the parent proc ..() and, at the very least, using spawn() on the AI loop so that New() can finish. You'd probably be better off using the waitfor setting though:

proc
AI()
set waitfor = 0
// loop stuff...
Your sleep call is only occurring when it finds a player in view(0), which I'm assuming isn't happening most of the time. So it's just doing an infinite loop with no delay. Put sleep(50) in your while loop, not your for loop.

There are other things you can do to make a more efficient AI, but this is probably your issue.
Best response
You can modify this to fit your needs, but this is a simpler version of how I handle large amounts of zombies in my past projects ;3

world
mob = /mob/player

var/list/players = list()

mob/player/Login()
global.players |= src
mob/player/Logout()
global.players -= src
mob/player/Move()
. = ..()
for(var/mob/NPC/NPC in ohearers())
if(!NPC.active)
spawn(0.1)NPC.AI()

mob/NPC
var
active = FALSE
mob/target = null
proc/AI()
Zombie
AI()
active = TRUE
var/list/Container = list()
for(var/mob/player/PLAYER in ohearers())
Container |= PLAYER
target = pick(Container)
if(target)
while(target && get_dist(src,target) <= 7)
step_towards(src,target)
sleep(10)
target = null
active = FALSE
In response to Kozuma3
That's a neat little method of handling AI, but two suggestions:

1) Make sure you use . = ..() instead of ..() alone in Move(), since the proc is expected to return a value.

2) Call ..() before the NPC loop, not after, so you're alerting NPCs in your new location instead of the old one.
Thank you so much. All answers resulted in learning and productivity. The issue has been fixed