上面的代码有效,但是在单词列表中只有 5 个项目可供选择,如果输入大于 5 的数字,则可能会出错,因此我在列表中添加了一些其他单词,但我也删除了输入的行要求用户输入与要发现的单词相关的项目编号的功能。所以:我导入了随机模块。
我删除了输入代码。
我使用 random.sample 函数来存储要发现的单词(第 12 行)。
我将 words[i] 替换为 samplecode[0] 作为要发现的单词的标签。
我在 word.append('_ ') 中的下划线后添加了一个空格,以使字母的数量更加明显(_ _ _ _ _ 而不是 _____ )。
import random
print("Welcome to Hangman! Guess the word in less than 6 try.")
words= ['utopian','fairy','tree','monday','blue',
'winner','chosen','magician','european',
'basilar','fonsaken','butter','butterfly',
'flipper','seaside','meaning','gorgeous',
'thunder','keyboard','pilgrim','housewife'
]
sampleword = random.sample(words,1)
if(sampleword[0]):
print("The length of the word is: " , len(sampleword[0]))
guesses=0
letters_guessed = []
word = []
for x in range(len(sampleword[0])):
word.append('_ ')
while guesses < 6:
guess=input("Please enter the letter you guess: ")
if(guess in sampleword[0]):
print("The letter is in the word.")
for index, letter in enumerate(sampleword[0]):
if letter == guess:
word[index] = guess
letters_guessed.append(guess)
else:
print("The letter is not in the word.")
guesses=guesses+1
letters_guessed.append(guess)
print("you have guessed these letters: %s"%(''.join(letters_guessed)))
print("Letters matched so far %s"%''.join(word))
print()
if ''.join(word) == sampleword[0]:
break
if guesses==6:
print("Failure. The word was:" , sampleword[0])
else:
print("YOU'VE WON!! Great Job!")
print("You only made %i wrong guesses"%guesses)