当用户在列表中找到正确的字母时,我该如何告诉他们呢?我知道的唯一方法是插入索引,但这感觉不是很灵活,特别是当单词长度不同时
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
使用Python的“in”关键字检查列表/iterable中是否有内容
尽管如此,我还是使用regex或列表理解来获取索引,因为在游戏中可能需要它们
谈论列表中的字符,或者-我认为在你的例子中更可能的是-你可以检查单词中的字符
进一步使用索引函数来确定位置(如果多次出现,则使用位置)
当然,也可以直接使用index()函数,然后使用返回值
对单词中的字母使用一个集合,每当玩家猜到一个字母时,检查字母是否还在集合中。如果不是,那是一封错误的信;如果是的话,就把那封信去掉,继续写下去。如果集合在某个点是空的,那么玩家就猜出了单词的所有字母
让您开始:
相关问题 更多 >
编程相关推荐