我的hangman python代码似乎陷入无限循环?

时间:2012-04-02 02:55:07

标签: python

在我的刽子手代码中,我得到了字母和空格的长度以匹配,但由于某种原因,我无法获得字母来替换空格及其无限循环。我不知道我哪里出错了/我错过了什么。

from random import*

def main():
print
print "-----------------------------------"
print "H A N M G M A N: Tropical Fruit 1.0"
print "-----------------------------------"
print
wordList = ["pomegranate","mango","cassabanana","conkerberry","jujube"]
randomIdx = randrange(0, len(wordList))
secretWord = wordList[randomIdx]
print "(The secret word is", secretWord,")"
lettersGuessed = []
underscore = []
for i in range(len(secretWord)):
    underscore.append('_')
    newUnderscore = " ".join(underscore)
print newUnderscore
count = 6
while(True):
    guess = getNewLetter(lettersGuessed)
    if lettersGuessed == randomIdx:
        print "You guessed the letter! It is: ",ch2
        break

def getLetter():
   letter = True
   while (letter):
     ch = raw_input("Guess a letter: ")
     if len(ch) == 1:
       if ('a' <= ch) and (ch <= 'z'):
         return ch
       elif ('A' <= ch) and (ch <= 'Z'):
         return chr(ord(ch)-ord('A')+ord('a'))
       else:
         print ch,"is not a valid letter."
     else:
       print ch,"is not a single character."

def getNewLetter(oldChar):
letter = True
while (letter):
    ch = getLetter()
    if ch not in oldChar:
        oldChar.append(ch)
        return ch 
    else:
        print "You already guessed",ch,"!"


main()
编辑:所以我将主函数中的while循环更改为this,这样字母就会附加到空白中,但仍然有问题。

while(True):
guess = getNewLetter(lettersGuessed)
if lettersGuessed == randomIdx:
        lettersGuessed.append(newUnderscore)
        return newUnderscore
        break

1 个答案:

答案 0 :(得分:3)

这一行:

if lettersGuessed == randomIdx:

绝不是真的。 lettersGuessed是到目前为止已经猜到的字母数组(类似于['c', 'o', 'n']。randomIdx是所选单词的索引(类似2)。

ETA:还有一些其他问题 - 例如,如果

print "You guessed the letter! It is: ",ch2

已执行,您会发现ch2从未定义过。此外,你没有看到他们是否猜到了这封信,你看他们是否猜到了这个词。也许您正在寻找的是更像这样的东西:

        if set(secretWord).issubset(set(lettersGuessed)):
            print "You guessed the word!"

进行此更改时,以下是程序的示例运行:

-----------------------------------
H A N M G M A N: Tropical Fruit 1.0
-----------------------------------

(The secret word is mango )
_ _ _ _ _
[]
Guess a letter: M
['m']
Guess a letter: A
['m', 'a']
Guess a letter: N
['m', 'a', 'n']
Guess a letter: G
['m', 'a', 'n', 'g']
Guess a letter: O
You guessed the word!

ETA:您可以插入以下行:

        print "".join([l if l in lettersGuessed else "_" for l in secretWord])

进入while循环。该程序的行为将是这样的:

-----------------------------------
H A N M G M A N: Tropical Fruit 1.0
-----------------------------------

(The secret word is jujube )
_ _ _ _ _ _
______
Guess a letter: J
j_j___
Guess a letter: U
juju__
Guess a letter: B
jujub_
Guess a letter: E
You guessed the word!