import random
def main():
num_guesses = 4
instruction_file=open('instructions.txt', 'r')
list_of_words = ['apple', 'banana', 'watermelon', 'kiwi', 'pineapple', 'mango']
answer=random.choice(list_of_words)
puzzle=['_'] * len(answer)
def display_instructions(instruction_file):
file_contents=instruction_file.read()
instruction_file=instruction_file.close()
print(file_contents)
def get_guess(num_guesses):
print('The number of guesses remaining is ' + str(num_guesses)+ '.')
letter_input = input("Guess a letter ")
return letter_input
def update_puzzle_string(letter_input,puzzle,answer):
if get_guess(num_guesses) in answer:
for i,x in enumerate(answer):
if x is get_guess:
puzzle[i]=letter_input
return True
def display_puzzle_string(puzzle):
print('The current state of the puzzle is '+str(puzzle))
def is_word_found(puzzle,answer):
is_word_found=True
puzzle_string=print(''.join(puzzle))
if puzzle_string == answer:
return False
def play_game(answer,puzzle):
while True:
display_puzzle_string(puzzle)
get_guess(num_guesses)
update_puzzle_string(get_guess,puzzle,answer)
print(str(puzzle))
is_word_found(puzzle,answer)
display_instructions(instruction_file)
play_game(answer,puzzle)
main()
对于格式问题,我们深表歉意。该程序的目标是收集用户的猜测,然后将其与从列表中随机选择的单词进行比较,这样做后,它会更新一个谜题,其中该字母所属的位置有空白,如果该单词的所有字母都被猜到,则用户是告诉他们是正确的。用户得到 4 个猜测。基本上就是刽子手。当我执行这个程序时,它只是打印指令、初始拼图状态、请求猜测,然后不断要求猜测。我不明白为什么这不起作用。在获得帮助后,我将实现猜测的数量。
最佳答案
import random
def main():
num_guesses = 4
instruction_file=open('instructions.txt', 'r')
list_of_words = ['apple', 'banana', 'watermelon', 'kiwi', 'pineapple', 'mango']
answer=random.choice(list_of_words)
puzzle=['_'] * len(answer)
def display_instructions(instruction_file):
file_contents=instruction_file.read()
instruction_file=instruction_file.close()
print(file_contents)
def get_guess(num_guesses):
print('The number of guesses remaining is ' + str(num_guesses)+ '.')
letter_input = input("Guess a letter: ")
return letter_input
def update_puzzle_string(letter_input,puzzle,answer):
for i,x in enumerate(answer):
if x is letter_input:
puzzle[i]=letter_input
return
def display_puzzle_string(puzzle):
print('The current state of the puzzle is '+str(puzzle))
def is_word_found(puzzle,answer):
is_word_found=True
puzzle_string=print(''.join(puzzle))
if puzzle_string == answer:
return False
def play_game(answer,puzzle):
while True:
display_puzzle_string(puzzle) #display '_ _ _ _ _'
guess = get_guess(num_guesses)
update_puzzle_string(guess,puzzle,answer)
#print(str(puzzle)) #this statement is causing the repetitive puzzle prints
is_word_found(puzzle,answer)
display_instructions(instruction_file)
play_game(answer,puzzle)
main()
修复格式问题后,代码现在会反复要求猜测并接受输入。我认为问题主要存在于格式中,因为我现在没有收到错误。另外,你之前有随机导入吗?干杯
编辑:
查看 update_puzzle_string()
和 play_game
的更改。您重复调用 get_guess 函数而不是使用其初始返回值。
编辑2:(请参阅此答案的评论)
关于python - 为什么我的函数在调用时不会激活?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58306650/