我试着自学Python,在网上找到了几个练习。其中之一是设计一个策划类游戏here。在
在SO的帮助下,我已经成功地完成了大部分需求,但最后一点我还是被卡住了。我不知道如何在每次新的猜测中保持以前的猜测值,变量msg1
的显示。在
这是我迄今为止的代码片段。欢迎发表任何意见!在
def position(x, y):
position = sum(1 for a,b in zip(x ,y) if (a == b))
return position
def exists(x, y):
exists = len(set(x) & set(y))
return exists
checks = [
lambda n: (len(n)==4, "Enter 4 digits only."),
lambda n: (n.isdigit(), "Enter digits only."),
lambda n: (len(set(str(n)))==4, "Enter non duplicate numbers only.")
]
a = raw_input("Enter the 4 numbers you want to play with: ")
sturn = 1
lturn = 8 #this set the maximum number of turns
while sturn <= lturn:
b = raw_input("Enter your guess: ")
all_good = True
for check in checks:
good, msg = check(b)
if not good:
print msg
all_good = False
break
if int(b) == int(a):
print ("You guessed the key {0}! It took you {1} tries").format(a, sturn)
if sturn == lturn and int(b) != int(a):
print ("You lose. The answer was {0}").format(a)
elif int(b) != int(a) :
msg1 = ("{0}: position:{1}, exists {2}").format(b, position(a, b), (exists(a, b) - position(a, b)))
print msg1
sturn += 1
如果你想每次都重新显示猜测的全部历史,那么让msg1成为一个不断增长的字符串。在
请注意,现在每个msg都带有它的linebreak,因此打印不再需要输出一个。在
然而,正如thomask所观察到的:旧的输入仍然应该显示在终端上,除非你设法清除终端。在
相关问题 更多 >
编程相关推荐