如何自动将参数传递给特定对象上的函数

2024-07-03 06:13:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Python制作一个基于文本的游戏。我设置了一个radar()函数,但目前唯一的使用方法是玩家直接向控制台输入参数。我想程序来检测车辆的球员是驾驶和通过任何属性的车辆需要通过自动无需球员必须键入他们。你知道吗

例如 而不是玩家必须输入 'a.radar([100100100],100)'为了使用radar()函数,我希望玩家只需要输入'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)

Tags: instancesnameself玩家rangeabsdescriptiondesc
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)

像其他人一样。你知道吗

看,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()的调用将导致自动找到用户控制的实例并对其调用radar。你知道吗

相关问题 更多 >