我在制作Hangman程序时遇到了麻烦

时间:2011-11-14 14:45:23

标签: python pydev

我无法从代码中获取正确的输出。我需要它一个接一个地提供头部,身体,手臂和腿部,但它不会。请检查我的代码。

import random
max_wrong = len(HANGMAN) -1
WORDS = ("Caleb","Owen","Ben","Adriane","Marley")
word = random.choice(WORDS)
so_far = "-" * len(word)
wrong = 0
used = []

while wrong < max_wrong and so_far != word:  #The start of the sequence  to make it loop
    print(HANGMAN[wrong])
    print("you used the following letters: ",used)
    print("So far the length of the word is ",so_far)

    guess = raw_input("What letter do you think is in the word? ")
    guess = guess.upper()

    while guess in used:
        print("Hey,wait a minute you have already guessed that word.")
        guess = raw_input("What letter do you think is in the word? ")
        guess = guess.upper()

used.append(guess)

if guess in used:
    print('Yes',guess,"is in the word")
    # new so_far
    new = " "
    for i in range(len(word)):
        if guess == word[i]:
            new += guess 

    else:
    new += so_far[i]
    max_wrong = len(HANGMAN) -1

    so_far = new

else:
    print("Sorry ", guess, " is not in the word")
    wrong += 1 

if wrong == max_wrong:
    print(HANGMAN[wrong])
    print"Oops sorry you have been hanged!"

else:
    print("You guessed it the word was ",word)

顺便说一下,我已经用“图形”创建了元组,但是堆栈溢出不会让我显示它所以我把它留在了后面。它不会提供身体,它一直说这封信是在这个词中。 输出就是这个,即使它不在单词

 ------
 |    |
 |
 |
 |
 |
 |
 |
 |
----------

('you used the following letters: ', [])
('So far the length of the word is ', '-----')
What letter do you think is in the word? n
('Yes', 'N', 'is in the word')

 ------
 |    |
 |
 |
 |
 |
 |
 |
 |
 ----------

('you used the following letters: ', ['N'])
('So far the length of the word is ', ' -----')
What letter do you think is in the word? k
('Yes', 'K', 'is in the word')

  ------
  |    |
  |
  |
  |
  |
  |
  |
  |
  ----------

 ('you used the following letters: ', ['N', 'K'])
 ('So far the length of the word is ', '  ----')
 What letter do you think is in the word? 

2 个答案:

答案 0 :(得分:1)

嗯,首先,看起来你有一个未定义的变量:

max_wrong = len(HANGMAN) -1

你的意思是

max_wrong = len(word) -1

??在这种情况下,您必须在定义单词后定义它。

你还必须看看你是如何设置循环的...例如你有一个缩进的“其他”(不确定这是不是通过你的副本和粘贴)。如果您正在尝试使用

new = " "

设置一个空白字符串并在每次正确猜测时添加字母,你可能想要在if循环之外,否则每次循环时都会覆盖一个新的空字符串。

这是否适合你的课堂作业?

答案 1 :(得分:0)

开始于:

if guess in used: 
    print('Yes',guess,"is in the word")

你不想检查猜词是否在单词中吗?