Steelclaw Gap - Need Help Understanding Level - Python

Hi, I just completed the level Steelclaw Gap. I was able to complete it by getting help from various forum posts, but I don’t understand what the code is doing and how/why it works. Usually when I need to turn to the forums, I am able to understand what I was doing wrong. However, for this level I couldn’t understand what others were saying in their explanations. Here is my code:

defendPoints = [{"x": 35, "y": 63},{"x": 61, "y": 63},{"x": 32, "y": 26},{"x": 64, "y": 26}]

summonTypes = ["soldier","soldier","soldier","soldier","archer","archer","archer","archer"]

# You start with 360 gold to build a mixture of soldiers and archers.
# self.built is an array of the troops you have built, ever.
# Here we use "len(self.built) % len(summonTypes)" to wrap around the summonTypes array
def summonTroops():
    type = summonTypes[len(hero.built) % len(summonTypes)]
    if hero.gold >= hero.costOf(type):
        hero.summon(type)

def commandTroops():
    friends = hero.findFriends()
    for i in range(len(friends)):
        friend = friends[i]
        # Use % to wrap around defendPoints based on friendIndex
        defPoint = defendPoints[i % len(defendPoints)] 
        # Command your minion to defend the defendPoint
        hero.command(friend, "defend", defPoint)

while True:
    summonTroops()
    commandTroops()

I am mainly confused about lines 9 and 18. Could someone try to explain what exactly the code is doing and why it works? Thanks.

Let’s see if this helps…The first time that line 9 in summonTroops runs, the hero has built (summoned) nothing. So, to translate the line, it would read:

type = summonTypes[len(hero.built) % len(summonTypes)]
or
type = 0 % 6

Which is of course zero. This equates to summonTypes[0], or “soldier”. Hero then builds 1 soldier, which increments the hero.built count by 1. Therefore, the next time summonTroops is called, it would then be:

type = 1 % 6

Which equals 1, so type now equals summonTypes[1]…

2 Likes

Ok. So basically the way that the modulo operator is used in this level is just another way to increment/cycle through an array?

In a way, yes.

For example, what happens if the hero happens to have built 10 items? Which one would you select from the list of 6? Think of it as 10 % 6 = ?

2 Likes

It would be the 4th item because once 6 items are built, it loops back to the start of the array, right?

Exactly. That’s why it’s “kind of” iterating through a list. If your counter goes over (is larger than the length of the list), it simply starts at the beginning again.

2 Likes

Ok, thank you so much!

2 Likes

This topic was automatically closed 12 hours after the last reply. New replies are no longer allowed.