我现在开始学习编程,我必须做一个 secret 文字游戏,但是每当我运行代码时,结果都会连接起来,并且它应该只出现一次,我哪里出错了?我将粘贴代码并附上控制台的屏幕截图。 我愿意接受其他提示和改进。
print('¨' * 40)
print(f'|{"Secret Word Game":^38}|')
print('¨' * 40)
secret_word = 'believer'
user_input = ''
typed = []
attempts= 0
number_of_letters = '_ ' * len(secret_word)
discovering_secret_word = ''
print('Try to guess the Secret Word!')
print(f'The secret word is: {number_of_letters}')
while discovering_secret_word != secret_word:
user_input = input('Type a letter: ')
attempts += 1
if len(user_input) > 1:
print('You can´t insert more than one letter!')
continue
typed.append(user_input)
for letter in secret_word:
if letter in typed:
discovering_secret_word += letra
else:
discovering_secret_word += '_ '
print(f'The Secret Word is {discovering_secret_word}')
else:
print('Congratulations, you won!')
print(f'The Secret Word is {secret_word}.')
print(f'It took {attempts} attempts.')
`
最佳答案
出现此问题的原因是您没有重置 discovering_secret_word
字符串。你不断地串联起来。这是您需要执行的操作:
print('¨' * 40)
print(f'|{"Secret Word Game":^38}|')
print('¨' * 40)
secret_word = 'believer'
user_input = ''
typed = []
attempts = 0
number_of_letters = '_ ' * len(secret_word)
discovering_secret_word = ''
print('Try to guess the Secret Word!')
print(f'The secret word is: {number_of_letters}')
while discovering_secret_word != secret_word:
user_input = input('Type a letter: ')
attempts += 1
if len(user_input) > 1:
print('You can´t insert more than one letter!')
continue
typed.append(user_input)
# reset discovering_secret_word
discovering_secret_word = ""
for letter in secret_word:
if letter in typed:
discovering_secret_word += letter # Fixed to letter had letra before
else:
discovering_secret_word += '_ '
print(f'The Secret Word is {discovering_secret_word}')
else:
print('Congratulations, you won!')
print(f'The Secret Word is {secret_word}.')
print(f'It took {attempts} attempts.')
这就是我尝试解决 secret 单词后我的控制台的样子:
¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨
| Secret Word Game |
¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨
Try to guess the Secret Word!
The secret word is: _ _ _ _ _ _ _ _
Type a letter: b
The Secret Word is b_ _ _ _ _ _ _
Type a letter: b
The Secret Word is b_ _ _ _ _ _ _
Type a letter: e
The Secret Word is be_ _ e_ e_
Type a letter: l
The Secret Word is bel_ e_ e_
Type a letter: i
The Secret Word is belie_ e_
Type a letter: v
The Secret Word is believe_
Type a letter: r
The Secret Word is believer
Congratulations, you won!
The Secret Word is believer.
It took 7 attempts.
关于python - secret 文字游戏 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75902508/