What is wrong with my code? Python, Sand Snakes

I can’t figure out why this is not working

loop:
    coins = self.findItems()
    coinIndex = 0
    nearest = None
    nearestDistance = 9999

    # Loop through all the coins to find the nearest one.
    while coinIndex < len(coins):
    # while the coinindex (0) is less than the number of coins
        coin = coins[coinIndex]
    # coin is the items in the coinindex
        coinIndex += 1
    # add 1 to the coinindex
        distance = self.distanceTo(coin)
    #the distance is my distance to the items in the coin index
        if distance < nearestDistance:
    # if my distance to the coin is less than the nearest distance
            nearest = coin
    # nearest becomes the items in the coinindex
            nearestDistance = distance
    #nearestdistance becomes the distance to the coins in the coin index
            if nearest:
    #if theres an item in the coin index
                self.moveXY(nearest.pos.x, nearest.pos.y)
        #move to the item

If you move to nearest while you’re inside the while-loop, You’re just going to move to the first coin that gets assigned to nearest. Move the part where you move to the nearest coin outside the while-loop.

1 Like

Can someone explain this statement?

My understanding of this code is that the while-loop is going through all of the coins in the level, and isolating the one closest to the hero.

So nearestdistance is the distance between the hero and the closest coin.
Wouldn’t “if distance == nearestDistance:” make it so that the nearest coin is selected? How can any coin be closer than the nearest coin?

I predict I’m misunderstanding what nearestDistance means, and probably other concepts.

Cheers

if when you use the distance function - if what it returns is lower than your variable nearestDistance…currently 9999, from the top of your code… then do what ever follows