【问题标题】:Randomizing a function each time its called每次调用函数时随机化一个函数
【发布时间】:2012-08-20 00:42:22
【问题描述】:

如何让 Python 3 每次调用时从列表中随机选择一个项目? 我有两个需要执行此操作的功能。我尝试过 item = random.randint() 和 item = random.choice(),但它们只随机化一次然后将其存储到 item 中。

这是两个函数。 使用函数 1,我需要在每次调用它时随机化该项目,因此玩家每次都会获得一个随机项目。对于功能 2,我需要玩家和老鼠的攻击在我选择的数字内随机化。所以每当玩家攻击时,它在 10 到 30 之间,而当老鼠攻击时,它在 10 到 15 之间。它必须每回合都这样做。

这可能吗?

功能1。

def chest(sector):
    item = random.choice(items)
    print("You see a chest, you unlock it and inside is '{0}'".format(item))
    print()
    if item in inventory:
        print("You already have a {0}".format(item))
    item_take = input("Do you wish to take the '{0}'?: ".format(item)).lower()
    if item_take == ("yes"):
        inventory.append(item)
        if item == "Armor":
            player["hp"] = 150
        print("The {0} has been added to your inventory!".format(item))
        sector()
    else:
        print("You don't take the '{0}'!".format(item))
        print()
        sector()

功能 2.

player = dict(
    name = " ",
    att = random.randint(10, 30),
    hp = 100,)

rat = dict(
    name = "Rat",
    att = random.randint(10, 15),
    hp = 20,)


def attack(player, enemy):
    firstAtt = random.randint(1, 2)#Player = 1, Enemy = 2. Checks to see who goes first.
    if firstAtt == 1:
        while player["hp"] > 0 and enemy["hp"] > 0:
            enemy["hp"] = enemy["hp"] - player["att"]
            print("You have dealt {0} damage to the {1}!".format(player["att"], enemy["name"]))
            if enemy["hp"] <= 0:
                print()
                print("You have killed the {0}".format(enemy["name"]))
                print("You have {0}HP left.".format(player["hp"]))
                break

            player["hp"] = player["hp"] - enemy["att"]
            print("The {0} has dealt {1} damage to you!".format(enemy["name"], enemy["att"]))
            if player["hp"] <= 0:
                print()
                print("The {0} has killed you!".format(enemy["name"]))
                break

    elif firstAtt == 2:
        while player["hp"] > 0 and enemy["hp"] > 0:
            player["hp"] = player["hp"] - enemy["att"]
            print("The {0} has dealt {1} damage to you!".format(enemy["name"], enemy["att"]))
            if player["hp"] <= 0:
                print()
                print("The {0} has killed you!".format(enemy["name"]))
                break

            enemy["hp"] = enemy["hp"] - player["att"]
            print("You have dealt {0} damage to the {1}".format(player["att"], enemy["name"]))
            if enemy["hp"] <= 0:
                print()
                print("You have killed the {0}".format(enemy["name"]))
                print("You have {0}HP left.".format(player["hp"]))
                break

【问题讨论】:

  • 是什么让你觉得 random.choice 不是每次调用函数时都随机化?
  • 我希望我可以 +1 你的用户名,@NoobMcNoobNoob
  • @BrenBarn 哦,它确实是随机的。我的列表中没有足够的项目。哎呀。

标签: python random python-3.x


【解决方案1】:

chest() 很好。

对于attack(),将att元素转为函数,然后酌情调用。

  att=lambda: random.randint(...),

 ...

      dmg = player['att']()
       ...

【讨论】:

    【解决方案2】:

    除非您尝试完全无类(可能作为课堂作业或作为理解函数式编程或字典的练习),否则在这种情况下,python 类会大量清理您的代码。这也有许多连锁反应。例如,在这段代码中,我可以很容易地访问最小和最大攻击值,可能会显示在棋盘上的角色标记或攻击对话框中。这是一个准系统示例,您需要对其进行扩展并进一步修改以满足您的需要。就个人而言,我会包含一个“take_damage”函数来处理攻击造成的伤害(这样,如果我想要或在它们自己的函数中执行其他与伤害相关的效果,我可以根据所承受的伤害减少 atk_min 或 atk_max)和每个变量,我都会有另一个“当前”变量(self.current_atk_min,self.current_atk_max,self.current_hp)等。这样,我可以独立于当前变量跟踪原始值并应用项目奖励,魔法奖励,伤害惩罚等,而不会丢失原始值。

    from random import randint
    class Character():
        def __init__(self, name, atk_min, atk_max, hp):
            self.name = name
            self.atk_min = atk_min
            self.atk_max = atk_max
            self.hp = hp
    
        def attack(self):
            return randint(self.atk_min, self.atk_max)
    
    rat = Character('rat', 10, 15, 20)
    player = Character('Player', 15, 30, 100)
    

    我知道代码更长,但更容易被发现,Future You 会在 2 年后感谢 Current You 2 年没有看它。我不得不把它全部扔掉,因为我不再知道它应该做得足够好来智能地改变它)。

    【讨论】:

    • 我打算用我学到的东西制作一个游戏,然后继续上课。谢谢,我会试试这个!
    • 是的,我明白了。这是有道理的,尤其是因为课程很难掌握(至少它们对我来说是这样)。我只是想确保您考虑过这一点,因为这是表示它们的“标准”方式。
    猜你喜欢
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多