python - 如何在 Hangman 游戏中通过一次猜测激活多个字母?

标签 python python-3.x

当我使用包含 2 个相同字母的单词(例如“snazzy”)时,猜测一次只会激活 1 个字母。我该如何解决这个问题?

l1=input('Input your (lowercase) letter:')
l2=input('Input your (lowercase) letter:')
l3=input('Input your (lowercase) letter:')
l4=input('Input your (lowercase) letter:')
l5=input('Input your (lowercase) letter:')
l6=input('Input your (lowercase) letter:')word=[l1,l2,l3,l4,l5,l6]
n1=''
n2=''
n3=''
n4=''
n5=''
n6=''
show=[n1,n2,n3,n4,n5,n6]
fail=0
good=0
while fail<=6 and good<6:
    guess=input('Guess a letter...')
    if guess in word:
        print('Right!')
        good=good+1
        if guess==l1:
            n1=guess
        elif guess==l2:
            n2=guess
        elif guess==l3:
            n3=guess
        elif guess==l4:
            n4=guess
        elif guess==l5:
            n5=guess
        elif guess==l6:
            n6=guess
        show=[n1,n2,n3,n4,n5,n6]
    else:
        print('No.')
        fail=fail+1
    print(show)
print(word)
if fail==7:
    print('Executioner wins!')
else:
    print('Prisoner wins!')

澄清一下,我无法两次猜测该字母来显示其所有实例。

最佳答案

嗯,你的代码中有很多东西不是最优的,但这里有一个小的改进(这也不是最优的)。我使用 for 循环来查找与猜测匹配的所有字母。

num_letters = 6

word_to_guess = []
for _ in range(num_letters):
    word_to_guess.append(
        input('Input your (lowercase) letter:').lower().strip())

word_to_show = ['?', ] * num_letters
fail = 0
good = 0

while fail <= num_letters and good < num_letters:
    guess = input('Guess a letter...').lower().strip()
    if guess in word_to_guess:
        print('Right!')

        for i, letter in enumerate(word_to_guess):
            if guess == letter:
                good += 1
                word_to_show[i] = letter
    else:
        print('No.')
        fail += 1

    print(word_to_show)

print('word_to_guess', word_to_guess)
print('word_to_show', word_to_show)
if fail == 7:
    print('Executioner wins!')
else:
    print('Prisoner wins!')

这对你有用吗?

关于python - 如何在 Hangman 游戏中通过一次猜测激活多个字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55077513/

相关文章:

python - BeautifulSoup Instagram 帖子 html 抓取

Python递归挑战

python - 将 Pandas DataFrame 与不同列中的键合并

python - OpenCV : Is there an alternative to cv2. inRange 使用半径?

python - 用python逐句拆分列表

python - 当我运行程序时,为什么 python 会出现错误“需要缩进 block ?”

python - 优化Python : Large arrays,内存问题

python-3.x - 如何使用 Pyramid 读取http post参数?

python - 如何在 ScalarFormatter 之后更改双对数图的 xticks 和 yticks?

Python Setter 和 Getter 命名