我对编程非常陌生,我对它感兴趣了一段时间。我目前正在通过zed a艰难地学习python。肖。我来练习31,我试图通过开发一个我的孩子可以玩的小游戏来发展我的技能。我正在尝试将循环插入到我的代码中,这样如果你让游戏结束,它会让你回到顶部。我现在遇到代码第4行的问题。
randomnum = random.randint(0,20)
我收到错误
NameError:name' random'没有定义。
当我在行之前添加def时,它仍然没有运行它。
这是我更新的代码:
print("""Welcome to my game! \nsee if you can complete the task ahead""")
print("You enter a dark cave with a corridor, do you go stealth or charge in?")
randomnum = random.randint(0,20)
stealth = input ("> ")
charge = input ("> ")
if stealth:
print("you see an enemy outpost on your left.")
print("what do you do?")
print("1. continue to sneak past?")
print("2. attack the outpost?")
outpost = input("> ")
if outpost == "1":
print(randomnum)
if randomnum < 11:
print("you're seen and die!")
print("game over!")
else:
print("success! continue to next zone.")
else:
print(randomnum)
if randomnum < 11:
print("you fail and die")
print("game over!")
else:
print("success! you defeat the goblins.\ncontinue to next zone.")
if charge:
print("you see an enemy outpost in front of you.")
print("what do you do?")
print("1. charge with a battle cry?")
print("2. attack from distance?")
outpost = input("> ")
if outpost == "1":
print(randomnum)
if randomnum < 11:
print("you fail your attack and die!")
print("game over!")
else:
print("success! you defeat the goblins.\nContinue to next zone.")
else:
print(randomnum)
if randomnum < 8:
print("you fail and die")
print("game over!")
else:
print("success! you defeat the goblins. \ncontinue to next zone.")
答案 0 :(得分:0)
如果您想检查随机生成的数字是否小于11或大于10,您将使用:
randomnum = random.randint(0,20)
print(randomnum)
if randomnum < 11:
print("you fail and die")
print("game over!")
start()
elif randomnum > 10:
print("success! you defeat the goblins. \ncontinue to next zone.")`
然而,因为数字只能是&lt; 11或&gt; 10,你可以使用else语句:
randomnum = random.randint(0,20)
print(randomnum)
if randomnum < 11:
print("you fail and die")
print("game over!")
start()
else:
print("success! you defeat the goblins. \ncontinue to next zone.")`
答案 1 :(得分:0)
我认为你没有随机输入。
转到您的代码并在第一行下面换一个新行,然后输入&#39;随机导入&#39;
它应该有用!