有没有一种方法可以将完整的代码块定义为变量,作为python上goto函数的替代



这就是我所拥有的。在三个点上(《仁慈的终结》、《逃亡》和《其他》(,我希望它能循环回"表演"菜单。但是我不知道该怎么做。我对编码很陌生,所以我真的很欣赏这些例子。

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.")```

你最好使用一些函数,比如这个:

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()

感谢大家的帮助和支持。只要稍微调整一下,我相信我已经解决了我的问题。这不是最漂亮的代码,但它完成了任务。

HP=20
ATK=5
DEF=2
MHP=40
MATK=5
print("A Monster approaches you!")
while HP>0:
print(" ")
print("Fight, Mercy, Flee, Heal")

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