# Infinite loop problem-the trials

I’m doing the trials level and I’m fairly sure my code would beat the level(I haven’t seen the third trial) and I keep getting an infinite loop problem when I run the code(It stops while collecting mushrooms trial 1). Please help. Here is my gear:
3503 health
deflector
boss star 3
long sword
softened leather boots
engraved wrist watch
programmaticon IV
twilight glasses
sapphire sense stone
Here is my code:

My code-click to expand
``````# This level is intended to be for advanced players. The solution should be pretty complex with a lot of moving parts. It might also be a bit of a gear check unless you use "creative" methods.
# You need to make your way to the first trial (Oasis of Marr) killing enemies along the way. When you reach it, pick all the mushrooms to trigger the trial to begin. If you survive the onslaught, make your way to the next Oasis for the second trial, then the Temple. When all trials are complete you will have to face the final boss. Good luck!
# HINT: Glasses with a high visual range help tremendously on this level so buy the best you can get.
# HINT: the unit 'type' for the oasis guardians is 'oasis-guardian'
time1 = 90
time2 = 180
time3 = 270
def trial(x, y, stopTime):
hero.moveXY(x, y)
enemy = hero.findNearestEnemy()
while enemy and hero.distanceTo(enemy) <= 50:
hero.attack(enemy)
enemy = self.findNearestEnemy()

item = self.findNearestItem()
while item:
item = self.findNearestItem()
if item:
hero.moveXY(item.pos.x, item.pos.y)

enemy = hero.findNearestEnemy()
item = self.findNearestItem()
while enemy and hero.distanceTo(enemy) <= 50 or hero.time <= stopTime:
enemy = self.findNearestEnemy()
friends =  self.findFriends()
if self.costOf("soldier") <= self.gold:
hero.summon("soldier")
for friend in friends:
hero.command(friend, "defend", hero.pos)
if enemy and self.distanceTo(enemy) < 50:
if self.isReady("cleave"):
self.cleave(enemy)
hero.attack(enemy)
trial(124, 24, time1)
hero.moveXY(14, 31)
trial(11, 111, time2)
trial(114, 123, time3)
``````

I have 6 GB of RAM, I’m using Edge, and my code is in Python.

You should consider, how this loop works if there are no enemies near and no money for summon units.

``````    while enemy and hero.distanceTo(enemy) <= 50 or hero.time <= stopTime:
enemy = self.findNearestEnemy()
friends =  self.findFriends()
if self.costOf("soldier") <= self.gold:
hero.summon("soldier")
for friend in friends:
hero.command(friend, "defend", hero.pos)
if enemy and self.distanceTo(enemy) < 50:
if self.isReady("cleave"):
self.cleave(enemy)
hero.attack(enemy)
``````