I have completely redone the worm’s code from scratch, since he was still too buggy. But now he is perfect, at least his behavior. Also I have made his map, appropriately titled “Worm’s den”.
I would have posted his pseudo-code, but he is still missing something: the part of the code that tells him to run the script after his death (which is more complicated, since he’s a multi-piece npc).
[EDIT]: Here is his pseudo (pre-assembled) code: Worm Pseudo Code