我一直用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
答案 0 :(得分:1)
您需要将guesses_left = MAX_GUESSES - guesses
置于while word_guessed() is False:
循环内。就像现在一样,您在guesses_left = MAX_GUESSES - guesses
时设置guesses == 0
,然后仅在循环内更改guesses
。这将使guesses_left
保持不变。
答案 1 :(得分:1)
您不会重新计算guesses_left
。在每次迭代开始时,您必须执行guesses_left = MAX_GUESSES - guesses