# Sand Snakes Level Problem (Python)

#1

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

loop:
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?

#2

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…

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

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

1 Like
#4

How does this not work.

while True:
coins = hero.findItems()
coinIndex = 0
nearest = None
nearestDistance = 9999
# Loop through all the coins to find the nearest one.
while coinIndex < len(coins):
coin = coins[coinIndex]
coinIndex += 1
distance = hero.distanceTo(coin)
# If this coin's distance is less than the nearestDistance
if coin.distance < nearestDistance:

# Set nearest to coin
nearest = coin
# Set nearestDistance to distance
nearestDistance = distance
hero.moveXY(nearest.pos.x, nearest.pos.y)
# If there's a nearest coin, move to its position. You'll need moveXY so you don't cut corners and hit a trap
hero.moveXY(nearest.pos.x, nearest.pos.y)

#5

First, the line after nearestDistance = distance shouldn’t be there. You’re telling your hero to move twice.

You’ve defined the variable, “nearest,” but you’re not checking to see if nearest: before trying to move there. You should always check to make sure that an object exists before acting on the object. In this case it should work because nearest always exists but don’t count on that. Just get in the habit of putting if statements first.

if object:
do something with object