如何让控制台 "remember" 用户在 Python 中输入?

How to get the console to "remember" a user input in Python?

我想弄清楚如何让控制台“记住”用户在我的刽子手游戏中输入的内容。例如,如果单词“tree”是从我创建的刽子手字符串中挑选出来的,如果用户输入字母“r”,我希望控制台记住该输入并在每次用户输入时将其打印到控制台一个字母,直到 session 结束。如果用户输入“r”而用户可以在单词中找到其他字母,我希望控制台 re-print“- r - -”。如果用户也输入字母“t”或“e”:“- r e e”,我希望同样的事情发生。谢谢,对不起,如果我要求太多,我找不到答案。

这是我的代码:

#hangman mini-project

import random
import string
import time

letters = string.ascii_letters
lettertree = ['a', 'b', 'c', 'd', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 's', 'u', 'v', 'w', 'x', 'y', 'z']
hangmanwords = ['tree','sun']
sunchoices = ['s _ _', '_ u _', '_ _ n']
treechoices = ['t _ _ _', '_ r _ _', ' _ _ e _', '_ _ _ e']
lettercount = [0]
gameWinTree = False
gameWinSun = False
limbCount = 5

hangmanword = random.choice(hangmanwords)
correct = hangmanword
if hangmanword == "sun":
    print (random.choice(sunchoices))
if hangmanword == "tree":
    print (random.choice(treechoices))
    
    
    
    if letters == "r":
        print("Nice! You guessed one letter from the word")
        if letters == "e":
            print("Wow! You guessed two letters from the word, if you wish, you can guess the word")
while True:
    letters = input("Please enter a letter to guess the word")
    if letters == correct:
        input("Correct! The word was " + correct + ". Press enter to play again.")
        time.sleep(1)
        break
    if letters == correct:
        gameWinTree == true
        if gameWinTree == true:
            time.sleep(1)
        break
    print("The letter that you chose was " + letters)
    if letters == "r":
        print("Nice! You guessed one letter from the word!\n t r _ _")
        
    if letters == "e":
        print("Wow! You guessed two letters from the word!\n t _ e e")
    if letters == correct:
        print("Correct! The word was tree!")
    if letters == lettertree:
        print("Sorry, that's not a correct letter, feel free to try again.")
    limbCount -=1
    if limbCount == 0: 
        print("Unfortunately, you are out of tries, better luck next time!")
        time.sleep(1)
        exit()
        

抱歉,如果我的代码看起来马虎,我刚开始学习 Python 学习其他编程语言。

以下是我将如何构造您要查找的字符串。当玩家猜到一个字母时,我会将其存储在一个名为 guesses 的集合中。如果它在单词的字母集合中,称为 correct,那么我有效​​地将它添加到这些集合的交集,称为 correct_guesses。然后,我遍历单词,并将每个字母打印到占位符字符串中,如果该字母不在 correct_guesses 中,则用下划线替换。这就是它在代码中的样子:

word = 'tree'
guesses = set()
correct = set(list(word))
correct_guesses = set()

while correct_guesses != correct:
  # Get input
  guess = input("Guess: ")
  guesses.add(guess)
  correct_guesses = guesses.intersection(correct)

  # Print word status
  placeholder = ' '.join(['%s' for _ in word])
  print(placeholder % tuple([l if l in correct_guesses else '-' for l in word]))
  print("You've guessed: " + ", ".join(guesses))

如果此代码对您不起作用或需要更多解释,请告诉我。