【问题标题】:Hangman game duplicates and sorting python errors刽子手游戏重复和排序python错误
【发布时间】:2021-08-18 21:22:28
【问题描述】:

我正在尝试用 Python 编写一个 Hangman 游戏,我几乎可以用简单的单词来理解它,但是当有重复时它会混淆返回索引。代码如下:

def hangman_game():  
words = ["aback", "abaft", "abandoned", "abashed", "aberrant", "abhorrent", "abiding", "abject", "ablaze", "able",
     "abnormal", "aboard", "aboriginal", "abortive", "abounding", "abrasive", "abrupt", "absent", "absorbed",
     "absorbing", "abstracted", "absurd", "abundant", "abusive", "acceptable", "accessible", "accidental",
     "accurate", "acid", "acidic", "acoustic", "acrid", "actually", "ad hoc", "adamant", "adaptable", "addicted",
     "adhesive", "adjoining", "adorable", "adventurous", "afraid", "aggressive", "agonizing", "agreeable", "ahead",
     "ajar", "alcoholic", "alert", "alike", "alive", "alleged", "alluring", "aloof", "amazing", "ambiguous",
     "ambitious", "amuck", "amused", "amusing", "ancient", "angry", "animated", "annoyed", "annoying", "anxious",
word = random.choice(words)
print(f'Random word = {word} (backtesting)')
letter_set = []
word_set = []
for i in word:
    word_set.append(i)
print(f'Letter remaining to be found ={word_set}')

while len(letter_set) < len(word_set):

    for i in word:
        letter = input("Guess a letter: ")

        if letter in word_set:
            
            letter_set.insert(word.index(letter)), letter) # issue here
            word_set.remove(letter)
            print(f'Word with letters removed: {word}')
            print(f"Letter {letter} found at word index: {word.index(letter)}")
            print(f'Letters found in word: {letter_set}')
            print(f'Word set = {word_set}')

        else:
            print(f'Letter not found in word: {word}')
print(letter_set)
print("".join(map(str, letter_set)))

当它在 word 中找到重复项时,它会从 word_set 中删除重复的字母,而不是从 word 中删除。因此,当它找到像“字母”这样的单词时,它会始终在索引 [1] 处插入“e”。所以它会像“leettr”一样打印。我发现即使没有重复,有时它也会与索引混淆,通常是在较长的单词上,但无法真正弄清楚原因。

我正在考虑让 letter_set 有 i 个“_”,这取决于默认情况下的单词,而不是使用 word_set 替换它。 关于如何始终将字母返回到正确索引的任何建议?

【问题讨论】:

    标签: python list indexing duplicates set


    【解决方案1】:

    我在这里复制我的代码,以防将来有人需要类似的东西。 `

    `

    def hangman_game():
    
    new_game = input("Press enter for new game")
    word = random.choice(words)
    print(f'Random word = {word} (testing)')
    letter_set = list("_" * len(word))
    lives = 3
    
    while "_" in letter_set:
        letter = input("Guess a letter: ").upper()
        letter_count = word.count(letter)
        if letter.isnumeric() or len(letter) > 1:
            print("Insert valid character: a-z")
    
        for index, (find_word, hidden) in enumerate(zip(word, letter_set)): # create new list with "_"*len(word)
            if find_word == letter.lower() and hidden == "_":               # check if letter is found in word, and if it is already revealed
                letter_set[index] = letter                                  # change "_" at the found indexes with letter
                print(f'Letter found!')
        if len(letter) > 1:
            lives += 1
            print(f"One letter at the time!  ")
        if letter.lower() not in word and letter.isnumeric() == False:
            lives -= 1
            print(f"Letter not found! Lives = {lives}")
    
            if lives == 0:
                print(f"YOU LOST! \n")
                hangman_game()
    
            if letter_count >= 1:
                letter_set[index] = letter.upper()
    
        print(f'Your word is: {" ".join(map(str, letter_set))}')
    
    print("YOU WON \n")
    hangman_game()
    
    hangman_game() #wrong copied indentation
    

    【讨论】:

      【解决方案2】:

      您可以稍微重构一下代码。例如,您可以创建一个列表hidden_word,其中包含与word 中的字母相同数量的#。用户将猜测字母,您将显示隐藏单词中的字母,直到没有任何东西可以显示。例如:

      def hangman_game():
          word = "letter"  # <-- chose a random word here instead of hardcoding it
      
          hidden_word = list("#" * len(word))
      
          while "#" in hidden_word:
              print("STATUS")
              print("------")
              print(word)
              print(hidden_word)
              print("------")
      
              letter = input("Guess a letter: ")
      
              for idx, (w, h) in enumerate(zip(word, hidden_word)):
                  if w == letter and h == "#":
                      hidden_word[idx] = letter
                      print("Letter found!")
                      break
              else:
                  print("Letter not found!")
      
      
      hangman_game()
      

      打印:

      STATUS
      ------
      letter
      ['#', '#', '#', '#', '#', '#']
      ------
      Guess a letter: e
      Letter found!
      STATUS
      ------
      letter
      ['#', 'e', '#', '#', '#', '#']
      ------
      Guess a letter: e
      Letter found!
      STATUS
      ------
      letter
      ['#', 'e', '#', '#', 'e', '#']
      ------
      Guess a letter: t
      Letter found!
      STATUS
      ------
      letter
      ['#', 'e', 't', '#', 'e', '#']
      ------
      Guess a letter: t
      Letter found!
      STATUS
      ------
      letter
      ['#', 'e', 't', 't', 'e', '#']
      ------
      Guess a letter: r
      Letter found!
      STATUS
      ------
      letter
      ['#', 'e', 't', 't', 'e', 'r']
      ------
      Guess a letter: x
      Letter not found!
      STATUS
      ------
      letter
      ['#', 'e', 't', 't', 'e', 'r']
      ------
      Guess a letter: l
      Letter found!
      

      【讨论】:

      • 正是我想要的!我只是不知道如何使用 enumerate 和 zip 尤其是在 for 循环中结合使用。
      猜你喜欢
      • 2014-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-18
      • 2015-05-29
      • 1970-01-01
      • 1970-01-01
      • 2019-08-27
      相关资源
      最近更新 更多