【发布时间】:2019-12-06 22:46:37
【问题描述】:
我正在尝试用 Python 制作类似于 Mastermind 的游戏,但使用数字 [1-9] 而不是颜色。然而,游戏需要有点复杂,这就是我苦苦挣扎的地方。我希望能够在 [0-9] 之间随机生成 5 位密码,并让用户有 10 次尝试才能正确使用它。如果他们猜对了一个数字,我想告诉他们它在列表中的哪个位置,并要求他们继续前进。到目前为止,我有这个:
import random
random_password = [random.randint(0,9) for i in range (5)]
for counter in range (10):
guess = input ("Crack the Mastermind code ")
if guess != random_password :
print ("Guess again ")
#Here I am trying to make it find out if it has a didgit correct, tell them where
#and ask the them to keep guessing. once count runs out, I want it to say they lost
elif guess
else print ("Sorry, you lose :( ")
if guess == random_password :
print ("Congrats, you win! ")
感谢溢出兄弟的任何帮助,我迷路了。我知道我需要它来访问列表中的项目。会使用像 append 这样的函数吗?
编辑:这是我的新代码。 Sorta 有效,但是即使我猜对了数字,我的输出现在也显示它是错误的。它希望我输入 '' 和 , 来分隔列表,但我不应该让用户这样做来使游戏功能。
import random
random_password = [str (random.randint(0,9)) for i in range (5)]
for counter in range (10):
guess = input(str ("Crack the Mastermind code ") )
if guess != random_password :
print ("Guess again ")
#Here I am tryin to make it find out if it has a didgit correct, tell them where
#and ask the them to keep guessing. once count runs out, I want it to say they lost
for i in random_password:
if(i in guess):
print (i)
if guess == random_password :
print ("Congrats, you win! ")
else :
print ("Sorry, you lose :( the correct answer was.... ")
print (random_password)
【问题讨论】:
-
将问题分解成更小的部分,并用文字描述解决问题所需的步骤。例如,“让它找出它是否有一个正确的数字”需要从数字中获取数字。弄清楚如何做到这一点。这是返回数字列表的函数
def get_digits(n)的理想候选者。
标签: python