Hangman程序中的多个错误

时间:2016-01-21 06:29:16

标签: python-2.7 2d-games

我最近一直在教我自己在python中编程并决定制作这个游戏。除了一些事情之外,我在大多数事情上取得了成功

  1. 当输入的字母不正确时,该字母会附加到错误的字母数组中,以便在gamespace数组中找到与用户信息相同的多个位置。例如:如果我输入“the”作为wordtarget,我得到t, h和e打印2次进入错误的字母数组。无论这封信输入错误的字母数组
  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()
    

    我猜测问题在于我正在运行的for循环以及我正在检查正确答案的方式,但无法弄明白。

1 个答案:

答案 0 :(得分: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循环,你应该好好去。

相关问题