我想创建一个猜词游戏,程序从我的单词列表中随机选择一个单词,用户必须猜测这个单词。
- 用户一次只能猜一个字母。
- 用户只能有 6 次失败的猜测。(使用 6 次失败尝试失败)。
- 如果用户在使用 6 次失败尝试之前猜出完整的单词,则用户获胜。
所以我的程序面临很多问题:
- 当它进入下一轮猜测时,我如何让猜测的字母留在空白处?
- 如果这个词有两个相同的字母,我如何在我的空白处也显示它?
- 如何在每一轮中显示所有用户丢失的字母?
这是我到目前为止所做的:
import random
wordlist = ['giraffe','dolphin',\
'pineapple','durian',\
'blue','purple', \
'heart','rectangle']
#Obtain random word
randWord = random.choice(wordlist)
#Determine length of random word and display number of blanks
blanks = '_ ' * len(randWord)
print ()
print ("Word: ",blanks)
#Set number of failed attempts
count = 6
#Obtain guess
while True:
print ()
guess = input ("Please make a guess: ")
if len(guess) != 1:
print ("Please guess one letter at a time!")
elif guess not in 'abcdefghijklmnopqrstuvwxyz':
print ("Please only guess letters!")
#Check if guess is found in random word
for letters in randWord:
if guess == letters:
letterIndex = randWord.index(guess)
newBlanks = blanks[:letterIndex*2] + guess + blanks[letterIndex*2+1:]
print ("Guess is correct!")
else:
count -=1
print ("Guess is wrong! ", count, " more failed attempts allowed.")
print()
print("Word: ",newBlanks)
我希望获得的结果(对于 randWord 'purple'):
Word: _ _ _ _ _ _
Missed:
Please make a guess: l
Guess is correct!
Word: _ _ _ _ l _
Missed:
Please make a guess: z
Guess is wrong! 5 more failed attempts allowed.
Word: _ _ _ _ l _
Missed: z
Please make a guess: o
Guess is wrong! 4 more failed attempts allowed.
Word: _ _ _ _ l _
Missed: z, o
Please make a guess: p
Guess is correct!
Word: p _ _ p l _
Missed: z, o
Please make a guess: e
Guess is correct!
Word: p _ _ p l e
Missed: z, o
Please make a guess: r
Guess is correct!
Word: p _ r p l e
Missed: z, o
Please make a guess: u
Guess is correct!
Word: p u r p l e
YOU WON!