# [SOLVED] Sand Snakes

I still beat it without flags.

1 Like

@Ironhead All Gamestack is saying is that he wants to learn the point of the lesson. There are many levels that you can just beat with flags, however the point of the lesson is missed.

@Gamestack - the code I can see looks fine, although you define distance in line 10 but don’t use the variable in line 12. I can’t see if it’s there, but you need an “if nearest” conditional inside your loop to tell your guy to move to the nearest coin. The comments on line 18 are the instructions for the remaining code.

1 Like
``````loop:
coins = self.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 = self.distanceTo(coin)
# If this coin's distance is less
while coinIndex < len(coins):
# Set nearest to coin
nearest = coin
# Set nearestDistance to distance
nearestDistance = distance

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

``````

That’s my new code. ;-;

He walks in place without going to the coins.

@Chaboi_3000 summoned

You have not defined nearest.

1 Like

You said that nearest equals none, yet you call on it when you want to move to the nearest coin, when nearest does not have a value, as u defined it.

1 Like
``````loop:
coins = self.findItems()
coinIndex = 0
nearestDistance = 9999
# Loop through all the coins to find the nearest one.
while coinIndex < len(coins):
coin = coins[coinIndex]
coinIndex += 1
distance = self.distanceTo(coin)
# If this coin's distance is less
while coinIndex < len(coins):
# Set nearest to coin
nearest = coin
# Set nearestDistance to distance
nearestDistance = distance

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

``````

My character isn’t moving.

The two indicated lines are identical. The second one is wrong and doesn’t belong there.

In the first one, you are iterating through the array of coins and incrementing by one. You then define distance but never use this variable.

In the second line, you should have a conditional statement comparing each coin’s distance to nearestDistance to see if it’s less than nearestDistance. You then properly redefine nearestDistance as distance.

Other than the line where you see the second red arrow, your code is fine.

1 Like

There’s also a mistake in your logic. You need two separate steps:

1. Loop through all the coins to find the nearest
2. THEN move to the nearest
2 Likes

1 Like

2 Likes