Python Mastermind 游戏问题

标签 python python-3.x

我是 Python 编程的初学者,在当前作业中遇到了问题。作业内容如下……

  • 你的程序应该 secret 地生成一个没有重复数字的 4 位数字(或只包含数字,4 个字符长的字符串)。
  • 然后您的程序应该要求用户输入密码的猜测值。用户的猜测应该是 4 个字符长,仅由数字组成,没有重复的数字。您的程序应该在对输入进行评分之前验证输入是否有效,并在必要时提示用户重新输入。无效输入不计入密码破解者的猜测次数。您的代码可能会忽略(剥离)输入中的前导或尾随空格,但应将内部空格计为不正确的输入。
  • 在每个回合中,打印回合数并获得用户的猜测。如果输入有效,则该回合的输出应该是用户的猜测,然后是反馈。 Feedback 是一个 4 字符的字符串:'X'代表正确位置的每个数字; “O”表示代码中但位置不正确的每个数字; '-' 代表所有其他人。请注意,X 和 O 应该放在一起;反馈只是每种类型有多少个钉子,而不是哪些钉子或它们在哪里。
  • 维护所有猜测和反馈的历史记录,以便在每个回合为用户打印。

现在我只专注于作业的“反馈”部分。我的代码目前是:

import random

def validateInput():
inputGuess = input("Enter your guess as 4 numbers:")

while True:
    if len(inputGuess) != 4:
       inputGuess = input("Enter your guess as 4 numbers:")
    else:
        numberList = list(inputGuess) ##

        invalidNumbers = False
        for number in numberList:
            if number not in ['1','2','3','4','5','6','7','8','9']:
                invalidNumbers = True 

        if invalidNumbers == True:
            print ("Possible numbers are 1, 2, 3, 4, 5, 6, 7, 8, 9.")
            inputGuess = input("Enter your guess as 4 numbers:") 

        else:
            return numberList

guessesRemaining=10

code=['1','2','3','4']



while guessesRemaining > 0:
     report=[]
     guess=validateInput()
     guessesRemaining -= 1
     if guess[0] == code[0]:
         report.append("X")
     if guess[1] == code[1]:
         report.append("X")
     if guess[2] == code[2]:
         report.append("X")
     if guess[3] == code[3]:
         report.append("X")

     tempCode=sorted(code)
     tempGuess=sorted(guess)

     if tempCode[0]==tempGuess[0]:
         report.append("O")
     if tempCode[1]==tempGuess[1]:
         report.append("O")
     if tempCode[2]==tempGuess[2]:
         report.append("O")
     if tempCode[3]==tempGuess[3]:
         report.append("O")

     report2=report[0:4]
     dash=["-","-","-","-"]
     report3=report2+dash
     report4=report3[0:5]



     print(report4)

例如,如果用户猜测 1879 而密码是 1234,我收到“X O --”但我想收到“X---”。此外,任何关于简化我的代码的建议都会很棒。为简单起见,我暂时将“随机代码”设为 [1,2,3,4]。

最佳答案

您可以使用 Python 函数 map() 非常优雅地解决您的问题。 (不像我原先想象的那么优雅,但仍然很漂亮。)

guess = "1879" # or [ '1', '8', '7', '9' ]
answer = "1234"

map() 是这样工作的:你给它一个函数作为它的第一个参数,然后一个或多个序列作为它的参数。然后它接受该函数并首先将其应用于第一个元素,然后是第二个元素,依此类推。例如:

>>> def f(a,b):
>>>  return a + b
>>> map( f, [1,2,3,4], [ 10, 20, 30, 40 ] )

[ 11, 22, 33, 44 ]

现在,您有两个字符序列,“guess”和“answer”。您可以编写一个函数,如果它们相等则返回 X,否则像这样:

>>> def mastermind_hint( a, b ):
>>>   return "X" if a == b else "-"

这还不够,您还需要输入“O”。为此,您需要一次使用整个“answer”序列:

>>> def mastermind_hint( a, b ):
>>>   if a == b: return "X"
>>>   if a in answer: return "O"
>>>   return "-"

使用 map ,我们可以将其应用于您拥有的序列:

>>> map( mastermind_hint, guess, answer )
[ "X", "-", "-", "-" ]

现在,现在我们给出的信息比我们预期的要多,因为我们提示的位置对应于猜测字符的位置。隐藏此信息的一种简单方法是对序列进行排序。 Python 有一个 sorted() 函数可以执行此操作:

>>> sorted( map( mastermind_hint, guess, answer ) )
[ "-", "-", "-", "X" ]

剩下的就是将其连接成一个字符串:

>>> "".join( sorted( map( mastermind_hint, guess, answer ) ) )
"---X"

关于Python Mastermind 游戏问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15648407/

相关文章:

python-3.x - 对于共享 IP 地址的多个 Flask 站点,Certbot 证书不适用于 Apache

python - 如果是字母数字则返回 True(不允许方法或导入)

python - 从完整域名中查找国家

python - 如何获得数据框的简单散点图(最好使用 seaborn)

python - setup.py 可以使用 pip 而不是 easy_install 吗?

python-3.x - 您如何指定 CPLEX 在 pyomo 中仅使用一个线程?

python - Streamlabs API 405 响应代码

python - 将不可见的 ASCII 字符附加到字符串

python - 在用户定义的函数中访问全局框架

python - 更改 numpy 数组中字符串的位置