如何改善我的回合制游戏循环代码

时间:2018-09-25 20:14:05

标签: python-3.x function loops

我开始了创造回合制格斗游戏的旅程。我只是想获得您对代码的反馈。我在尝试找出不重复以下代码行的方式时遇到了一个问题...

move_command = input("What move would you like to use? one, two, three, or four? ")


  if move_command == "one":
      for key in player.move_one:
          print("You used {}".format(key))
          print("")
      bot_damage = player.move_one[key][0]
      mana_used = player.move_one[key][1]


  if move_command == "two":
      for key in player.move_two:
          print("You used {}".format(key))
          print("")
      bot_damage = player.move_two[key][0]
      mana_used = player.move_two[key][1]

  if move_command == "three":
      for key in player.move_three:
          print("You used {}".format(key))
          print("")
      bot_damage = player.move_three[key][0]
      mana_used = player.move_three[key][1]



  if move_command == "four":
      for key in player.move_four:
          print("You used {}".format(key))
          print("")
      bot_damage = player.move_four[key][0]
      mana_used = player.move_four[key][1]

我相信我可以创建一个函数来帮助我将这4个块削减为两个,但是我不确定该怎么做。我知道我必须对我的player.move_“ one”属性和我的move_command保持灵活,任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

您可以将选项变成字典,并将每个选项分配为键,并将结果分配为其值。从那里,您可以简单地将键传递给将使用关联值的函数。

move_command = input("What move would you like to use? one, two, three, or four? ")

move_dict = {"one": player.move_one, "two": player.move_two, "three": player.move_three, "four": player.move_four}

do_command(move_command)

do_command()的定义为:

def do_command(command_number):
    for key in move_dict[command_number]:
        print("You used {}".format(key))
        print("")
      bot_damage = player.move_one[key][0]
      mana_used = player.move_one[key][1]