如何自动将参数传递给某些对象上的函数

时间:2014-01-04 08:35:19

标签: python

我正在尝试使用Python制作基于文本的游戏。我设置了一个radar()函数,但目前使用它的唯一方法是玩家直接在控制台中输入参数。我希望程序能够检测到玩家正在驾驶哪辆车并通过该车辆的任何属性需要自动通过,而玩家不必输入它们。

例如 而不是玩家必须输入 'a.radar([100,100,100],100)'为了使用radar()函数,我希望玩家只需输入'雷达',并自动传递所有其他参数。我怎样才能做到这一点?我应该完全重构这个代码吗?

我的代码:

class Mobilesuits:
    #class global variables/methods here
    instances = [] #grid cords here
    def __init__(self,armor,speed,name,description,cockpit_description,\
                 radar_range, coordinates):
        Mobilesuits.instances.append(self)
        self.armor=armor
        self.speed=speed
        self.name=name
        self.description=description
        self.cockpit_description=cockpit_description
        self.radar_range=radar_range
        self.coordinates=coordinates


    def radar(self, coordinates, radar_range):
        for i in range(len(a.instances)):
            cordcheck=a.instances[i].coordinates
            if cordcheck == coordinates:
                pass
            elif (abs(cordcheck[0]-coordinates[0]) <= radar_range) and \
                (abs(cordcheck[1]-coordinates[1]) <= radar_range) and \
                (abs(cordcheck[2]-coordinates[2]) <= radar_range):
                print("%s detected at %s ") %(a.instances[i].description, a.instances[i].coordinates)



a=Mobilesuits(100,100,"Leo","leo desc","dockpit desc",100,[100,100,100])
b=Mobilesuits(100,100,"Leo","leo desc","dockpit desc",100,[300,100,100])
c=Mobilesuits(100,100,"Leo","leo desc","dockpit desc",100,[100,150,100])

a.radar([100,100,100], 100)

2 个答案:

答案 0 :(得分:2)

让您的程序使用raw_input函数输入:

user_input = raw_input()

然后根据输入做一些事情:

if user_input == "some_command":
    do_something(appropriate, variables)

例如,

if user_input == "radar":
    a.radar([100,100,100], 100)

您可能还想更改radar方法获取参数的方式。看起来coordinatesradar_range参数中的至少一个应该来自self的相应属性。例如,如果移动服的雷达应该自动使用移动套装自己的坐标和雷达范围,您可以按如下方式编写方法:

def can_detect(self, other):
    for own_coord, other_coord in zip(self.coordinates, other.coordinates):
        if abs(own_coord - other_coord) > self.radar_range:
            return False
    return True

def radar(self):
    for other in Mobilesuits.instances:
        if other is not self and self.can_detect(other):
            print "%s detected at %s" % (other.description, other.coordinates)

答案 1 :(得分:0)

就像builtins那样。

看,str()函数只是对__str__函数的专门调用。 object类默认为__str__,如果您未使用p3k,str()对于没有__str__的对象有一些逻辑。

最后,str()内置可能看起来像这样(概念上,实现可能完全不同):

def str(obj):
    try:
         return obj.__str__()
    except AttributeError:
         return default_behaviour(obj)

你可以做同样的事情。

你需要返回用户对象的功能(比如游戏中有3个玩家:A,B和C,其中A由用户控制;你需要功能get_user_player()它将返回一个实例。

然后,您需要实现无争议的radar函数:

def radar():
    return get_user_player().radar()

现在拨打radar()会自动查找用户控制的实例并在其上调用雷达。