Hangman代码无法检测到正确的猜测

时间:2017-05-31 10:14:26

标签: python python-3.x

编辑:已解决。谢谢你,bruno desthuilliers!

我正在为学校作业做一个Hangman游戏,我遇到了一个错误。我的程序无法正确识别何时进行正确的猜测,而是说每次猜测都是错误的。

我将打破程序的主循环。之前和之后的所有代码都是按预期工作的介绍性和结束性对话。问题在于猜测这个词。

这部分代码运行正常 - 这是处理不同类型的无效输入。

while "_" in placeholder:
    guess = input("Guess a letter: ").lower()
    if not guess.isalpha():
        print("Please enter a letter.")
    elif not len(guess) == 1:
        print("Please enter one letter only.")  
    elif guess in previous_guesses:
        print("You have already guessed that letter. Please guess a letter")

这是有问题的部分。这是程序检查猜测的字母是否在单词中的位置。 word_letters只是单词中的字母列表 - 由word.split()

组成
elif guess in word_letters: 
    print("'" + guess + "'" + " is in the word. Good guess!")
    previous_guesses.append(guess)
    index = word_letters.index(guess)
    for index, letter in enumerate(word_letters):
        if letter == guess:
            placeholder[index] = guess

同样,这部分在这里工作正常。只有在猜测错误时才会发生,但即使猜测正确也会发生。

else:
    print("'" + guess + "'" + " is not in the word. Try again.")
    previous_guesses.append(guess)
    stage += 1
    Hangman.draw(stage)

我真的不明白为什么这不能正常工作。我创建了一个测试块,它完全模拟了我的主程序中发生的事情,并且它正常工作。

placeholder = ['_', '_', '_', '_', '_']
word_letters = ['h', 'e', 'l', 'l', 'o']
guess = input("guess ")
if guess in word_letters:
  print("It works")
  index = word_letters.index(guess)
  for index, letter in enumerate(word_letters):
    if letter == guess:
      placeholder[index] = guess
  print(placeholder)    
else:
  print("It didn't work")

有人可以向我解释一下我的主程序到底是什么问题吗?

1 个答案:

答案 0 :(得分:0)

  

" word_letters只是单词中的字母列表 - 由word.split()"

组成

然后再看一下 - word_letters不是你想象的那样:

>>> word = "hello"
>>> word_letters = word.split()
>>> word_letters
['hello']
>>> "h" in word_letters
False

str.split(sep=None)实际上会将字符串拆分为sep,默认为任何"空格"字符:

>>> "hello word".split()
['hello', 'word']
>>> "hello\nword".split()
['hello', 'word']
>>> "hello\tword".split()
['hello', 'word']

要制作字符串list字符,您必须使用list(yourstring),即:

>>> word_letters = list(word)
>>> word_letters
['h', 'e', 'l', 'l', 'o']
>>> "h" in word_letters
True

但这里甚至没有必要,因为字符串已经是序列和支持包含测试:

>>> word
'hello'
>>> 'h' in word
True

index方法:

>>> "hello".index("h")
0
>>> "hello".index("o")
4