我正在尝试为我的comp-sci类编写游戏代码。但是,当我到达一个指示攻击敌人的功能时,即使该功能完成后,它也会回到顶部,而不是继续执行代码。 (忽略了毫无意义的for循环,我只需要在代码中添加一个)就已经尝试了很多东西,但我仍然无法使其工作。
lives = 3
primary = "Rusty Sword"
armor = "Old Armor"
damage = 2
luck = 3
defense = 1
defchance = 3
enemynumber = 0
print("\nYou begin your trek through the dense forest and you stumble accross a skeleton!\nThe skeleton has",enelives1,"lives.\nYou currently have",lives,"lives.")
print("\nInventory:\n"+primary+"-",damage,"Damage\n"+armor+"-",defense,"Defense")
aord = input("\nThe skeleton is coming towards you! Do you attack it or defend first?\n")
aord = aord.lower()
while aord != "attack" and aord != "defend":
print("Invalid input")
print("Would you like to attack or defend?")
aord = input("\nThe skeleton is coming towards you! Do you attack it or defend first?\n")
def attack1():
hit = random.randint(1,luck)
print("In order to attack the skeleton you must correctly guess a number from 1 to",luck+2,".")
attackguess = int(input())
guessnumber = 1
global enelives1
global lives
while lives >= 3 and (guessnumber == 1 or guessnumber == 2):
while guessnumber == 1:
if attackguess > hit:
print("Too high. One more chance.")
guessnumber = 2
elif attackguess < hit:
print("Too low. One more chance.")
guessnumber = 2
else:
enelives1 = enelives1 - damage
print("You hit the skeleton! It now has",enelives1,"lives.")
guessnumber = 3
while guessnumber == 2:
attackguess = int(input())
if attackguess == hit:
enelives1 = enelives1 - damage
print("You hit the skeleton! It now has",enelives1,"lives.")
guessnumber = 3
global aord
aord == "defend"
if lives >= 1 and guessnumber == 2:
print("You missed the skeleton! It is now about to swing at you!")
aord = "defend"
elif lives < 1:
print("Oh no! You ran out of lives and died! Press enter to end the program")
input()
quit()
while enelives1 >= 1:
if aord == "attack":
attack1()
elif aord == "defend":
defend1()
答案 0 :(得分:0)
我并没有真正地通过代码来理解它,但是乍一看,我认为这与以下事实有关:您根本不会改变生命的价值,却退出了while循环取决于生命的价值。
答案 1 :(得分:0)
函数未退出的原因是while循环中的guessnumber。如果您在第二次猜测中并且猜对了,您将按预期输入if语句以获得成功并退出。但是,如果您第二次猜错了,您将被困在while循环中,因为guessnumber仍然等于2。因此,保持while循环运行的条件仍然成立。为了解决不存在的问题,如果他们弄错了第二个猜测,则需要像下面这样更改guessnumber的值(除1外的任何值):
while guessnumber == 2:
attackguess = int(input())
if attackguess == hit:
enelives1 = enelives1 - damage
print("You hit the skeleton! It now has" ,enelives1, "lives.")
guessnumber = 3
global aord
aord == "defend"
else:
guessnumber = 0 #this will allow while loop to break
现在,如果您更改支票的值,它应该可以:
if lives >= 1 and guessnumber == 0: