Teach me to code! lvl sarven-shepherd

Does the moveXY go in the while loop or the regular loop?
edit:
I did it!

2 Likes

As shown in my sample, it should go in the regular loop.

Why? You use the while loop to go through the enemies one by one, and you use the regular loop to repeat your set of actions until the “end of time” :slight_smile:

If you put the moveXY command in the while loop, you would go to the center after each enemy. However, it’s better to go back only when you finished checking/killing all the enemies on screen…

2 Likes

I won! now I am in cloudrip! (I did mad maxer, clash of clones and those other levels too)

2 Likes

This code isn’t working. Whats the problem. It either says the loop is forever or it’s slow or infinite loop.

loop:
enemies = self.findEnemies()
enemyIndex = 0

# Wrap this logic in a while loop to attack all enemies.
# Find the array's length with:  len(enemies)
while True:
    while enemyIndex < len(enemies):
        enemy = enemies[enemyIndex]
        if enemy.type != "sand-yak":
            while enemy.health < 5:
                self.attack(enemy)
    pass
enemyIndex += 1
# Between waves, move back to the center.
self.moveXY(39, 41)
2 Likes

Your problem is in the while True:, which is an infinite loop. However, it is already inside an infinite loop. Just get rid of that and you should be fine.

2 Likes
  1. Additionally to what ChronistGilver sad, you need to move the enemyIndex+=1 inside the loop.
    The standard why to write a loop that goes over all enemies:
enemyIndex=0
while enemyIndex<len(enemies) :
   #do_something_with enemies[enemyIndex]
   enemyIndex++ 

  1. Didn’t look at the level but:
while enemy.health < 5:

will only attack enemy if he is at a very low health already

2 Likes

Thanks guys… it always helps to have you coders around.

2 Likes

I cant seem to figure out why this is not working, my charcter never attacks or does anything
’’'
while True:

enemies = hero.findEnemies()
enemyIndex = 0

loop:

# Wrap this logic in a while loop to attack all enemies.
# Find the array's length with:  len(enemies)
while enemyIndex < len(enemies):
    enemy = enemies[enemyIndex]
    # "!=" means "not equal to."
    if enemy.type != "sand-yak":
        enemyIndex += 1
        # While the enemy's health is greater than 0, attack it!
        while enemy.health > 0:
            self.attack(enemy)
        pass

# Between waves, move back to the center.
self.moveXY(40, 32)

‘’’

2 Likes

I have an easier code :

2 Likes

This post is 4 months old. Please do not revive dead topics. Also, do not give away correct code as it does not let others learn code, which is the purpose of CodeCombat, but simply let them copy off of others. :slight_smile:

2 Likes

Ok sorry. I didn’t know.

2 Likes

It’s okay, everyone makes mistakes :slightly_smiling_face:

2 Likes