我正在尝试用Python制作一个基于文本的游戏。我设置了雷达()函数,但目前使用它的唯一方法是播放机直接向控制台输入参数。我想要程序检测哪辆车的球员正在驾驶,并通过任何属性的车辆需要自动通过,而不需要玩家键入他们。
例如,不需要输入'a.radar(100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100,100播放器,我希望播放器只需要键入‘雷达’,所有其他参数将自动传递的‘雷达’和所有其他参数。我怎样才能做到这一点?我应该完全重构这个代码吗?
我的代码:
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)
发布于 2014-01-04 08:43:45
让您的程序接受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
方法接受参数的方式。看起来至少有一个coordinates
或radar_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)
发布于 2014-01-04 08:52:34
就像内置的一样。
听着,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()
,它将返回A实例。
然后,您需要实现您的无论证的radar
函数:
def radar():
return get_user_player().radar()
现在,对radar()
的调用将导致用户控制实例的自动查找,并在其上调用雷达。
https://stackoverflow.com/questions/20918757
复制相似问题