【问题标题】:hangman game python able to replace hidden letters but doesn't pick up where it left off刽子手游戏python能够替换隐藏的字母,但不会从中断的地方继续
【发布时间】:2017-07-04 04:56:15
【问题描述】:

您好,我正在尝试在 python 上创建一个刽子手游戏, 当用户使用此方法输入正确的字母时,我能够显示隐藏的字母:

def getGuessedWord():
    import re
    guessed = re.sub(r'\S', '_', word)
    l = checkLetterInWords()
    if l == True:
        new = ""
        for index, char in enumerate(word):
            if char == letter:
                new += letter
            else:
                new += guessed[index]
        guessed = new
        print(guessed, "\n")
    return guessed

但是,当我输入另一个正确的字母时,它不会显示它停止的位置。例如:

这个词是西瓜

输入:w

输出:w_ _ _ _ _ _ _ _ _


第二个输入:a

输出:_ a _ _ _ _ _ _ _ _

我如何使输入像

w _ _ _ _ _ _ _ _ ?

我在 stackoverflow 上查看了许多其他方法,但没有一个有效。有人可以帮我弄清楚吗?谢谢!

【问题讨论】:

  • 不要在每次运行getGuessedWord()函数时都导入re模块。
  • 这段代码sn-p不完整。 wordcheckLetterInWords() 的定义是什么?为什么函数getGuessedWord没有参数?

标签: python python-3.5


【解决方案1】:

我对这段代码进行了一些重组,以便它获取用户猜测的每个字母,如果正确,则将其添加到单词中。

word = "example"
guessWord = ['-'] * len(word)

def guessLetter(letter):
    for i, c in enumerate(word):
        if c == letter:
            guessWord[i] = letter

print("".join(guessWord)) # -> '-------'
guessLetter('e')
guessLetter('a')
guessLetter('x')
guessLetter('m')
print("".join(guessWord)) # -> 'exam--e'

这允许:

  • 不需要正则表达式(通常也是导入的 在文件的顶部,而不是在函数内部)。
  • 运行时间更短。我们只经历一次“----”这个词的版本。在大 O 表示法中:O(n)。
  • 更短的代码。

【讨论】:

    【解决方案2】:

    你必须保持最后的状态,我把你的代码改成这样:

    word = "ramin"
    letter = 'r'
    
    import re
    correct = re.sub(r'\S', '_', word)
    
    def getGuessedWord(): 
        global correct
        if letter in word:
            new = ""
            for index, char in enumerate(word):
                if char == letter:
                    new += letter
                else:
                    new += correct[index]
            correct = new
            print(correct, "\n")
        return correct
    
    letter = 'r'
    print(getGuessedWord())
    letter = 'a'
    print(getGuessedWord())
    
    # Output:
    # ('r____', '\n')
    # r____
    # ('ra___', '\n')
    # ra___
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-31
      • 2015-11-20
      • 1970-01-01
      • 1970-01-01
      • 2014-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多