我的程序应该在变量等于或小于0时停止,但是当程序运行时,如果变量大于0,代码将重置。
这是我的代码: Main.py
import random
import os
import sys
global foodamount
foodamount = random.randint(1,10)
answer = str(input(("Right or Left")))
if answer == "Right" or answer == "right":
#Check if foodamount is greater than 1, then if it is run cave.py
foodamount = foodamount -1
if foodamount < 1:
print("You ran out of food. You lose")
sys.exit()
if foodamount > 0:
os.system('python cave.py')
这是cave.py
import random
import sys
import os
import main
print("Do you want to attack?")
attak = str(input(("Yes or No")))
if attak == "Yes" or attak == "yes":
x = random.randint(1,2)
if x == 1:
os.system('python attack')
if x == 2:
print("You lose")
sys.exit()
if attak == "no" or attak == "No":
print("Do you leave the cave or go around the spider?")
y = str(input("Leave or Around"))
if y == "Leave" or y == "leave":
main.foodamount = main.foodamount -1
if main.foodamount < 1:
print("You ran out of food. You lose")
sys.exit()
else:
os.system('python test')
&#13;
当我在python中运行它时,程序从头开始,程序从头开始重新启动。
如果您能提供帮助,我们将不胜感激。
答案 0 :(得分:1)
您的程序重新启动,因为导入错误。我不确定正确的输出应该是什么,但是我解决了你的代码,所以在做它应该做的事情之前它没有重新启动。我希望这有帮助。最后,您需要将两个文件放在同一目录中才能使用它们。
Main.py
import random
import os
import sys
import cave
foodamount = random.randint(1,10)
def main():
global foodamount
answer = str(input(("Right or Left")))
if answer == "Right" or answer == "right":
#Check if foodamount is greater than 1, then if it is run cave.py
foodamount = foodamount -1
if foodamount < 1:
print("You ran out of food. You lose", foodamount)
sys.exit()
elif foodamount > 0:
os.system('python cave.py')
main()
cave.py
import random
import sys
import os
from Main import *
print("You are in a cold section of the cave")
print("You see a spider in front of you")
print("Do you want to attack?")
attak = str(input(("Yes or No")))
if attak == "Yes" or attak == "yes":
x = random.randint(1,2)
if x == 1:
os.system('python attack')
if x == 2:
print("You lose")
sys.exit()
if attak == "no" or attak == "No":
print("Do you leave the cave or go around the spider?")
y = str(input("Leave or Around"))
if y == "Leave" or y == "leave":
foodamount = foodamount -1
if foodamount < 1:
print("You ran out of food. You lose")
sys.exit()
else:
os.system('python test')
答案 1 :(得分:0)
如果满足某些条件,您似乎编写了一个在最后运行的脚本。不要这样做。相反,编写一个实现游戏逻辑的函数,并在“while”循环中运行该函数,如下所示:
def play_game():
if the player dies:
return False
return True
while play_game():
pass