在Hang子手中触发胜利功能

时间:2019-03-23 08:22:15

标签: python python-3.x

我对编码还很陌生,并且已经开始为学校项目编码子手游戏。目前,我遇到有关触发胜利的问题。我还遇到另一个问题,即用户输入后什么都不打印。任何帮助将不胜感激。

print ("WELCOME, YOU ARE PLAYING HANGMAN!")

import random
def guess():

    word = (random.choice(open("Level1py.txt").readline().split()))
    guesses = 8

#If letterguessed == current letter in word, add that letter else add a _

#guess function
guessword = []
word = (random.choice(open("Level1py.txt").readline().split()))
guesses = 8
def checkLetter(letter, word, guess_word):
for c in word:
    if c == letter:
        guess_word[word.index(c)] = c
        word_list = list(word)
        word_list[word.index(c)] = "*"
        word = ''.join(word_list)
        print(guess_word)
guess_word = ['_' for x in word]
while '_' in guess_word:
guess = input('Letter: ')
print(checkLetter(guess, word, guess_word))
while guesses > -1 and not guess_word == word:
            guess = input("Guess:")
            if guess in word:
                    print("correct letter")
                    print(guess_word)
            else:
                    print("incorrect")
                    guesses -= 1
            if guesses < 0:
                        print ("""
_______
|/   |    
|   (_)    
|   /|\          
|    |        
|   / \        
|              
|___          
HANGMAN""""You guessed wrong. The correct word was: " + str(word))
            else:
                    print("congrats, you won")

1 个答案:

答案 0 :(得分:0)

您确实需要检查缩进并简化代码。永远不会触发胜利的原因是,永远不会到达else语句(由于while循环中的条件不是guess_word == word)。您需要使游戏结束退出while循环。您也不必在多个位置打印guess_word

这是工作版本。您可以在这里进行测试:https://repl.it/@glhr/hangman。我对该词进行了硬编码,而不是从文件中提取该词,因为那部分与您的问题无关。

print ("WELCOME, YOU ARE PLAYING HANGMAN!")

guessword = []
word = "test"
guesses = 8
guess_word = ['_' for x in word]
def checkLetter(letter, word, guess_word):
    for c in word:
            if c == letter:
                    guess_word[word.index(c)] = c
                    print(guess_word)

while '_' in guess_word and guesses > -1:
    guess = input('Letter: ')

    if guess in word:
                    print("correct letter")
    else:
                    print("incorrect")
                    guesses -= 1
                    print (guesses," guesses left")
    checkLetter(guess, word, guess_word)

if guesses < 0:
    print ("""
    |/   |    
    |   (_)    
    |   /|\          
    |    |        
    |   / \        
    |              
    |___          
    HANGMAN"""" You guessed wrong. The correct word was: " + str(word))
else:
    print("congrats, you won")