Python:输入答案并随机从响应列表中获取回复
我想实现的功能是,当你输入一个字母时,如果这个字母是正确的,就会自动给出一个反馈,告诉你这个字母是对的。不过,每次输入正确字母时,反馈的内容不能总是一样。
为此,我准备了一份反馈的列表,并使用了一个随机函数来从这个列表中选取反馈。
reaction=['good job','lucky guess!',you\'re on a roll]
react=random.choice(reaction)
我尝试把这个随机反馈放在
for letter in rand:
rand_list.append(letter)
之后,但这样做并不是我想要的效果,因为这样每次输入正确字母时,反馈都是一样的,只有在你猜下一个单词时才会改变。
完整的代码是:
import random
alphabeth = 'abcdefghijklmnopqrstuvwxyz'
rand_list = []
guessed_list = []
def prepWord():
global rand, guessed_list, blank, rand_list,good,react_good
react_good = ['Good job!', 'Lucky guess!', 'Took you a while to guess that letter!', 'You\'re on a roll!']
words = ['note', 'pencil', 'paper','foo']
rand = random.choice(words)
guessed_list = []
blank = ['_']*len(rand)
rand_list = []
for letter in rand:
rand_list.append(letter)
startPlay()
def startPlay():
print('Welcome to Hangman. You have 8 tires to guess the secret word.')
gameQ = input('Ready to play Hangman? y or n: ')
if gameQ == 'y' or gameQ == 'Y':
print('Guess the letters:')
print(blank)
checkAnswer()
elif gameQ == 'n' or gameQ == 'N':
print('goodbye')
print('*********************')
else:
print('Invalid answer. Please try again')
startPlay()
def playAgain():
again = input('Would you like to play again? y or n --> ')
if again == 'y':
prepWord()
elif again == 'n':
print('Thanks for playing')
else:
print('Invalid answer. Please type y or n only')
print(' ')
playAgain()
def checkAnswer():
tries = 0
x = True
while x:
answer = input('').lower()
if answer not in guessed_list:
guessed_list.append(answer)
if len(answer)>1:
print('One letter at a time.')
elif answer not in alphabeth:
print('Invalid character, please try again.')
else:
if answer in rand:
print("The letter {} is in the word.".format(answer))
indices = [b for b, letter in enumerate(rand_list) if letter == answer]
for b in indices:
blank[b] = answer
print (blank)
else:
print ("I'm sorry the letter {} is not in the word. Please try again.".format(answer))
tries +=1
if tries
if tries == 8:
print('Game over. You are out of tries')
playAgain()
else:
print('Letter {} already used. Try another.'.format(answer))
if '_' not in blank:
print('You guessed the secret word. You win!')
final_word = 'The secret word is '
for letter in blank:
final_word += letter.upper()
print(final_word)
print('')
x = False
playAgain()
prepWord()
相关问题:
- 暂无相关问题
2 个回答
每次你想要一个新的消息时,都得调用一次random。如果你只调用一次并把结果保存下来,那么你的react
变量就不会改变了。下面的代码在最上面定义了反应列表,方便编辑,但在checkAnswer()
函数里有一行代码,每当输入正确的字母时,就会调用random.choice来获取新的反应,代码是print(random.choice(reaction))
。
import random
alphabeth = 'abcdefghijklmnopqrstuvwxyz'
rand_list = []
guessed_list = []
reaction=["good job","lucky guess!","you're on a roll"]
def prepWord():
global rand, guessed_list, blank, rand_list,good,react_good
react_good = ['Good job!', 'Lucky guess!', 'Took you a while to guess that letter!', 'You\'re on a roll!']
words = ['note', 'pencil', 'paper','foo']
rand = random.choice(words)
guessed_list = []
blank = ['_']*len(rand)
rand_list = []
for letter in rand:
rand_list.append(letter)
startPlay()
def startPlay():
print('Welcome to Hangman. You have 8 tires to guess the secret word.')
gameQ = input('Ready to play Hangman? y or n: ')
if gameQ == 'y' or gameQ == 'Y':
print('Guess the letters:')
print(blank)
checkAnswer()
elif gameQ == 'n' or gameQ == 'N':
print('goodbye')
print('*********************')
else:
print('Invalid answer. Please try again')
startPlay()
def playAgain():
again = input('Would you like to play again? y or n --> ')
if again == 'y':
prepWord()
elif again == 'n':
print('Thanks for playing')
else:
print('Invalid answer. Please type y or n only')
print(' ')
playAgain()
def checkAnswer():
tries = 0
x = True
while x:
answer = input('').lower()
if answer not in guessed_list:
guessed_list.append(answer)
if len(answer)>1:
print('One letter at a time.')
elif answer not in alphabeth:
print('Invalid character, please try again.')
else:
if answer in rand:
print("The letter {} is in the word.".format(answer))
print(random.choice(reaction))
indices = [b for b, letter in enumerate(rand_list) if letter == answer]
for b in indices:
blank[b] = answer
print (blank)
else:
print ("I'm sorry the letter {} is not in the word. Please try again.".format(answer))
tries +=1
if tries == 8:
print('Game over. You are out of tries')
playAgain()
else:
print('Letter {} already used. Try another.'.format(answer))
if '_' not in blank:
print('You guessed the secret word. You win!')
final_word = 'The secret word is '
for letter in blank:
final_word += letter.upper()
print(final_word)
print('')
x = False
playAgain()
prepWord()
我对你的代码做了一些修改。把这些改动放在这里,希望你能通过对比看到不同之处,从而对你有帮助。以下是一些改动:
没有使用递归:虽然递归很强大,但通常使用循环会更安全。比如在
startPlay()
函数中,每当用户输入一个无效字符时,你就会打开另一个嵌套的startPlay()
函数。这可能会导致同时加载很多嵌套的函数。更糟糕的是,startPlay()
可能会调用checkAnswer()
,而checkAnswer()
又可以调用playAgain()
,然后playAgain()
可能会调用prepWord()
,最后又回到startPlay()
。用户玩得越久,你的程序占用的内存就越多,最终可能会崩溃。没有可变的全局变量。虽然在脚本顶部定义全局变量很有用,但在函数中调用
globals
并修改它们是有风险的,这会让你的代码更难调试和重用。最好是把需要的东西从一个函数传递到另一个函数。有些人可能会反对在顶部定义任何变量,但我觉得这很有用。特别是当其他人需要自定义细节,但不需要理解代码是如何工作的时。处理列表和字符串的一些细节是不同的。你不需要自己定义字母表,因为它已经存在于 string.ascii_lowercase 中。你可以直接用
if 'p' in 'python':
来检查字符串中的字符,所以你不需要把选定的单词转换成列表。你可以用join
把列表转换回字符串,比如" ".join(blank)
,这会把blank
从列表转换成字符串,并在每个元素之间加一个空格。如果在join
前使用不同的字符串,会改变每个元素之间插入的字符。
希望这些对你有帮助。你可以随意使用这段代码:
import random
import string
# Global and on top for easy editing, not changed in any function
words = ['note', 'pencil', 'paper','foo']
react_good = ["Good job!",
"Lucky guess!",
"Took you a while to guess that letter!",
"You're on a roll!"]
def game():
games = 0
while start(games): # Checks if they want to play.
games += 1
play_game()
def play_game(): # returns True if won and returns False if lost.
rand_word = random.choice(words) # Choose the word to use.
blank = ['_']*len(rand_word)
guessed = []
tries = 0
while True: # Not infinite, ends when a return statement is called
print("")
print(" ".join(blank)) # Converting to string first looks better
answer = input('Guess a letter: ').strip().lower() # remove whitespace
if answer == 'exit' or answer == 'quit':
return False # Exit Game
elif len(answer) != 1:
print('One letter at a time.')
elif answer not in string.ascii_lowercase: # same as alphabet string
print('Invalid character, please try again.')
elif answer in guessed:
print('Letter {} already used. Try another.'.format(answer))
elif answer in rand_word: # Correct Guess
# Update progress
indices = [i for i, x in enumerate(rand_word) if x == answer]
for i in indices:
blank[i] = answer
# Check if they have won
if blank == list(rand_word): # Or could convert blank to a string
print('You guessed the secret word. You win!')
print('The secret word is ' + rand_word.upper())
print('')
return True # Exit Game
guessed.append(answer)
print("The letter {} is in the word.".format(answer))
print(random.choice(react_good))
else: # Incorrect Guess
tries += 1
# Check if they have lost.
if tries >= 8:
print('Game over. You are out of tries')
return False # Exit Game
print ("I'm sorry the letter {} is not in the word. Please try again.".format(answer))
guessed.append(answer)
def start(games = 0): # Gives different messages for first time
if games == 0: # If first time
print('Welcome to Hangman. You have 8 tires to guess the secret word.')
# Loops until they give a valid answer and a return statement is called
while True:
# Get answer
if games > 0: # or just 'if games' works too
game_q = input('Would you like to play again? y or n --> ')
else:
game_q = input('Ready to play Hangman? y or n: ')
# Check answer
if game_q.lower() == 'y':
return True
elif game_q.lower() == 'n':
if games > 0:
print('Thanks for playing')
else:
print('goodbye')
print('*********************')
return False
else:
print('Invalid answer. Please try again')
game()