[SOLVED] Uneasy Truce Python Help

Hi again everyone. Second post. I am having a problem with Uneasy Truce. The link is https://codecombat.com/play/level/uneasy-truce My code is

# Summon one soldier for every ogre to the south of you!
# Don't count the ogres to the north!

# Accept an array of units as the parameter.
# Return only the units to the south of the hero.
def findSouthernUnits(units):
    southernUnits = []
    for unit in units:
        if unit.pos.y < hero.pos.y:
            # Add the unit to the array with: append()
            southernUnits.append(unit)
    return southernUnits


while True:
    friends = hero.findFriends()
    enemies = hero.findEnemies()
    # Use findSouthernUnits to get enemies to the south.
    findSouthernUnits(enemies)
    # If there are more ogres south of you than friends.
    if findSouthernUnits > friends:
        # Then summon another "soldier".
        hero.summon("soldier")

but it just keeps summoning as many soldiers as I can. What am I doing wrong?

One detail to review, you are calling the function findSouthernUnits properly, but not assigning it to a variable. Also, keep in mind how you count the list of enemies in the two array variables, including the new variable for the function so you can compare if there are more southern units than friends.

3 Likes

So I would do

numSouthernUnits = findSouthernUnits(enemies)

instead of just

findSouthernUnits

But are you saying that I should make another function to summon more soldiers if the number of southern units is greater than the number of soldiers

You’ve got the first bit right @CryptiCrystal,

This is exactly right. Whenever you call a function that “returns” something, you need to store the function’s value in a variable.
What @brooksy125 (welcome back! :grin: :tada:) is saying here:

Is how you go about comparing the lengths of the arrays numSouthernUnits and friends. You can only compare single things like 5, or “hello” with the > operator, or indeed any comparative operator like >, <, ==, !=. You can’t compare whole arrays which are full of different values. There’s something you add on to the end of an array which contains the length of the array… I hope that helps you remember.
Danny

3 Likes

So I need to make a for loop with the lengths of numSouthernUnits and friends so we can compare the number of items in each array?

It would be possible to count the amount of units in each array with something like:

count = 0
for item in array:
    count += 1

However, there is a nifty function you can use: len().
Put an array inside it’s brackets and it will contain the value of the array.
e.g.

if len(enemies) > 100:
    hero.say("Retreat!")
2 Likes

I got it! Thanks for the help. I was using the len() function to find the lengths of the arrays, then compared the lengths rather than just the arrays.

2 Likes

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