Skip to main content
 首页 » 编程设计

python之MasterMind 问题

2025年05月04日7webabcd

我已经制作了 Mastercode 游戏,但我无法让计算机告诉用户他们得到了正确和错误的数字。 下面列出了我的代码,以及我用来让计算机打印正确答案的尝试。如果有人能告诉我我做错了什么并指出正确的方向,那就太好了。

import random 
def masterMind():   
    Password = "%05d" % random.randint(0, 99999) #the computer chooses 5 random numbers 
    for tries in range(10): 
        userGuess = raw_input("Guess my 5 digit password to access the treasure:")  
        if Password == userGuess:  
            print "Win on the %d try" % (tries + 1)  
            hint(password, userGuess)  
            break #terminates the ongoing loop and executes next statement 
    print "answer was:", Password #tells computer to print the password 
 
def hint(password, guess): #function of the hints 
     for i in range(5): #the range within the five integers 
        if guess[i] == password[i]: #if the user's integer aligns with computers integer then an 'x' should appear 
           print 'x', 
           continue 
        if guess[i] in answer: #if don't have corresponding number then an 'o' will appear 
           print 'o', 

请您参考如下方法:

我认为您确实需要在 hint() 的不同部分检查黑白钉。这使您可以删除“匹配为黑色”的内容,而不是 [错误地] 为其添加额外的白色。

使用列表,可以这样实现:

def hint(password, guess): 
 
  # convert the strings to lists so we can to assignments, below  
  password_list = list(password) 
  guess_list = list(guess) 
 
  # check for black (correct number in correct position) 
  for i in range(5): #the range within the five integers 
      if guess_list[i] == password_list[i]: 
          print 'x', 
          # punch in some non-possible value so we can exclude this on the check for white 
          guess_list[i] = None 
          password_list[i] = None 
 
  # check for white (correct number in wrong position) 
  for i in range(5): 
      if guess_list[i] == None: 
          continue 
      if guess_list[i] in password_list: 
          print 'o', 
          # remove this from the password list, so that a given 
          # password digit doesn't incorrectly count as multiple white 
          password_list.remove(guess_list[i]) 
 
          # or this would work, too: 
          #password_list[password_list.index(guess_list[i])] = None 
 
  print 

如果你有更多的 Python 经验,你可能会找到更简洁的方法来使用 set() 对象或 Counter() 对象......但看看你是否能明白为什么上面的工作。

这是我的测试用例:我将密码设置为“12345”,然后进行了这些测试:

Guess my 5 digit password to access the treasure:11111 
x 
Guess my 5 digit password to access the treasure:21777 
o o 
Guess my 5 digit password to access the treasure:77721 
o o 
Guess my 5 digit password to access the treasure:21774 
o o o 
Guess my 5 digit password to access the treasure:21775 
x o o 
Guess my 5 digit password to access the treasure:14355 
x x x o 
Guess my 5 digit password to access the treasure:12345 
Win on the 7 try 

这就是您想要的结果吗?