Bullet.FromDocument: Abstract weird constructor handling.
[python-bulletml.git] / bulletml / impl.py
index 938e9e2..aa911fa 100644 (file)
@@ -305,6 +305,13 @@ class Bullet(object):
         self._actions = [Action(self, None, action, params, rank)
                          for action, params in actions]
 
+    @classmethod
+    def FromDocument(cls, doc, x=0, y=0, direction=0, speed=0, target=None,
+                     params=(), rank=0.5, Action=Action):
+        """Construct a new Bullet from a loaded BulletML document."""
+        actions = [a(params, rank) for a in doc.actions]
+        return cls(x, y, direction, speed, target, actions, rank, Action)
+
     def __repr__(self):
         return ("%s(%r, %r, accel=%r, direction=%r, speed=%r, "
                 "actions=%r, target=%r, vanished=%r)") % (
@@ -314,11 +321,17 @@ class Bullet(object):
 
     @property
     def aim(self):
-        """Angle to the target, in radians."""
-        if self.target is None:
-            return self.direction
+        """Angle to the target, in radians.
+
+        If the target does not exist or cannot be found, return 0.
+        """
+        try:
+            target_x = self.target.x
+            target_y = self.target.y
+        except AttributeError:
+            return 0
         else:
-            return math.atan2(self.target.x - self.x, self.y - self.target.y)
+            return math.atan2(target_x - self.x, self.y - target_y)
 
     @property
     def finished(self):