我目前是一名新学生学习python。这是我第一次做很多计算机编码的真实经历。对于我的项目,我必须在三个不同难度级别的空白测验中创建填充。一旦用户选择了难度,游戏应根据难度打印不同的段落。游戏的每个部分都运行正常,但我在创建“难度选择器”时遇到了问题。"无论我选择哪种难度,游戏都会按顺序滚动简单,中等和硬级别,然后崩溃。
下面我已经介绍了介绍性文字和难度选择器。我会喜欢一些帮助。我确信有一些我不明白的事情。谢谢!
def introduction():
print '''Welcome to Kevin's European Geography Quizzes.
Test your knowledge of European geography. \n'''
difficulty = raw_input('''Do you want to play an easy, medium, or hard game?
Please type the number 1 for easy, 2 for medium, or 3 for hard.\n''' )
game_chooser(difficulty)
def game_chooser(difficulty):
cursor = 0
difficulty_choice = [easy_game(), medium_game(), hard_game()]
#each element of the above list links to a procedure and starts one of the
#mini-games.
while cursor < len(difficulty_choice):
if difficulty != cursor:
cursor += 1
else:
difficulty_choice[cursor]
break
答案 0 :(得分:1)
如果您只想打印某些内容但是如果每个级别都有单独的代码块,则可以使用if else
,然后为每个级别定义一个函数并使用此模式:
您可以定义功能块,并根据用户输入调用它们:
# define the function blocks
def hard():
print ("Hard mode code goes here.\n")
def medium():
print ("medium mode code goes here\n")
def easy():
print ("easy mode code goes here\n")
def lazy():
print ("i don't want to play\n")
# Now map the function to user input
difficulty_choice = {0 : hard,
1 : medium,
4 : lazy,
9 : easy,
}
user_input=int(input("which mode do you want to choose : \n press 0 for hard \n press 1 for medium \n press 4 for lazy \n press 9 for easy "))
difficulty_choice[user_input]()
然后调用功能块:
difficulty_choice[num]()
答案 1 :(得分:0)
为输入添加条件。
if difficulty == 'easy':
print("here is an easy game")
elif difficulty == 'medium':
print('here is a medium game')
elif difficulty == 'hard':
print('here is hard')
else:
print('Please enter valid input (easy, medium, hard)')
在每个if语句下放置您的游戏代码。
答案 2 :(得分:0)
您的代码遇到所有困难的原因是因为这一行:
difficulty_choice = [easy_game(), medium_game(), hard_game()]
当Python看到类似easy_game()
的内容时,它会调用easy_game
函数并将其替换为结果。你不想调用这个函数,所以你可以取下括号来代替函数:
difficulty_choice = [easy_game, medium_game, hard_game]
这意味着您必须在将其从阵列中取出后调用该函数。
至于崩溃,当你使用raw_input()
时,你会得到一个字符串。这意味着当您输入1
来决定简单游戏时,您会获得字符1
,其由数字49
表示。这就是为什么您的代码会经历所有事情并崩溃的原因:您的1
实际上是49
。实际上,如果您在解释器中输入1 < '1'
,那么您将获得True
。
要解决此问题,您可以将raw_input()
的结果传递给int()
函数,该函数将解析它并为您提供正确的整数(如果不能,则抛出异常)解析)。 introduction
的最后一行看起来像game_chooser(int(difficulty))
。
你也可以跳过大部分game_chooser
的代码,只需索引到数组中(毕竟它们是什么):
def game_chooser(difficulty):
# the lack of parens here means you get the function itself, not what it returns
difficulty_choice = [easy_game, medium_game, hard_game]
#each element of the above list links to a procedure and starts one of the
#mini-games.
# note the parens to actually call the retrieved function now
difficulty_choice[difficulty]()