So, this is the level where you need to get more coins than your doppelganger before time runs out.
With the help of the AI query, I was able to write a code that results in success. However, I cannot clearly explain to myself how and why this code works, which I personally believe is something I need to do in my future in programming (if any).
hero.warcry()
while True:
bestCoin = None
maxRating = 0
coinIndex = 0
coins = hero.findItems()
while coinIndex < len(coins):
coin = coins[coinIndex]
rating = coin.value / hero.distanceTo(coin)
if rating > maxRating:
bestCoin = coin
maxRating = rating
coinIndex += 1
if bestCoin:
if hero.isReady("warcry"):
hero.warcry()
elif not hero.isPathClear(hero.pos, bestCoin.pos):
hero.say("Can't get there")
else:
hero.move(bestCoin.pos)
I’m especially curious as to why the need to assign a “maxRating” variable, the “rating” variable, and then comparing them in an if statement.
Is it to stop the while coinIndex < len(coins) loop that keeps looking through the coins array?
Why the need to assign the “maxRating” as the new “rating”? What purpose does it serve afterward? Does it stop the while loop it’s currently in?
Why divide the coin.value by the hero.distanceTo(coin) to get the “rating”? What does this determine?
After the code block inside the if bestCoin: statement is executed, is the code running back to the beginning of the while True: statement? If yes, does the values of all the variables reset because it’s written that way?
bestCoin = None
maxRating = 0
coinIndex = 0
coins = hero.findItems()
I’m going crazy on this for two days now, and I don’t want to move on from this level until I can clearly explain to myself how and why this code works, and made sure I can explain it to others.
EDIT: Any insight or example on how can this be applied to actual Python projects or scenarios is welcome or how it’s useful in any way is welcome.
Help!