2016-01-21 30 views
1

我一直在教我自己最近在Python中編程並決定製作這款遊戲​​。我已成功爲廣大它除了幾件事情Hangman程序中的多個錯誤

  1. 當一個不正確的字母輸入,字母被附加到錯誤的字母排列的遊戲空間陣列的userletter不等於在儘可能多的點。例如:如果我爲wordtarget輸入「the」,我會將t,h和e打印成錯誤的字母數組2次。不管信得到什麼伸到錯誤的字母排列

代碼:

wordTarget = raw_input("enter word here: ").lower() 
gameSpace = ["_"] * Len(wordTarget) 
wrongLetter = [] 
def main(): 
    for x in range(0, len(wordTarget)):  
     while (gameSpace[x] !=  wordTarget[x]): 
      getLetter() 
      for i in range(0,len(wordTarget)): 
       if (wordTarget[i] == userLetter): 
        gameSpace[i] = userLetter 
       elif (wordTarget[i] != userLetter): 
        print "letter is incorrect, try again" 
        wrongLetter.append(userLetter) 
      print ("Incorrect Letters: %s" % wrongLetter) 
      print ("Correct Letters: %s" % gameSpace) 
      if (gameSpace == wordTarget): 
       print "Congratulations! You won"     
main() 

我猜問題出在了我跑環,我檢查權的方式回答但無法弄清楚。

+0

您需要在_your question_中添加_the relevant_部分代碼。不是你的代碼的所有內容,也不是鏈接到某個非現場的地方。 – Lafexlos

+0

'gameSpace'和'wordTarget'值是如何設置的?他們是字符串,列表還是其他東西? – Blckknght

+0

gameSpace是一個數組,其中存儲空格和字母,如果猜對了。 wordTarget是用戶輸入並且是一個變量。 –

回答

0

檢查這封信的循環似乎是你的問題。試着用替換它:

 position = 0 
     ptr = wordTarget.find(userLetter, position) 
     while ptr != -1: 
      gameSpace[ptr] = userLetter 
      position = ptr + 1 
      ptr = wordTarget.find(userLetter, position) 

     if position == 0: # no match ever found 
      print "letter is incorrect, try again" 
      wrongLetter.append(userLetter) 

還與while ("".join(gameSpace) != wordTarget):代替原來的for循環,你應該是好去。

+0

wordTarget變量是單詞存儲的地方,而不是字母。給我一下,我會在這裏發佈getletter代碼 –

+0

我認爲userLetter中的值是輸入的字母。如果是這樣,那麼'wordTarget.find(position,userLetter)'意思是「查找字符串wordTarget,從位置開始,找到userLetter的下一個實例。」 getLetter()函數調用後,答案中的代碼立即開始。 –

+0

我編輯了代碼並得到了錯誤:ptr = wordTarget.Find(position,userletter)。屬性錯誤:'str'對象沒有屬性'查找' –