2017-10-10 70 views
-1

我是python編程的新手。我想在每輸入一個正確的字母后顯示一條中獎信息,如果輸入了錯誤的字母,則不會顯示信息。在我的hang子手類型/益智遊戲中實現一個while循環

我寫了我的代碼,使得它一次只接受一個字母,並減少1的嘗試次數,而不管它是錯的還是正確的。

我將如何能夠實現一個while循環,這個讓我不要讓收到此錯誤:

builtins.TypeError: 'str' object does not support item assignment

word="banana" 
word_list=list(word) 
length=len(word_list) 
word_list= set(word_list) 
word_list=list(word_list) 
answer=["_"]*length 
answer=list(answer) 
guess=[] 
count = 4 
    win=False # boolean so we do not use an identifier in our if statements  
    user_guess=window.input_string("Guess a letter: ", x, y) 
    y = y + font_height 
    guess.append(user_guess) 
    while count > 0: 
     # Removes guesses if they are not in the word so that the blanks do not fill in with incorrect letters 
     for letter in guess: 
      if letter not in word_list: 
       guess.remove(letter) 
      else: 
       win=True 
     # Replaces blanks in empty list with the letter guess 
     for place,letter in enumerate(list(word)): 
      for i in range(len(guess)): 
       if letter == guess[i]: 
        answer[place]=guess[i] 
     answer=" ".join(answer) 
     update_message = 'The answer so far is: ' 
     window.draw_string(update_message + answer,x,y) 
     y = y + font_height 
    #End Game 
    win_message = 'Good job! You got the word.' 
    lose_message = 'Not quite, the correct word was: '+word +' Better luck next time' 

    if win: 
     window.draw_string(win_message,x,y) 
     y = y + font_height 
     count -=1 
    else: 
     window.draw_string(lose_message,x,y) 
     y = y + font_height 
     count -=1 
+0

你使用什麼庫?看起來不像pygame。請提供[最小,完整且可驗證的示例](https://stackoverflow.com/help/mcve)。 – skrx

回答

1

請注意這個任務:answer=" ".join(answer)。在作業之前,answer是一個字符串列表。分配後,answer成爲一個字符串。

所以,在while循環的下一次迭代,answer[place]=guess[i]變成無效的,因爲Python不允許通過指定「性格」一些地方的字符串修改字符串。

確實需要一些時間才能找到故障。在未來提問時,最好提供信息,如「程序中的哪一行鍼對錯誤消息」。