我目前正在为CompSci课程制作游戏,我想缩短我们随机的怪物战斗。有没有办法让我这样做当我调用def我可以根据随机变量更改名称?这是我正在谈论的片段
Loop = True
MonsterType = random.randint(1,20)
Monster*()
battle()
我有
def Monster1
def Monster2
def Monster3
.
.
.
def Monster20
我希望第一个片段中的*是变量MonsterType,有没有办法让它做到这一点?即当它运行时,如果MonsterType = 15,那么它将被称为Monster13()。
答案 0 :(得分:2)
是的,有一种方法,创建一个dictionary
并将每个函数映射到一个整数:
import random
def monster1():
print "Hello monster1"
def monster2():
print "Hello monster2"
def monster3():
print "Hello monster3"
def monster4():
print "Hello monster4"
d = {1:monster1, 2:monster2, 3:monster3, 4:monster4}
#When you need to call:
monsterType = random.randint(1, 4)
d[monsterType]()
答案 1 :(得分:1)
在阅读了您想要完成的任务后,我相信使用OOP对您的情况会更好:
# A class for a bunch of monsters
class Mob(object):
def __init__(self, num_monsters):
self._num_monsters = num_monsters
self._monsters = []
for i in range(self._num_monsters):
# randomly create a type of monster based on the number of monsters
self._monsters.append(Monster(random.randint(0, self._num_monsters)))
# Each monster has a type that is attacks with
class Monster(object):
def __init__(self, monster_type):
self._type = monster_type
def attack(self):
print(self._type)
test = Mob(20)
答案 2 :(得分:1)
听起来像你使用了一点OOP。我建议:
class Monster(object):
def __init__(self, name):
self.name = name
def do_work(self):
print self.name
然后创建一个可以生成n个怪物对象的管理器,并提供一个静态方法来管理要调用的对象:
class MonsterManager(object):
monsters = []
def call_monster(self, index):
monsters[i].do_work()
有了这个,你可以有更好的用途,如下:
manager = MonsterManager();
manager.monsters.append(Monster('Monster1')
manager.monsters.append(Monster('Monster2')
# etc
# then call a single monster
manager.call_monster(i)