当用户在字符列表中得到正确的字母时通知用户

2024-09-27 07:17:24 发布

您现在位置:Python中文网/ 问答频道 /正文

当用户在列表中找到正确的字母时,我该如何告诉他们呢?我知道的唯一方法是插入索引,但这感觉不是很灵活,特别是当单词长度不同时

import random

possibleWords = [["apple"], ["grapefruit"], ["pear"]]
randomWord = random.choice(possibleWords)
anotherWord = ''.join(randomWord)
finalWord = list(anotherWord)
maxTries = list(range(0, 11))
attemptsMade = 0
triesLeft = 10

print("Hangman!")
print("\nYou got {} tries before he dies!".format(maxTries[10]))
print("There's {} possible letters.".format(len(finalWord)))

for tries in maxTries:
    userChoice = input("> ")

    if userChoice == finalWord[0]:
        print("You got the first letter correct! It is {}.".format(finalWord[0]))

    else:
        print("Ouch! Wrong letter! {} tries remaining.".format(triesLeft))

    attemptsMade += 1
    triesLeft -= 1

Tags: formatrandomlistprintgotlettertriesrandomword
3条回答

使用Python的“in”关键字检查列表/iterable中是否有内容

if userChoice in finalWord:

尽管如此,我还是使用regex或列表理解来获取索引,因为在游戏中可能需要它们

char_indexes = [i for (i, l) in enumerate(finalWord) if l == userChoice]
if len(char_indexes):

谈论列表中的字符,或者-我认为在你的例子中更可能的是-你可以检查单词中的字符

if userChoice in finalWord:
        # [...] do stuff here

进一步使用索引函数来确定位置(如果多次出现,则使用位置)

finalWord.index(userChoice)

当然,也可以直接使用index()函数,然后使用返回值

对单词中的字母使用一个集合,每当玩家猜到一个字母时,检查字母是否还在集合中。如果不是,那是一封错误的信;如果是的话,就把那封信去掉,继续写下去。如果集合在某个点是空的,那么玩家就猜出了单词的所有字母

让您开始:

def hangman (word):
    letters = set(word.lower())
    attempts = 5
    while attempts > 0:
        guess = input('Guess a character ')
        if guess[0].lower() in letters:
            print('That was correct!')
            letters.remove(guess[0])
        else:
            print('That was not correct!')
            attempts -= 1

        if not letters:
            print('You solved the word:', word)
            return

hangman('grapefruit')

相关问题 更多 >

    热门问题