【问题标题】:Making a game like Mastermind in Python用 Python 制作像 Mastermind 这样的游戏
【发布时间】: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


【解决方案1】:

快速完成此操作的一种方法是创建一个小函数,该函数将检查您的任何字符串答案(来自输入)是否与密码列表中的任何字符匹配

我还更改了您的条件语句的顺序,使其更加清晰和高效。

最后,我将您的 random_password 从 LIST 更改为 STRING,因为这样您就可以正确猜测 == random_password。

希望对你有帮助!

PS:

如果您使用 Python2.X,则应将输入更改为 raw_input(以获取字符串值),否则如果您使用 Python3.X,请保持这种方式

import random

def any_digits(guess,password):
    for character in guess:
        if character in password:
            return True
    return False

random_password = ''.join([str(elem) for elem in [random.randint(0,9) for i in range (5)]])

print(random_password) 
print(type(random_password))

for counter in range (10):
    guess = input ("Crack the Mastermind code   ")
    if guess == random_password :
        print ("Congrats you win!  ")
    elif any_digits(guess, random_password):
        print ("Some numbers are correct!  ")
    else:
        print ("Guess again  ")

print("No more chances, you lose...") 
print("The code was ", random_password)

【讨论】:

    猜你喜欢
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多