我有一个刽子手类型的游戏,它将密码显示为破折号。
所以在这种情况下,秘密字符串是'+ * 794242',它将首先显示为'--------'。现在,takeguess函数获取猜测的数字并用它替换正确的相应破折号。这适用于初始猜测,但之后的任何猜测都会使部分变量更长(部分显示猜测和短划线,例如:' - 7-4-4 - ')。
我开始拆分它,看看它是否是部分空白的初始猜测。我不确定为什么它会在每次猜测后继续使部分字符串更长。你会明白我的意思!另外,如果还有其他更好的方法可以解决这个问题,我想知道!谢谢!
secret = '+*794242'
partial = ''
def takeguess(a):
incomp = ('-' * len(secret)) #Dashes
if partial == '': # If just starting (first guess), partial is blank
for i in range(0,len(secret)):
if guess == secret[i]:
global partial
partial = partial + guess
else:
global partial
partial = partial + incomp[i]
return partial
else: # After initial guess, partial won't be blank, this is where I need help
for i in range(0,len(secret)):
if guess == secret[i]:
global partial
partial = partial + guess
else:
global partial
partial = partial + incomp[i]
return partial
while True: #Example while true
guess = raw_input('Enter guess: ')
takeguess(guess)
print partial
答案 0 :(得分:2)
如果您使用套装,则可以进一步简化。
message = '+*794242'
currentLetters = set()
currentMessage = ''
def takeguess(letterGuess):
if letterGuess in message:
currentLetters.add(letterGuess)
while message != currentMessage:
takeguess(raw_input('Enter guess: '))
currentMessage = ''.join([l if l in currentLetters else '-' for l in message])
print currentMessage
<强>提示强>:
答案 1 :(得分:0)
这就是我重写程序的方式:
secret = '+*794242'
partial = bytearray('-' * len(secret))
def takeguess(a):
global partial
for i in range(0,len(secret)):
if guess == secret[i]:
partial[i] = guess
while partial != secret:
guess = raw_input('Enter guess: ')
takeguess(guess)
print partial
最重要的变化是允许它大大简化的变化 - 将partial
改为bytearray
而不是字符串(它是不可变的)。这样做可以将它初始化为所有破折号,然后慢慢填充每次连续猜测。