在我的刽子手类型/益智游戏中实现while循环

时间:2017-10-10 06:57:25

标签: python-3.x while-loop pygame

我是python编程的新手。我想在每个正确的字母输入后显示一条获胜消息,如果输入的字母不正确,则不显示任何消息。

我编写了我的代码,这样它一次只接受一个字母并将尝试减少1,无论它是错还是正确。

我如何能够在其中实现while循环,以便我不会一直收到此错误:

  

builtins.TypeError:'str'对象不支持项目分配

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

1 个答案:

答案 0 :(得分:1)

请注意这项任务:answer=" ".join(answer)。在分配之前,answer是一个字符串列表。分配后,answer成为字符串。

因此,在while循环的下一次迭代中,answer[place]=guess[i]变为无效,因为python不允许通过分配"字符来修改字符串"到某个地方。

找到错误确实需要一些时间。在将来提问时,您最好提供信息,例如"程序中的哪一行定位错误消息"