我已经做了游戏主代码,我有麻烦让电脑告诉用户他们得到了正确和错误的数字。 下面列出了我的代码,以及我用来让计算机打印正确答案的尝试。如果有人能告诉我我做错了什么,并给我指出正确的方向,那就太好了。在
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()中不同部分的黑白挂钩。这允许您删除“匹配为黑色”的内容,而不会[错误地]为其添加额外的白色。在
使用列表,可以这样实现:
如果您有更多的Python经验,您可能会找到更简洁的方法来使用set()对象或Counter()对象。。。但是看看你能不能明白为什么上面的方法有效。在
下面是我的测试用例:我将密码设置为“12345”,然后执行以下测试:
^{pr2}$这就是你要找的结果吗?在
关于masterMind()部分:hint()调用在错误的位置执行。它还使用
password
而不是Password
作为参数关于提示部分:
answer
在任何地方都没有定义,我想你的意思是password
。在我不确定你能用那样的整数,但如果你把它们转换成字符串就好了。在
最后,该算法结构不能很好地工作。如果一个猜测数在正确的位置,guess函数将同时返回}。在
x
和{您应该使用一个
if ... elif
结构,然后您可以添加一个else
子句来通知用户这个号码根本不在密码中!在尝试用这些指示重写hint()函数,但是如果需要更多帮助,这里有一个有效的解决方案。在
^{pr2}$另外,最好检查一下用户的猜测是否正好是5位数。如果少于五位数,就会有错误。在
首先,您应该将
hint
调用移出if
块(可能只有在用户正确输入密码时才提示用户不是一个好主意):顺便说一下,您将
hint
称为hint(password, userGuess)
。Python名称区分大小写,您应该这样调用它:hint(Password, userGuess)
。好吧,实际上您应该将Password
变量重命名为password
-Python的常见惯例是在变量名中使用小写。在其次,
^{pr2}$hint
函数中有未定义的变量。我认为这个函数应该是这样的:通过这些更改,您的代码可以工作:我在第10次尝试时得到了
18744
密码。在相关问题 更多 >
编程相关推荐