我想更新我的基本游戏。我已经做过脚本从文本文件中获取单词的操作,现在我想将它们分成模块,因为我有不同的文本文件和不同的单词。
我有我的主要脚本jumble_game.py:
import random
import amazement
#Welcome the player
print("""
Welcome to Word Jumble.
Unscramble the letters to make a word.
""")
def wordlist(file):
with open(file) as afile:
global the_list
the_list = [word.strip(",") for line in afile for word in line.split()]
print(the_list)
def main():
score = 0
for i in range(4):
word = random.choice(the_list)
theWord = word
jumble = ""
while(len(word)>0):
position = random.randrange(len(word))
jumble+=word[position]
word=word[:position]+word[position+1:]
print("The jumble word is: {}".format(jumble))
#Getting player's guess
guess = input("Enter your guess: ").lower()
#congratulate the player
if(guess==theWord):
print("Congratulations! You guessed it")
score +=1
else:
print ("Sorry, wrong guess.")
print("You got {} out of 10".format(score))
#filename = "words/amazement_words.txt"
wordlist(filename)
main()
我希望将文件amazement.py导入jumble_game.py,因为我希望用户选择从中选择单词的组。
amazement.py:
filename = "amazement_words.txt"
我收到此错误:
File "jumble_game.py", line 49, in
wordlist(filename)
NameError: name 'filename' is not defined
如果我以另一种方式执行此操作,则将主脚本导入amazement.py并运行后者,则代码可以正常运行。
任何线索我想念什么?还是Python初学者,所以请多多包涵。:)
感谢您的帮助/建议!