问题描述
我是 python 编程的新手,我正在尝试做一个简单的命令行游戏。 基本上,命令行要求输入一个从 1 到 3 的数字,用户给出该数字,然后命令行将其与随机数进行比较并决定获胜者是否通过,如果他通过了洞,事情会重复直到他错过了数字. 我的问题是为下一次更新随机数! 每次命令行将它与用户的号码进行比较时,我都需要一个新的随机数。
这是我的代码:
#!/usr/bin/env python
#ChooseADoor
from random import randint
import time
import sys
print("Welcome mortal, to the Choose a door game...")
Score = 0
StrScore = str(Score)
#DeathDoor = 0
#DeathDoor = randint(1,3)
tutorialRequired = input("Would you like to go through the tutorial? (YES / NO): ")
if tutorialRequired == "YES":
print("""Alright mortal, you were kidnaped and you wake up in a room.
There are 3 doors, two of them let you continue,
one of them gives you a painful death...
Yeah, sorry about that...
""")
ready = input("Ready mortal? (YES / NO): ")
if ready =="YES":
print("Starting game in 3...")
time.sleep(1)
print("2...")
time.sleep(1)
print("1...")
time.sleep(1)
print("GO!")
time.sleep(1)
else:
print("Goodbye mortal.")
sys.exit()
else:
print("""Alright smarty pants let's see if you live to tell your story...
""")
ready = input("Ready mortal? (YES / NO): ")
if ready =="YES":
print("Starting game in 3...")
time.sleep(1)
print("2...")
time.sleep(1)
print("1...")
time.sleep(1)
print("GO!")
time.sleep(1)
else:
print("Goodbye mortal.")
sys.exit()
while Score < 10:
print("Three doors ahed... ")
door = input("Pick one (1, 2, 3): ")
doorNum = int(door)
if door in ("123"):
DeathDoor = 0
DeathDoor = randint(1,3)
if DeathDoor == door:
print("End of line, mortal.")
print("You passed", StrScore, ("doors until the endo of your miserable life..."))
break
else:
RandomNum = 0
RandomNum = randint(1,3)
if RandomNum == 1:
print("You're safe for now, mortal. Go on.")
DeathDoor = 0
Score = (Score + 1)
StrScore = str(Score)
print("Score: " + StrScore)
elif RandomNum == 2:
print(" Beginner's luck. Let's see if you laugh next time mortal.")
DeathDoor = 0
Score = (Score + 1)
StrScore = str(Score)
print("Score: " + StrScore)
elif RandomNum == 3:
print(" Keep the fireworks, they may be useful for your funeral. Go on.")
DeathDoor = 0
Score = (Score + 1)
StrScore = str(Score)
print("Score:" + StrScore)
else:
print("Don't try to fool me,")
print("goodbye mortal.")
StrScore = str(Score)
print("You passed " + StrScore + (" doors until the endo of your miserable life..."))
time.sleep(1)
sys.exit()
StrScore = str(Score)
print("Congratulations mortal, you live. For now."))
我究竟做错了什么?
1楼
您实际上每次循环都会获得一个新的随机数。 你的问题在这里:
...
if DeathDoor == door:
...
您正在将一个整数与一个字符串进行比较,它总是产生False
。
正确的方法是
if DeathDoor == int(door)
此外重置RandomNum
和DeathDoor
为零是不必要的。
由于您刚刚开始学习 Python,您应该考虑阅读风格指南。 如果您从一开始就遵循指南中的规则,您的代码将更容易理解(不仅对其他人而且对您而言)。