-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathksp_part_resource.py
265 lines (220 loc) · 7.96 KB
/
ksp_part_resource.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
__author__ = 'Paul'
import copy
from ksp_resources import ALL_RESOURCES, KSPModule, KSPModuleKeywords
class IterPartRegistry(type):
def __init__(cls, name, bases, attrs):
super().__init__(name, bases, attrs)
cls._registry = {}
def __contains__(cls, item):
return (cls._registry.__contains__(item) or
any(c.__contains__(item) for c in cls.__subclasses__()))
def __iter__(cls):
# return (c for c in cls._registry.values() if isinstance(c, cls))
yield from cls._registry.values()
for subcls in cls.__subclasses__():
yield from subcls
def __call__(cls, name, *args, **kwargs):
if name not in KSPPart:
ret = super().__call__(name=name, *args, **kwargs)
cls._registry[name] = ret
else:
ret = KSPPart[name]
if isinstance(ret, cls):
ret.modify(**kwargs)
else:
raise TypeError(name + " is " +str(type(ret)) + ", expected " + str(cls))
return ret
def __getitem__(cls, item):
try:
return cls._registry[item]
except KeyError:
for subcls in cls.__subclasses__():
try:
return subcls.__getitem__(item)
except KeyError:
pass
raise
def __len__(cls):
return len(cls._registry) + sum(c.__len__() for c in cls.__subclasses__())
def __delitem__(cls, key):
try:
del cls._registry[key]
return
except KeyError:
for subcls in cls.__subclasses__():
try:
subcls.__delitem__(key)
return
except KeyError:
pass
raise
class KSPPart(object, metaclass=IterPartRegistry):
"""
Main part class
"""
_resourceNameBindings = {}
def __getattr__(self, item):
if item in self._resourceNameBindings:
return self.resources[self._resourceNameBindings[item]]
if item in KSPModuleKeywords:
return sum(getattr(m, item, 0) for m in self.modules)
raise AttributeError(item)
def __init__(self, name, mass, techrequired="start", title=None, price=0, extra_modules=None, resources=None, enabled=True):
"""
Creates basic part
:param name: id
:type name: str
:param mass: mass
:type mass: float
:param extra_modules: set containing all extra modules.
:param resources: dictionary containing resource, amount keys
:type resources: {KSPResource: float}
"""
self.__name = name
# self._registry.append(self)
self.mass = mass
self.price = price
if title is None:
self.title = name
else:
self.title = title
if extra_modules is not None:
self.modules = copy.deepcopy(extra_modules)
else:
self.modules = set()
if resources is not None:
self.resources = copy.copy(resources)
else:
self.resources = {}
self.enabled = enabled
self.tech_required = techrequired
def modify(self, **kwargs):
for k, v in kwargs.items():
if k in self._resourceNameBindings:
self.resources[self._resourceNameBindings[k]] = v
elif isinstance(v, KSPModule):
self.modules.discard(v)
self.modules.add(v)
else:
setattr(self, k, v)
def hasResource(self, name):
if name in self._resourceNameBindings:
name = self._resourceNameBindings[name]
return name in self.resources
def getResource(self, name):
if name in self._resourceNameBindings:
name = self._resourceNameBindings[name]
return self.resources[name]
def hasModule(self, name):
return any(m.name == name for m in self.modules)
def getModule(self, name):
return next(m for m in self.modules if m.name == name)
@property
def name(self):
return self.__name
@property
def energy(self):
try:
return self.resources["ElectricCharge"]
except KeyError:
return 0
@property
def total_mass(self):
return self.mass + sum(ALL_RESOURCES[k].density * v for k, v in self.resources.items())
@property
def total_price(self):
return self.price + sum(ALL_RESOURCES[k].price * v for k, v in self.resources.items())
def __hash__(self):
return hash((self.name, type(self)))
def __eq__(self, other):
return type(self) == type(other) and self.name == other.name
def __str__(self, *args, **kwargs):
return self.name
class StructuralPart(KSPPart):
pass
class PayloadPart(KSPPart):
pass
class ControlPart(KSPPart):
"""
Control probe class
"""
_resourceNameBindings = copy.copy(KSPPart._resourceNameBindings)
_resourceNameBindings.update(
{"ElectricCharge":"ElectricCharge"}
)
def __init__(self, name, mass, command_module, controlwheel_module=None, ElectricCharge=0, crew_capacity=0, **kwds):
"""
Creats control probe
:param name: ID
:type name: str
:param mass: mass
:type mass: float
:param command_module: Command module (copied)
:type command_module: ModuleCommand
:param controlwheel_module: sas module (copyied)
:type controlwheel_module: ModuleReactionWheel
:param ElectricCharge: Amount of energy
:type ElectricCharge: float
"""
super().__init__(name=name, mass=mass, **kwds)
self.modules.add(copy.deepcopy(command_module))
self.resources["ElectricCharge"] = ElectricCharge
if controlwheel_module is not None:
self.modules.add(copy.deepcopy(controlwheel_module))
self.crew_capacity = crew_capacity
class ControlProbe(ControlPart):
pass
class ControlCommand(ControlPart):
_resourceNameBindings = copy.copy(ControlPart._resourceNameBindings)
_resourceNameBindings.update(
{"mono_prop_amount":"Mono"}
)
def __init__(self, name, mass, command_module, controlwheel_module, ElectricCharge=0, mono_prop_amount=0,
crew_capacity=0, **kwds):
super().__init__(name=name, mass=mass, command_module=command_module, controlwhell_module=controlwheel_module,
ElectricCharge=ElectricCharge, crew_capacity=crew_capacity, **kwds)
self.resources["Mono"] = mono_prop_amount
class BatteryPack(KSPPart):
"""
Control probe class
"""
_resourceNameBindings = copy.copy(KSPPart._resourceNameBindings)
_resourceNameBindings.update(
{"electric_charge":"ElectricCharge"}
)
def __init__(self, name, mass, electric_charge, **kwds):
super().__init__(name=name, mass=mass, **kwds)
self.resources["ElectricCharge"] = electric_charge
class EnergyGenerationPart(KSPPart):
def __init__(self, name, mass, ModuleEnergy, **kwargs):
super().__init__(name=name, mass=mass, **kwargs)
self.modules.add(copy.deepcopy(ModuleEnergy))
def getChargeRate(self, distance=0):
l=[m.getChargeRate(distance) for m in self.modules if hasattr(m,"getChargeRate")]
return sum(l)
class Antenna(KSPPart):
pass
def ModifyOrAdd(cls, name, pred=None, **kwargs):
if pred is None:
pred = lambda x: x.name == name
all_old = (x for x in cls if pred(x))
done = False
for old in all_old:
done = True
old.modify(**kwargs)
if done:
return None
else:
return cls(name=name, **kwargs)
def Modify(pred=None, name=None, **kwargs):
if pred is None:
if name is not None:
pred = lambda x: x.name == name
else:
pred = lambda x: True
try:
all_old = (old for old in KSPPart if pred(old))
for old in all_old:
old.modify(**kwargs)
except StopIteration:
return None