Python游戏,答案错误的东西为什么会这样?

时间:2020-02-17 18:04:37

标签: python python-3.x

这是我的python游戏:

import random



print('H A N G M A N')
hidden_words = ['python', 'java', 'kotlin', 'javascript']
hidden_word = random.choice(hidden_words)
display = '-' * len(hidden_word)
used = []
i = 0
maxshit = 8
while i < maxshit and display != hidden_word:
    print()
    print(display)
    inp = input("Input a letter: ")
    if inp in used:
        print("No improvements")
        i += 1
    elif inp in hidden_word:
        new = ""
        used.append(inp)
        for i in range(len(hidden_word)):
            if inp == hidden_word[i]:
                new += inp
            else:
                new += display[i]
        display = new 
    else:
        print("No such letter in the word")
        i += 1
if i == maxshit:
    print("You are hanged!")
else:
    print("You survived!")




print()
print('Thanks for playing!')
print("We'll see how well you did in the next stage")

当您输了8个错误答案并打印“您被绞死!”时,它会很好地工作,但是如果答案很好,您将获胜,并显示“您已幸存”;如果您打印了所有红色的单词,则会显示“否”即兴表演!”或者,如果您没有输入任何单词,它将打印“世界上没有这样的字母!”。 但是当您输入时

$ python govno.py
H A N G M A N

------
Input a letter: j
No such letter in the word

------
Input a letter: i

----i-
Input a letter: g
No such letter in the word

----i-
Input a letter: g
No such letter in the word

----i-
Input a letter: k

k---i-
Input a letter: g
No such letter in the word

k---i-
Input a letter: g
No such letter in the word

k---i-
Input a letter: g
No such letter in the word
You are hanged!

在此输入中,您只会在6个错误之后输掉。为什么这样呢? P.S对于常见错误,我才刚刚开始

1 个答案:

答案 0 :(得分:0)

问题出在第二个循环(for循环)中,您重用了变量i。当输入在隐藏单词中并且在循环之后,变量i将被设置为比隐藏单词(“ kotlin”)的长度小5(在这种情况下为5)。之后,{ {1}}增加了3次,以值8结束,该值等于i。因此循环结束并显示了消息。

将该变量更改为其他名称(例如maxshit)。 循环应如下所示:

j
相关问题