Grim Determination problem

Hello!I have a problem with healing paladins in this level.I saw, that in other posts people did not have problems with the simular code as mine.
So here is my code:

# Твоя цель - защитить Рейнальдо.
# Найди паладина с самым низким здоровьем.
def lowestHealthPaladin():
    lowestHealth = 99999
    lowestFriend = None
    friends = hero.findFriends()
    for friend in friends:
        if friend.type != "paladin":
            continue
        if friend.health < lowestHealth and friend.health < friend.maxHealth:
            lowestHealth = friend.health
            lowestFriend = friend
    return lowestFriend
def commandPeasant(friend):
    item = friend.findNearestItem()
    if item:
        hero.command(friend, "move", item.pos)
def commandGriffin(friend):
    enemy = friend.findNearestEnemy()
    if enemy:
        hero.command(friend, "attack", enemy)
def commandPaladin(paladin):
    # Вылечи паладина с низким здоровьем, используя `lowestHealthPaladin()`
    # Ты можешь использовать `paladin.canCast("heal")` и `command(paladin, "cast", "heal", target)`
    # Паладины также владеют щитом: `command(paladin, "shield")`
    # И не забудь, что они тоже умеют атаковать!
    paladin = hero.findNearest(hero.findByType('paladin'))
    enemy = paladin.findNearestEnemy()
    lowestFriend = lowestHealthPaladin()
    if lowestFriend and paladin.canCast("heal"):
        hero.command(paladin, "cast", "heal", lowestFriend)
    if enemy:
        hero.command(paladin, "attack", enemy)
    pass
def commandFriends():
    # Управляй своими союзниками.
    friends = hero.findFriends()
    for friend in friends:
        if friend.type == "peasant":
            commandPeasant(friend)
            pass
        elif friend.type == "griffin-rider":
            commandGriffin(friend)
            pass
        elif friend.type == "paladin":
            commandPaladin(friend)

while True:
    commandFriends()
    # Призывай наездников!
    if hero.gold >= hero.costOf("griffin-rider"):
        hero.summon("griffin-rider")

The paladins don’t heal each other.
Here is the screenshot of the error:


I use the russian CodeCombat, but you can reply in any language.

Hi Anonym,

Your code mostly looks good.

Take out this line (line 27), as you want to command the paladin that you’re feeding into the function, which isn’t necessarily the nearest one:

Suggest you also target the Warlocks and try to kill them first; and try to find a way of making the peasants collect different coins…

Jenny

1 Like

Thank you for your help.But could you please tell me about the values of different coins?

Well, I think Jenny meant either: (correct me if I’m wrong @jka2706) a) you should use code like in ‘misty island mine’ (if you’ve done that level yet) which makes the peasant avoid going to the same coin, or b) use a findBest coin function with distance/value.
Danny

3 Likes

Thank you.Could you please send me a link to the level, as I can’t find it?


Danny

Thanks a lot!I haven’t finished yet, so I don’t mark as solved.

From my experience 80% pass this level with WRONG code - i’m checking the leader board if the given advice is followed but usually i had wasted my time typing answers…
This will never ever work as intended.

    if lowestFriend and paladin.canCast("heal"):
        hero.command(paladin, "cast", "heal", lowestFriend)
    if enemy:
        hero.command(paladin, "attack", enemy)

How to write the function and why the above code will not work you’ll find using search:

grim determination  @xython with:images
4 Likes

Hello! So my peasants are collecting the best coins, paladins(seem to be!) healing each other, but they
can’t get to warlocks through the horde of skeletons.So the warlocks destroy everything!
My code:

# Твоя цель - защитить Рейнальдо.
# Найди паладина с самым низким здоровьем.
def lowestHealthPaladin():
    lowestHealth = 99999
    lowestFriend = None
    friends = hero.findFriends()
    for friend in friends:
        if friend.type != "paladin":
            continue
        if friend.health < lowestHealth and friend.health < friend.maxHealth:
            lowestHealth = friend.health
            lowestFriend = friend
    return lowestFriend
def commandPeasant(friend):
    def findBestItem(friend, excludedItems):
        items = friend.findItems()
        bestItem = None
        bestItemValue = 0
        for item in items:
            # Используй `in` для проверки вхождения элемента в массив `excludedItems`.
            # В этом случае пропусти предмет, другой крестьянин уже нацелился на него.
            if item in excludedItems:
                continue
            # Закончи функцию!
            # Помни, что `bestItemValue` должно вычисляться как максимальное `item.value / distanceTo`
            if item.value / friend.distanceTo(item) > bestItemValue:
                bestItem = item
                bestItemValue = item.value/friend.distanceTo(item)
        return bestItem
        bestCoin = findBestItem
    claimedItems = []
    item = findBestItem(friend, claimedItems)
    if item:
        hero.command(friend, "move", item.pos)
        claimedItems.append(item)
def commandGriffin(friend):
    enemy = friend.findNearestEnemy()
    if enemy and enemy.type == 'warlock':
        hero.command(friend, "attack", enemy)
    else:
        hero.command(friend, "attack", enemy)
    
def commandPaladin(paladin):
    # Вылечи паладина с низким здоровьем, используя `lowestHealthPaladin()`
    # Ты можешь использовать `paladin.canCast("heal")` и `command(paladin, "cast", "heal", target)`
    # Паладины также владеют щитом: `command(paladin, "shield")`
    # И не забудь, что они тоже умеют атаковать!
    enemy = paladin.findNearestEnemy()
    lowestFriend = lowestHealthPaladin()
    if lowestFriend and paladin.canCast("heal"):
        hero.command(paladin, "cast", "heal", lowestFriend)
    if enemy and enemy.type == 'warlock':
        hero.command(paladin, "attack", enemy)
    else:
        hero.command(paladin, "attack", enemy)
    pass
def commandFriends():
    # Управляй своими союзниками.
    friends = hero.findFriends()
    for friend in friends:
        if friend.type == "peasant":
            commandPeasant(friend)
            pass
        elif friend.type == "griffin-rider":
            commandGriffin(friend)
            pass
        elif friend.type == "paladin":
            commandPaladin(friend)

while True:
    commandFriends()
    # Призывай наездников!
    if hero.gold >= hero.costOf("griffin-rider"):
        hero.summon("griffin-rider")

I’m sorry to disappoint you but unfortunately your paladins aren’t healing. At least after the first enemy appears. I think this is what xython is saying. Take a look at your code:

if lowestFriend and paladin.canCast("heal"):
        hero.command(paladin, "cast", "heal", lowestFriend)
if enemy and enemy.type == 'warlock':
        hero.command(paladin, "attack", enemy)

It has the same problem as before. If there are two if statements and both are true, only the last one will run. So how do we prioritise the healing over the attacking? To only do the attacking if the first if is not true, but the conditions on the second if are true.
If you fix that you get instant success, but there are other bits of your code that don’t work: like the peasant excluded items bit. They still go for the same items.
Danny

2 Likes

Thanks a lot to everyone!I finally passed this level!

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