Play Home Contribute Github Join Us! Discourse Staff Members Github Contribution Guides Team

Store hero's position -- Coordinated defense

This is more of a general Python question.

Typing in coordinates is repetitive and annoying, so I’ve been trying to write defs and stuff to avoid having to do it more than I need to, and I noticed something on this level (I’ve not tried this before until now).

If I try to store my hero’s position as a variable using hero.pos; the value in the variable will automatically change as the hero moves without me updating it. I was trying to just grab the hero’s starting position so I could return to it:

start = hero.pos # Trying to store the hero's starting position so he can just walk back to it.
while True:
    # Get an array of enemies.
    enemies = hero.findEnemies()
    # If the array is not empty.
    if len(enemies) > 0:
        # Attack the first enemy from "enemies" array.
        hero.cast("drain-life", enemies[0])
        # Return to the start position.
        hero.moveXY(start.x, start.y)
        hero.say(start) # Hero says their current position, rather than the original position

So… is there a way I can deference the current hero.pos to store that value as a variable?

x = hero.pos.x
y = hero.pos.y
start = {'x': hero.pos.x, 'y': hero.pos.y}

while True:
    if  hero.pos.x < x + 50:
        #  you can attack enemies
        hero.move({'x': start.x + 51, 'y' : start.y})
        # hero.move({'x': x + 51, 'y' : y}) # same
        hero.moveXY(x, y)
        # hero.moveXY(start.x,start.y) # same
# you can not attack when moving with moveXY
# read about deep and shallow copy in internet.
# in CoCo deep copy is generally forbidden

Edit: CoCo is using lodash (javascrirt) and some (not all) of its methods are working both in javascript and the CoCo python. So this code is possible:

start = _.cloneDeep(hero.pos)
# or with Vector.copy()
# start = hero.pos.copy()
while True:
    if  hero.pos.x < start.x + 50:
        hero.move({'x': start.x + 51, 'y' : start.y})
        hero.moveXY(start.x, start.y)

Interesting, thanks for the heads-up about deep and shallow copy.


start = _.cloneDeep(hero.pos)
start = hero.pos.copy()
start = Vector( hero.pos.x, hero.pos.y)
start = {'x': hero.pos.x, 'y': hero.pos.y}
start = JSON.parse(JSON.stringify(hero.pos))

Don’t worry…you only just be xythonized! :stuck_out_tongue_winking_eye: