【发布时间】:2019-10-09 14:38:50
【问题描述】:
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 次猜测。基本上是刽子手。当我执行这个程序时,它只打印指令、初始拼图状态、请求猜测然后继续要求猜测。我不明白为什么这不起作用。在获得帮助后,我将实施猜测次数。
【问题讨论】:
-
你的代码有严重的缩进问题,这对于 Python 来说真的很难理解。你能纠正吗?只需编辑您的问题,粘贴您的代码,选择它,然后使用
{}按钮将其格式化为代码。不要对大代码块使用反引号。 -
@FredLarson 完成,谢谢!
-
当我运行此代码时(在顶部添加
import random后),它一直要求输入。 -
@JohnGordon 那是我的问题,我无法停止要求猜测。
-
在编程时,您应该采取更“循序渐进”的方法,您的代码中似乎有很多基本函数没有按照您的预期执行。此外,您将某些函数与变量混淆,并且您没有使用函数返回的内容。