Search code examples
pythonvariablesgoto

Is there a way to define a full block of code as a variable as a stand in for a goto function on python?


This is what I have. At three points (End of Mercy, Flee, and Else) I want it to loop back to the Act menu. I'm not sure how to do this however. I'm very new to coding so I would really appreciate examples.

ATK=5
DEF=2
MHP=40
MATK=5

print("A Monster approaches you!")
print("Fight, Mercy, Flee")

a=input("Act:")
if a == "Fight":
    MNHP=MHP-ATK
    MHP=MNHP
    print("You hit the enemy for ", ATK, " damage!")
    print("Enemy HP remaining: ", MHP)
elif a == "Mercy":
    print("You tried to spare the enemy...")
    if(MHP<15):
        print("You won!")
        print("You gained 0 EXP and 5 G")
    else:
        NHP=HP-MATK
        HP=NHP
        print("But the Monster wasn't weakened enough.")
        print("You lost ", MATK, "HP. HP remaining: ", HP)
elif a == "Flee":
    print("You tried to flee... But the overworld is missing.")
else:
    print("That's not an option.")```

Solution

  • You'd better to use some functions, like this one:

    def battle(ATK=5, DEF=2, MHP=40, MATK=5, HP=20):
        print("A Monster approaches you!")
        print("Fight, Mercy, Flee")
    
        action = input("Act: ")
        if action == 'leave':
            # leave the dungeon
            return False
    
        if action == "Fight":
            MHP -= ATK
            print("You hit the enemy for ", ATK, " damage!")
            print("Enemy HP remaining: ", MHP)
        elif action == "Mercy":
            print("You tried to spare the enemy...")
            if MHP < 15:
                print("You won!")
                print("You gained 0 EXP and 5 G")
            else:
                HP -= MATK
                print("But the Monster wasn't weakened enough.")
                print("You lost ", MATK, "HP. HP remaining: ", HP)
        elif action == "Flee":
            print("You tried to flee... But the overworld is missing.")
        else:
            print("That's not an option.")
        # return True to keep fighting
        return True
    if __name__ == '__main__':
        fight = True
        while fight:
            fight = battle()