0
def main():
    #word = input("Word to guess for player 2:")
    word = ['h','e','l','l','o']
    word2 = "hello"
    #make a list of _ the same length as the word
    display =[]
    for i in range (0,len(word)):
        display.append("_")

    chances = int(input("Number of chances to guess word:"))
    if len(word)== 11:
        print ("Your word is too long. It has to be 10 charecters or less")
    else:
        word = word
    if chances < len(word):
        answer = input("Your word is {0} letters long , are you sure you don't want more chances? Yes or no?". format (len(word)))
        if answer == "no":
            chances= int(input("Number of chances:"))
        else:
            chances = chances
            ("Ok then lets continue with the game")
    print ("Player 2, you have {0} chances to guess the word.". format (chances))
    won = False
    underscore = False
    while chances > 0 and won == False and underscore == False:
        guess = input("Enter your guess: ")
        gC=False

        for i in range (0,len(word)):
            if guess == word[i]:
                gC=True
                display[i]=guess

        if not gC:
            chances = chances - 1

        display2 = ""
        for i in display:
            display2 = display2 + i + " "

由于某种原因,当我声明我的 while 循环时,代码不起作用,因为游戏继续进行,直到用户猜不出来。有人对我如何解决这个问题有任何建议吗?

4

2 回答 2

2

won当用户通过猜测所有字母赢得游戏时,您永远不会设置为 True。

于 2013-05-08T16:57:02.370 回答
0

这不是您原始问题的答案,而是更多代码审查,但也许您会发现它很有用。

word = list('hello')  # replaces manual splitting of string into letters

display = [ '_' ] * len(word)  # replaces build-up using for-loop

chances = input("Number ... ")  # already returns int if the user enters an int
                                # but will evaluate any valid python expression the
                                # user enters; this is a security risk as what
                                # ever is done this way will be done using your
                                # permissions
chances = int(raw_input("Number ..."))  # probably what you wanted

...
else:
    word = word  # does nothing.  remove this line and the "else:" above

chances -= 1  # replaces 'chances = chances - 1' and does the same

display2 = ' '.join(display)  # replaces the for-loop to build display2

此外,我建议使用更好的名称。在这种情况下,变量喜欢display2gC不是很有帮助。在专业编程中,您始终必须记住,您正在为下一个必须维护它的开发人员编写代码(也或什至主要是)。因此,使其具有可读性和可理解性。选择类似displayStringguessedCorrectly代替的名称。

于 2013-05-08T18:20:19.730 回答