0

我一直在用 Python 制作这个 Hangman 游戏。问题出在 play_hangman 函数中。每次发生猜测时,恒定的“猜测”都会增加 1。我希望它打印出“%s 个猜测结果!” 我从全局常量(MAX_GUESSES)中减去局部常量(猜测)得到 %s。但是它似乎不起作用,当它应该向下增加时,它会继续吐出“剩下的 6 个猜测”。有什么建议么?

   # CONSTANTS
MAX_GUESSES = 6

# GLOBAL VARIABLES 
secret_word = 'claptrap' 
letters_guessed = []

# From part 3b:
def word_guessed():
    '''
    Returns True if the player has successfully guessed the word,
    and False otherwise.
    '''
    global secret_word
    global letters_guessed
    for i in secret_word:
        if i in letters_guessed:
            continue
        else:
            return False        
    return True


def print_guessed():
    '''
    Prints out the characters you have guessed in the secret word so far
    '''
    global secret_word
    global letters_guessed
    blanklist = []
    for i in secret_word:
        if i in letters_guessed:
            blanklist.append(i)
        else:
            blanklist.append("-")
    blanklist_string = "".join(blanklist)
    return blanklist_string

def play_hangman():
    # Actually play the hangman game
    global secret_word
    global letters_guessed
    global MAX_GUESSES
    # Put the mistakes_made variable here, since you'll only use it in this function
    mistakes_made = 0
    guesses = 0
    guesses_left = MAX_GUESSES - guesses

    while word_guessed() is False:
        print print_guessed()
        print "%s guesses left!" % guesses_left
        letter_choice = raw_input("Choose a letter:")
        if letter_choice not in secret_word:
            mistakes_made += 1
            print "you have made %s mistakes" %mistakes_made
            print "sorry, that is not in the word"
        letters_guessed.append(letter_choice)
        guesses +=1
        print "you have made %s guesses" %guesses
        word_guessed()

    while word_guessed() is True:
        print "Congratulations! You win :)"
        break
4

2 回答 2

1

你需要把guesses_left = MAX_GUESSES - guesses里面的while word_guessed() is False:循环。就像现在一样,您正在设置guesses_left = MAX_GUESSES - guesseswhen guesses == 0,然后仅guesses在循环内进行更改。那将guesses_left保持不变。

于 2013-03-19T21:10:43.947 回答
1

你不用重新计算guesses_left。在每次迭代开始时,您必须执行guesses_left = MAX_GUESSES - guesses

于 2013-03-19T21:10:59.877 回答