Code help: getting peasants to collect coins

I’m on the Grim Determination level in Cloudrip, and I’m trying to write a code that has my peasants collecting separate gold coins. There are some great scripts on rather complex methodologies for this, but I’m trying to do something simple (and in Python; if only those threads would’ve been in Python…). Unfortunately, it’s not working. The peasants just stand there.

Sample code:

# In the function commandPeasants():
def commandPeasant(psnt):
    if switch == 0:
        if gc1:
            hero.command(psnt, "move", {"x": gc1.pos.x, "y": gc1.pos.y})
            switch = 1
        else:
            pass
    elif switch == 1:
        if gc2:
            hero.command(psnt, "move", {"x": gc2.pos.x, "y": gc2.pos.y})
            switch = 0
        else:
            pass
    else:
        pass

# Now, in the loop where those variables get defined:
while True:
    coins = hero.findItems()
    gCoins = []
    switch = 0
    for c in coins:
        if c.value >= 3:
            gCoins.append(c)
    if gCoins[0]:
        gc1 = gCoins[0]
    if gCoins[1]:
        gc2 = gCoins[1]
    commandFriends()

Any help is greatly appreciated. (While I’m at it, can anyone tell me if there’s a simpler way to feed coordinated through command? I get errors if I use simple XY parentheses, or anything like gc1.pos.)

1 Like

I’ll give you a little nudge:

def commandPeasant(psnt):
    if switch == 0:
        ... # keep your original code
    elif switch == 1:
        ... # keep your original code
    else:
        hero.say("switch is neither 0 nor 1?!?!?!") # add this line
        pass

What you’ll experience is an issue with scope. In python, variables defined outside of functions can’t be changed inside functions (without a special trick…).

Extra

Comment out the switch = 0 and switch = 1 lines like this and then run it.

def commandPeasant(psnt):
    #global switch
    if switch == 0:
        if gc1:
            hero.command(psnt, "move", {"x": gc1.pos.x, "y": gc1.pos.y})
            # switch = 1 # notice this line is commented out
        else:
            pass
    elif switch == 1:
        if gc2:
            hero.command(psnt, "move", {"x": gc2.pos.x, "y": gc2.pos.y})
            # switch = 0 # notice this line is commented out
        else:
            pass
    else:
        hero.say("switch not defined")
        pass

Although now switch never changes between 0 and 1 in your program now, the peasants can move. Weird, isn’t it?

Python Global Variables

You should generally avoid using global variables unless absolutely necessary.
Here’s extra info to help you get your program running using a global variable in the meantime.


Using gc1.pos works for me.
hero.command(psnt, "move", gc1.pos)

2 Likes