Sand Snakes Level Problem (Python)


Hey! I’m really stuck with this level. Here is my code:

    coins = self.findItems()
    coinIndex = 0
    nearest = None
    nearestDistance = 9999
    while coinIndex < len(coins):
        coin = coins[coinIndex]
        coinIndex += 1
        distance = self.distanceTo(coin)
    if distance < nearestDistance:
        nearest = coin
        nearestDistance = distance
    if nearest:
        self.moveXY(nearest.pos.x, nearest.pos.y)

My hero just runs into the mine. That’s the problem?


Hello @Vollut and welcome to the forums! Feel free to reuse existing topics (related to this level) to ask your question next time.

What your code currently does is that it goes through the list of coins and calculates their distance. Once that is finished(!), it compares distance with nearestDistance. However, at this point distance holds the value of the distance of the last coin…

So what do you need to fix it?

You should check the distance inside the while block, so you check it for every coin, not only the last one…

# define variables
    while ...
        # get coin distance
        if distance < nearestDistance:
            # set nearestCoin and nearestDistance
    if nearest:
        # move to coin


Oh, now I get it! Thank you! Now it works