This is the code given for the problem im currently on. I have no problem solving this problem the way they want it but I wanted to change the code.
‘’‘
while True:
enemy = hero.findNearestEnemy()
if enemy:
hero.attack(enemy)
if enemy.health <= 0:
defeated += 1
if hero.now() > 15:
break
’’’
Is their any reason why I can not put the hero.now() function for the condition of a while loop? How can the if statement use it if the while cant? When I try and run this code it says my program is running slow or theirs an infinite loop. I dont really understand how the hero.now() function works. Its supose to return a number. Thats why im assuming it works fine in the if statement. I dont need a correction to the solution I just want to know why im getting an infinte loop.
‘’‘
while hero.now() < 15:
enemy = hero.findNearestEnemy()
if enemy:
hero.attack(enemy)
if enemy.health <= 0:
defeated += 1
’’’
This is the code given for the problem im currently on. I have no problem solving this problem the way they want it but I wanted to change the code.
while True:
enemy = hero.findNearestEnemy()
if enemy:
hero.attack(enemy)
if enemy.health <= 0:
defeated += 1
if hero.now() > 15:
break
Is their any reason why I can not put the hero.now() function for the condition of a while loop? How can the if statement use it if the while cant? When I try and run this code it says my program is running slow or theirs an infinite loop. I dont really understand how the hero.now() function works. Its supose to return a number. Thats why im assuming it works fine in the if statement. I dont need a correction to the solution I just want to know why im getting an infinte loop.
while hero.now() < 15:
enemy = hero.findNearestEnemy()
if enemy:
hero.attack(enemy)
if enemy.health <= 0:
defeated += 1
Ive read the post. Thanks. I see why waiting could help. I guess loops essentially are iterating super fast and thats why im slowing down. While I dont have an item to use wait. This article really did help me understand what was happening. Much appreciated.
Wow the very next problem says “Make sure your always doing something in a while-loop or you might get an infinite loop error.” Maybe put that statement a bit sooner for the ambitious coders that want to implement a different method. Look they even put in an event so an infinite loop doesnt occur.
while defeatedOgres < 6:
enemy = hero.findNearestEnemy()
if enemy:
hero.attack(enemy)
defeatedOgres += 1
else:
hero.say("Ogres!")