我想创建一个猜词游戏,程序从我的单词列表中随机选择一个单词,用户必须猜词。
所以我的程序面临很多问题:
我到目前为止所做的是:
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!
与其重用上一轮的
newBlanks
字符串,我建议重新构建它,使用join
和简单的列表理解,使用一个包含所有猜测的字符串guessed
,比如here。还要注意,您对正确/不正确字母的检查不会这样工作,但会减少单词中每个不是猜测字母的字母的count
。改用if guess in randWord:
。另外,您可以使用count
作为while
循环的条件,并且如果guess
不是单个字母,则可以使用continue
作为循环的下一次迭代。总而言之,您的代码可能如下所示:
只需为下一轮存储包含猜测字母和空格的字符串。您每次从
wordlist
开始重新计算(也可以每次重新计算,但之后需要修改字母搜索功能,请参见答案2)修改您的搜索循环,它应该在找到第一个匹配的字母后继续搜索。
letterIndex = randWord.index(guess)
将只返回字符串中guess的第一次出现。将它们分别存储在单独的字符串或列表中。所以你每次都可以打印出来。
与其重用上一轮的
newBlanks
字符串,我建议重新构建它,使用join
和简单的列表理解,使用一个包含所有猜测的字符串guessed
,比如here。还要注意,您对正确/不正确字母的检查不会这样工作,但会减少单词中每个不是猜测字母的字母的count
。改用if guess in randWord:
。此外,您可以使用count
作为while
循环的条件,并且如果guess
不是单个字母,则可以使用continue
作为循环的下一次迭代。总而言之,您的代码可能如下所示:
相关问题 更多 >
编程相关推荐