DIamond Dozen Python Issue

def findMostHealth(enemies):
    target = None
    targetHealth = 0
    enemyIndex = 0
    while enemyIndex < len(enemies):
        enemy = enemies[enemyIndex]
        if enemy.health > targetHealth:
            target = enemy
            targetHealth = enemy.health
        enemyIndex += 1
    return target

def findOptimalCoin(coins):
    coinIndex = 0
    coinValue = 0
    coinDistance = 0
    Optimalcoin = 0
    while len(coins) > coinIndex:
        coin = coin[coinIndex]
        if coin.value/hero.distanceTo(coin) > Optimalcoin:
            coinDistance = hero.distanceTo(coin)
            coinValue = coin.value 
            Optimalcoin = coinValue/coinDistance
        coinIndex += 1
    return Optimalcoin

while True:
    enemies = hero.findEnemies()
    enemy = findMostHealth(enemies)
    if enemy and enemy.health > 15:
        while enemy.health > 0:
        coins = hero.findItems()
        coin = None
        coin = findOptimalCoin(coins) # ∆ Uncomment this once you've written the function.
        if coin:
            hero.moveXY(coin.pos.x, coin.pos.y)

I keep getting an error in the while loop line of the findOptimalCoins function.

“Type error: can’t acces get 0 of that type: undefined”


You have:

coin = coin[coinIndex]

So with coinIndex starting at zero:

coin = coin[0]

What it’s trying to tell you is that you cannot access the first element of an array, of an undefined variable. coin hasn’t been defined yet. You’re probably missing an s.


I looked at this a dozen times telling myself that it wasn’t going to be a spelling error. lol.

Now I am having another error. " ‘pos’ was null. Use a null check before accessing properties. Try if pos: " and it says this is happening on line 33 where the while True loop starts. but has coin=findOptimalcoin(coins) function, that is inside the while true loop, highlighted green.