我该如何猜测在Hangman游戏中激活多个字母?

时间:2019-03-09 12:48:48

标签: python python-3.x

当我使用一个带有2个相同字母的单词(例如“时髦”)时,猜测一次只能激活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!')

为澄清起见,我无法两次猜测字母以显示其所有实例。

1 个答案:

答案 0 :(得分:1)

好吧,您的代码中有很多东西不是最优的,但是这是一个很小的改进(这也不是最优的)。我使用了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!')

对您有用吗?