Python:输入一个答案并接收响应列表中随机给出的响应

Python:输入一个答案并接收响应列表中随机给出的响应,python,python-3.x,Python,Python 3.x,我想做的是,当你输入一封信,如果信是正确的,会有一个自动的回答,它是正确的,但它不会是相同的响应,每次输入一封信的正确答案 我列出了一个响应列表,并为列表放置了一个随机函数 reaction=['good job','lucky guess!',you\'re on a roll] react=random.choice(reaction) 我试着把它放在后面 for letter in rand: rand_list.append(letter) 但这并不是我想要的,因为它会在你输入的每个

我想做的是,当你输入一封信,如果信是正确的,会有一个自动的回答,它是正确的,但它不会是相同的响应,每次输入一封信的正确答案

我列出了一个响应列表,并为列表放置了一个随机函数

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()

每次需要新消息时,都必须随机调用。调用一次并保存结果意味着您的
react
变量永远不会更改。下面在顶部定义了反应列表以便于编辑,但在
checkAnswer()
中有这一行,每次输入正确的字母时调用random.choice
print(random.choice(reaction))


每次需要新消息时,都必须随机调用。调用一次并保存结果意味着您的
react
变量永远不会更改。下面在顶部定义了反应列表以便于编辑,但在
checkAnswer()
中有这一行,每次输入正确的字母时调用random.choice
print(random.choice(reaction))


我重写了你的一些代码。我把它贴在这里,希望看到差异会对你有所帮助。其中一些变化是:

  • 无递归:虽然它可以非常强大,但使用循环通常更安全。例如,在
    startPlay()
    中,每次用户输入无效字符时,都会打开另一个嵌套的
    startPlay()
    函数。这可能导致同时加载许多嵌套函数。更糟糕的是
    startPlay()
    可以调用
    checkAnswer()
    它可以调用
    playreach()
    它可以调用
    preword()
    它可以调用
    startPlay()
    。用户播放的时间越长,程序占用的内存就越多。它最终会崩溃

  • 没有改变的全局变量。虽然在脚本顶部定义全局变量很有用,但是调用
    globals
    并在函数中编辑它们是有风险的,并且会使代码更难调试和重用。最好将需要的东西从一个函数传递到另一个函数。有些人可能会反对在顶部定义任何变量,但我发现它很有用。特别是如果其他人将自定义详细信息,但不需要了解代码是如何工作的

  • 使用列表和字符串的某些细节是不同的。你不需要定义字母表,它已经存在了。您可以直接使用与“python”中的“p”对应的
    检查字符串中的字符:
    ,这样您就不必将所选单词转换为列表。您可以使用
    join
    将列表转换回字符串,如
    ”。join(blank)
    blank
    从列表转换为字符串,每个
    blank
    元素之间留有空格。在
    连接之前使用不同的字符串将更改每个元素之间插入的字符

  • 我希望这对你有帮助。您可以使用此代码执行任何操作:

    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()
    

    我重写了你的一些代码。我把它贴在这里,希望看到差异会对你有所帮助。其中一些变化是:

  • 无递归:虽然它可以非常强大,但使用循环通常更安全。例如,在
    startPlay()
    中,每次用户输入无效字符时,都会打开另一个嵌套的
    startPlay()
    函数。这可能导致同时加载许多嵌套函数。更糟糕的是
    startPlay()
    可以调用
    checkAnswer()
    它可以调用
    playreach()
    它可以调用
    preword()
    它可以调用
    startPlay()
    。用户播放的时间越长,程序占用的内存就越多。它最终会崩溃

  • 没有改变的全局变量。虽然在脚本顶部定义全局变量很有用,但是调用
    globals
    并在函数中编辑它们是有风险的,并且会使代码更难调试和重用。最好将需要的东西从一个函数传递到另一个函数。有些人可能会反对在顶部定义任何变量,但我发现它很有用。特别是如果其他人将自定义详细信息,但不需要了解代码是如何工作的

  • 使用列表和字符串的某些细节是不同的。你不需要定义字母表,它已经存在了。您可以直接使用与“python”中的“p”对应的
    检查字符串中的字符:
    ,这样您就不必将所选单词转换为列表。您可以使用
    join
    将列表转换回字符串,如
    ”。join(blank)
    blank
    从列表转换为字符串,每个
    blank
    元素之间留有空格。在
    连接之前使用不同的字符串将更改每个元素之间插入的字符

  • 我希望这对你有帮助。您可以使用此代码执行任何操作:

    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()
    

    谢谢@KyleV的帮助。我正在研究你的代码,并尝试是否可以制作我的版本。不过我有个问题。如果正确和错误的猜测存储在guessed=[]中,为什么您必须放置guessed.append(answer)两次?我没有将答案添加到
    guessed
    中,直到检查它们是否有效。要追加的语句有两次,因为正确答案和错误答案都被添加了,每个都有一个语句。我没有将它放在长if/elif/else块之前,这样过长或非字母的答案就不会存储在猜测中。这意味着
    guessed
    必须保持小规模,重复的错误尝试会不断得到信息,告诉他们做错了什么。所以我再猜一次