【发布时间】:2020-01-30 16:49:21
【问题描述】:
我的代码是一个基本的刽子手游戏。我的问题是我的用户输入不断出现问题,我很确定这是因为我使用了错误的循环......
我已经观看了数小时的视频并阅读了许多以前提出的问题...我尝试只使用我所看到的所有建议,虽然有些建议像我当前的代码一样工作,但最终导致另一个问题。我真的是在乞求帮助。如果您查看我的代码,您会发现当我真正了解自己在做什么时,我会以极其详细的方式向自己解释一切。
#Word Puzzle Version 1
# Fill in the blank to guess the word.
import random, time
def main():
# display instructions
filename = 'instructions.txt'
mode = 'r'
file=open(filename,mode)
instructions=file.read()
print(instructions)
# display what is to be guessed
#import words file
filename2 = 'words.txt'
# Step 1 - Open the file
infile = open(filename2,mode)
# Step 2 - Read the file
content = infile.read()
# Step 3 - Strip the content of any leadning or trailing newline characters
content = content.strip()
# Step 4 - Additional clean up with splitlines function
all_words = content.splitlines()
# Randomly choose a word from list all_words
#I want only 1 word to be guessed
number_of_words = 1
#A sample of 1 word from my cleaned up list of words
word_list = random.sample(all_words,number_of_words)
# Use choice function from random module to choose sample from word list
answer = random.choice(word_list)
#Display word to be guessed
#Calculate the length of each word
Length = len(answer)
Underscores = (Length)*'_ '
#Prompt user to solve the puzzle
answer_so_far = 'The answer so far is '
#print('The answer so far is '+'_ '*(Length))
print(answer_so_far, Underscores)
#Prompt the player to fill in the blanks
Guess_a_letter = 'Guess a letter: '
guess =input(Guess_a_letter)
guess = guess.lower()
#If players guess in word replace the underscore
# Loop through the letters in the real word
for i in (answer):
if guess == i:
#print(answer_so_far, end = ' ')
print(guess, end = ' ')
elif guess != i:
print('_', end = ' ')
#Check if players guess is in the word
while guess:
if guess in answer:
print('\nGood job! You found the word '+(answer)+'.')
break
else:
print(answer_so_far,Underscores)
print('Not quite, the correct word was '+(answer)+'. Better luck next time.')
break
#End of game
#time.sleep(1.5)
input('Press enter to end the game.')
main ()
实际结果应该如下所示 正确时:
说明
目前的答案是_ _ _ _ _
猜一个字母:a
目前的答案是_ _ _ a _
干得好!你找到了(随机词)!
按回车键结束游戏。
当不正确时:
说明
目前的答案是_ _ _ _ _
猜一个字母:a
目前的答案是_ _ _ _ _
不完全是。正确的词是(随机词)。下次祝你好运。
按回车键结束游戏。
【问题讨论】:
-
mode = 'r'-- 有点无意义的变量。变量应该增加可读性,而不是减损它。 -
你所说的“古怪”是什么意思?实际发生了什么?
-
嗨,狮子座。摇摇晃晃的意思是我的答案区域一直以不同的方式出现。我将在我的问题的编辑版本中进行说明。
标签: python python-3.x list loops