Action: Don't need the owner in the constructor. Factory function to create a child.
[python-bulletml.git] / bulletml / parser.py
1 """BulletML parser.
2
3 This is based on the format described at
4 http://www.asahi-net.or.jp/~cs8k-cyu/bulletml/bulletml_ref_e.html.
5
6 Unless you are adding support for new actions, the only class you
7 should care about in here is BulletML.
8 """
9
10 from __future__ import division
11
12 from math import sin, cos, radians, pi as PI
13
14 from xml.etree.ElementTree import ElementTree
15
16 # Python 3 moved this for no really good reason.
17 try:
18 from sys import intern
19 except ImportError:
20 pass
21
22 try:
23 from io import StringIO
24 except ImportError:
25 try:
26 from cStringIO import StringIO
27 except ImportError:
28 from StringIO import StringIO
29
30 from bulletml.errors import Error
31 from bulletml.expr import NumberDef, INumberDef
32
33
34 __all__ = ["ParseError", "BulletML"]
35
36 PI_2 = PI * 2
37
38 class ParseError(Error):
39 """Raised when an error occurs parsing the XML structure."""
40 pass
41
42 def realtag(element):
43 """Strip namespace poop off the front of a tag."""
44 try:
45 return element.tag.rsplit('}', 1)[1]
46 except ValueError:
47 return element.tag
48
49 class ParamList(object):
50 """List of parameter definitions."""
51
52 def __init__(self, params=()):
53 self.params = list(params)
54
55 @classmethod
56 def FromXML(cls, doc, element):
57 """Construct using an ElementTree-style element."""
58 return cls([NumberDef(subelem.text) for subelem in element
59 if realtag(subelem) == "param"])
60
61 def __call__(self, params, rank):
62 return [param(params, rank) for param in self.params]
63
64 def __repr__(self):
65 return "%s(%r)" % (type(self).__name__, self.params)
66
67 class Direction(object):
68 """Raw direction value."""
69
70 VALID_TYPES = ["relative", "absolute", "aim", "sequence"]
71
72 def __init__(self, type, value):
73 if type not in self.VALID_TYPES:
74 raise ValueError("invalid type %r" % type)
75 self.type = intern(type)
76 self.value = value
77
78 def __getstate__(self):
79 return [('type', self.type), ('value', self.value.expr)]
80
81 def __setstate__(self, state):
82 state = dict(state)
83 self.__init__(state["type"], NumberDef(state["value"]))
84
85 @classmethod
86 def FromXML(cls, doc, element, default="absolute"):
87 """Construct using an ElementTree-style element."""
88 return cls(element.get("type", default), NumberDef(element.text))
89
90 def __call__(self, params, rank):
91 return (radians(self.value(params, rank)), self.type)
92
93 def __repr__(self):
94 return "%s(%r, type=%r)" % (
95 type(self).__name__, self.value, self.type)
96
97 class ChangeDirection(object):
98 """Direction change over time."""
99
100 def __init__(self, term, direction):
101 self.term = term
102 self.direction = direction
103
104 def __getstate__(self):
105 return [('frames', self.term.expr),
106 ('type', self.direction.type),
107 ('value', self.direction.value.expr)]
108
109 def __setstate__(self, state):
110 state = dict(state)
111 self.__init__(INumberDef(state["frames"]),
112 Direction(state["type"], NumberDef(state["value"])))
113
114 @classmethod
115 def FromXML(cls, doc, element):
116 """Construct using an ElementTree-style element."""
117 for subelem in element.getchildren():
118 tag = realtag(subelem)
119 if tag == "direction":
120 direction = Direction.FromXML(doc, subelem)
121 elif tag == "term":
122 term = INumberDef(subelem.text)
123 try:
124 return cls(term, direction)
125 except UnboundLocalError as exc:
126 raise ParseError(str(exc))
127
128 def __call__(self, owner, action, params, rank, created):
129 frames = self.term(params, rank)
130 direction, type = self.direction(params, rank)
131 action.direction_frames = frames
132 action.aiming = False
133 if type == "sequence":
134 action.direction = direction
135 else:
136 if type == "absolute":
137 direction -= owner.direction
138 elif type != "relative": # aim or default
139 action.aiming = True
140 direction += owner.aim - owner.direction
141
142 # Normalize to [-pi, pi).
143 direction = (direction + PI) % PI_2 - PI
144 if frames <= 0:
145 owner.direction += direction
146 else:
147 action.direction = direction / frames
148
149 def __repr__(self):
150 return "%s(term=%r, direction=%r)" % (
151 type(self).__name__, self.term, self.direction)
152
153 class Speed(object):
154 """Raw speed value."""
155
156 VALID_TYPES = ["relative", "absolute", "sequence"]
157
158 def __init__(self, type, value):
159 if type not in self.VALID_TYPES:
160 raise ValueError("invalid type %r" % type)
161 self.type = intern(type)
162 self.value = value
163
164 def __getstate__(self):
165 return [('type', self.type), ('value', self.value.expr)]
166
167 def __setstate__(self, state):
168 state = dict(state)
169 self.__init__(state["type"], NumberDef(state["value"]))
170
171 @classmethod
172 def FromXML(cls, doc, element):
173 """Construct using an ElementTree-style element."""
174 return cls(element.get("type", "absolute"), NumberDef(element.text))
175
176 def __call__(self, params, rank):
177 return (self.value(params, rank), self.type)
178
179 def __repr__(self):
180 return "%s(%r, type=%r)" % (type(self).__name__, self.value, self.type)
181
182 class ChangeSpeed(object):
183 """Speed change over time."""
184
185 def __init__(self, term, speed):
186 self.term = term
187 self.speed = speed
188
189 def __getstate__(self):
190 return [('frames', self.term.expr),
191 ('type', self.speed.type),
192 ('value', self.speed.value.expr)]
193
194 def __setstate__(self, state):
195 state = dict(state)
196 self.__init__(INumberDef(state["frames"]),
197 Speed(state["type"], NumberDef(state["value"])))
198
199 @classmethod
200 def FromXML(cls, doc, element):
201 """Construct using an ElementTree-style element."""
202 for subelem in element.getchildren():
203 tag = realtag(subelem)
204 if tag == "speed":
205 speed = Speed.FromXML(doc, subelem)
206 elif tag == "term":
207 term = INumberDef(subelem.text)
208 try:
209 return cls(term, speed)
210 except UnboundLocalError as exc:
211 raise ParseError(str(exc))
212
213 def __call__(self, owner, action, params, rank, created):
214 frames = self.term(params, rank)
215 speed, type = self.speed(params, rank)
216 action.speed_frames = frames
217 if frames <= 0:
218 if type == "absolute":
219 owner.speed = speed
220 elif type == "relative":
221 owner.speed += speed
222 elif type == "sequence":
223 action.speed = speed
224 elif type == "relative":
225 action.speed = speed / frames
226 else:
227 action.speed = (speed - owner.speed) / frames
228
229 def __repr__(self):
230 return "%s(term=%r, speed=%r)" % (
231 type(self).__name__, self.term, self.speed)
232
233 class Wait(object):
234 """Wait for some frames."""
235
236 def __init__(self, frames):
237 self.frames = frames
238
239 def __getstate__(self):
240 return dict(frames=self.frames.expr)
241
242 def __setstate__(self, state):
243 self.__init__(INumberDef(state["frames"]))
244
245 @classmethod
246 def FromXML(cls, doc, element):
247 """Construct using an ElementTree-style element."""
248 return cls(INumberDef(element.text))
249
250 def __call__(self, owner, action, params, rank, created):
251 action.wait_frames = self.frames(params, rank)
252 return True
253
254 def __repr__(self):
255 return "%s(%r)" % (type(self).__name__, self.frames)
256
257 class Tag(object):
258 """Set a bullet tag."""
259
260 def __init__(self, tag):
261 self.tag = tag
262
263 def __getstate__(self):
264 return dict(tag=self.tag)
265
266 def __setstate__(self, state):
267 self.__init__(state["tag"])
268
269 @classmethod
270 def FromXML(cls, doc, element):
271 """Construct using an ElementTree-style element."""
272 return cls(element.text)
273
274 def __call__(self, owner, action, params, rank, created):
275 owner.tags.add(self.tag)
276
277 class Untag(object):
278 """Unset a bullet tag."""
279
280 def __init__(self, tag):
281 self.tag = tag
282
283 def __getstate__(self):
284 return dict(tag=self.tag)
285
286 def __setstate__(self, state):
287 self.__init__(state["tag"])
288
289 @classmethod
290 def FromXML(cls, doc, element):
291 """Construct using an ElementTree-style element."""
292 return cls(element.text)
293
294 def __call__(self, owner, action, params, rank, created):
295 try:
296 owner.tags.remove(self.tag)
297 except KeyError:
298 pass
299
300 class Appearance(object):
301 """Set a bullet appearance."""
302
303 def __init__(self, appearance):
304 self.appearance = appearance
305
306 def __getstate__(self):
307 return dict(appearance=self.appearance)
308
309 def __setstate__(self, state):
310 self.__init__(state["appearance"])
311
312 @classmethod
313 def FromXML(cls, doc, element):
314 """Construct using an ElementTree-style element."""
315 return cls(element.text)
316
317 def __call__(self, owner, action, params, rank, created):
318 owner.apearance = self.appearance
319
320 class Vanish(object):
321 """Make the owner disappear."""
322
323 def __init__(self):
324 pass
325
326 @classmethod
327 def FromXML(cls, doc, element):
328 """Construct using an ElementTree-style element."""
329 return cls()
330
331 def __repr__(self):
332 return "%s()" % (type(self).__name__)
333
334 def __call__(self, owner, action, params, rank, created):
335 owner.vanish()
336 return True
337
338 class Repeat(object):
339 """Repeat an action definition."""
340
341 def __init__(self, times, action):
342 self.times = times
343 self.action = action
344
345 def __getstate__(self):
346 return [('times', self.times.expr), ('action', self.action)]
347
348 def __setstate__(self, state):
349 state = dict(state)
350 self.__init__(INumberDef(state["times"]), state["action"])
351
352 @classmethod
353 def FromXML(cls, doc, element):
354 """Construct using an ElementTree-style element."""
355 for subelem in element.getchildren():
356 tag = realtag(subelem)
357 if tag == "times":
358 times = INumberDef(subelem.text)
359 elif tag == "action":
360 action = ActionDef.FromXML(doc, subelem)
361 elif tag == "actionRef":
362 action = ActionRef.FromXML(doc, subelem)
363 try:
364 return cls(times, action)
365 except UnboundLocalError as exc:
366 raise ParseError(str(exc))
367
368 def __call__(self, owner, action, params, rank, created):
369 repeat = self.times(params, rank)
370 actions, params = self.action(params, rank)
371 child = action.Child(actions, params, rank, repeat)
372 owner.replace(action, child)
373 child.step(owner, created)
374 return True
375
376 def __repr__(self):
377 return "%s(%r, %r)" % (type(self).__name__, self.times, self.action)
378
379 class If(object):
380 """Conditional actions."""
381
382 def __init__(self, cond, then, else_=None):
383 self.cond = cond
384 self.then = then
385 self.else_ = else_
386
387 def __getstate__(self):
388 if self.else_:
389 return [('cond', self.cond.expr),
390 ('then', self.then),
391 ('else', self.else_)]
392 else:
393 return [('cond', self.cond.expr), ('then', self.then)]
394
395 def __setstate__(self, state):
396 state = dict(state)
397 state["else_"] = state.pop("else", None)
398 state["cond"] = INumberDef(state["cond"])
399 self.__init__(**state)
400
401 @classmethod
402 def FromXML(cls, doc, element):
403 """Construct using an ElementTree-style element."""
404 else_ = None
405 for subelem in element.getchildren():
406 tag = realtag(subelem)
407 if tag == "cond":
408 cond = INumberDef(subelem.text)
409 elif tag == "then":
410 then = ActionDef.FromXML(doc, subelem)
411 elif tag == "else":
412 else_ = ActionDef.FromXML(doc, subelem)
413 try:
414 return cls(cond, then, else_)
415 except UnboundLocalError as exc:
416 raise ParseError(str(exc))
417
418 def __call__(self, owner, action, params, rank, created):
419 if self.cond(params, rank):
420 branch = self.then
421 else:
422 branch = self.else_
423
424 if branch:
425 actions, params = branch(params, rank)
426 child = action.Child(actions, params, rank)
427 owner.replace(action, child)
428 child.step(owner, created)
429 return True
430
431 class Accel(object):
432 """Accelerate over some time."""
433
434 horizontal = None
435 vertical = None
436
437 def __init__(self, term, horizontal=None, vertical=None):
438 self.term = term
439 self.horizontal = horizontal
440 self.vertical = vertical
441
442 def __getstate__(self):
443 state = [('frames', self.term.expr)]
444 if self.horizontal:
445 state.append(('horizontal', self.horizontal))
446 if self.vertical:
447 state.append(('vertical', self.vertical))
448 return state
449
450 def __setstate__(self, state):
451 state = dict(state)
452 self.__init__(INumberDef(state["frames"]), state.get("horizontal"),
453 state.get("vertical"))
454
455 @classmethod
456 def FromXML(cls, doc, element):
457 """Construct using an ElementTree-style element."""
458 horizontal = None
459 vertical = None
460
461 for subelem in element.getchildren():
462 tag = realtag(subelem)
463 if tag == "term":
464 term = INumberDef(subelem.text)
465 elif tag == "horizontal":
466 horizontal = Speed.FromXML(doc, subelem)
467 elif tag == "vertical":
468 vertical = Speed.FromXML(doc, subelem)
469
470 try:
471 return cls(term, horizontal, vertical)
472 except AttributeError:
473 raise ParseError
474
475 def __call__(self, owner, action, params, rank, created):
476 frames = self.term(params, rank)
477 horizontal = self.horizontal and self.horizontal(params, rank)
478 vertical = self.vertical and self.vertical(params, rank)
479 action.accel_frames = frames
480 if horizontal:
481 mx, type = horizontal
482 if frames <= 0:
483 if type == "absolute":
484 owner.mx = mx
485 elif type == "relative":
486 owner.mx += mx
487 elif type == "sequence":
488 action.mx = mx
489 elif type == "absolute":
490 action.mx = (mx - owner.mx) / frames
491 elif type == "relative":
492 action.mx = mx / frames
493 if vertical:
494 my, type = vertical
495 if frames <= 0:
496 if type == "absolute":
497 owner.my = my
498 elif type == "relative":
499 owner.my += my
500 elif type == "sequence":
501 action.my = my
502 elif type == "absolute":
503 action.my = (my - owner.my) / frames
504 elif type == "relative":
505 action.my = my / frames
506
507 def __repr__(self):
508 return "%s(%r, horizontal=%r, vertical=%r)" % (
509 type(self).__name__, self.term, self.horizontal, self.vertical)
510
511 class BulletDef(object):
512 """Bullet definition."""
513
514 def __init__(self, actions=(), direction=None, speed=None, tags=(),
515 appearance=None):
516 self.direction = direction
517 self.speed = speed
518 self.actions = list(actions)
519 self.tags = set(tags)
520 self.appearance = appearance
521
522 def __getstate__(self):
523 state = []
524 if self.direction:
525 state.append(("direction", self.direction))
526 if self.speed:
527 state.append(("speed", self.speed))
528 if self.actions:
529 state.append(("actions", self.actions))
530 if self.tags:
531 state.append(("tags", list(self.tags)))
532 if self.appearance:
533 state.append(("appearance", self.appearance))
534 return state
535
536 def __setstate__(self, state):
537 state = dict(state)
538 self.__init__(**state)
539
540 @classmethod
541 def FromXML(cls, doc, element):
542 """Construct using an ElementTree-style element."""
543 actions = []
544 speed = None
545 direction = None
546 tags = set()
547 for subelem in element.getchildren():
548 tag = realtag(subelem)
549 if tag == "direction":
550 direction = Direction.FromXML(doc, subelem)
551 elif tag == "speed":
552 speed = Speed.FromXML(doc, subelem)
553 elif tag == "action":
554 actions.append(ActionDef.FromXML(doc, subelem))
555 elif tag == "actionRef":
556 actions.append(ActionRef.FromXML(doc, subelem))
557 elif tag == "tag":
558 tags.add(subelem.text)
559 dfn = cls(actions, direction, speed, tags)
560 doc._bullets[element.get("label")] = dfn
561 return dfn
562
563 def __call__(self, params, rank):
564 actions = [action(params, rank) for action in self.actions]
565 return (
566 self.direction and self.direction(params, rank),
567 self.speed and self.speed(params, rank),
568 self.tags,
569 self.appearance,
570 actions)
571
572 def __repr__(self):
573 return "%s(direction=%r, speed=%r, actions=%r)" % (
574 type(self).__name__, self.direction, self.speed, self.actions)
575
576 class BulletRef(object):
577 """Create a bullet by name with parameters."""
578
579 def __init__(self, bullet, params=None):
580 self.bullet = bullet
581 self.params = ParamList() if params is None else params
582
583 def __getstate__(self):
584 state = []
585 if self.params.params:
586 params = [param.expr for param in self.params.params]
587 state.append(("params", params))
588 state.append(('bullet', self.bullet))
589 return state
590
591 def __setstate__(self, state):
592 state = dict(state)
593 bullet = state["bullet"]
594 params = [NumberDef(param) for param in state.get("params", [])]
595 self.__init__(bullet, ParamList(params))
596
597 @classmethod
598 def FromXML(cls, doc, element):
599 """Construct using an ElementTree-style element."""
600 bullet = cls(element.get("label"), ParamList.FromXML(doc, element))
601 doc._bullet_refs.append(bullet)
602 return bullet
603
604 def __call__(self, params, rank):
605 return self.bullet(self.params(params, rank), rank)
606
607 def __repr__(self):
608 return "%s(params=%r, bullet=%r)" % (
609 type(self).__name__, self.params, self.bullet)
610
611 class ActionDef(object):
612 """Action definition.
613
614 To support parsing new actions, add tags to
615 ActionDef.CONSTRUCTORS. It maps tag names to classes with a
616 FromXML classmethod, which take the BulletML instance and
617 ElementTree element as arguments.
618 """
619
620 # This is self-referential, so it's filled in later.
621 CONSTRUCTORS = dict()
622
623 def __init__(self, actions):
624 self.actions = list(actions)
625
626 def __getstate__(self):
627 return dict(actions=self.actions)
628
629 def __setstate__(self, state):
630 state = dict(state)
631 self.__init__(state["actions"])
632
633 @classmethod
634 def FromXML(cls, doc, element):
635 """Construct using an ElementTree-style element."""
636 actions = []
637 for subelem in element.getchildren():
638 tag = realtag(subelem)
639 try:
640 ctr = cls.CONSTRUCTORS[tag]
641 except KeyError:
642 continue
643 else:
644 actions.append(ctr.FromXML(doc, subelem))
645 dfn = cls(actions)
646 doc._actions[element.get("label")] = dfn
647 return dfn
648
649 def __call__(self, params, rank):
650 return self.actions, params
651
652 def __repr__(self):
653 return "%s(%r)" % (type(self).__name__, self.actions)
654
655 class ActionRef(object):
656 """Run an action by name with parameters."""
657
658 def __init__(self, action, params=None):
659 self.action = action
660 self.params = params or ParamList()
661
662 def __getstate__(self):
663 state = []
664 if self.params.params:
665 params = [param.expr for param in self.params.params]
666 state.append(("params", params))
667 state.append(('action', self.action))
668 return state
669
670 def __setstate__(self, state):
671 state = dict(state)
672 action = state["action"]
673 params = [NumberDef(param) for param in state.get("params", [])]
674 self.__init__(action, ParamList(params))
675
676 @classmethod
677 def FromXML(cls, doc, element):
678 """Construct using an ElementTree-style element."""
679 action = cls(element.get("label"), ParamList.FromXML(doc, element))
680 doc._action_refs.append(action)
681 return action
682
683 def __call__(self, params, rank):
684 return self.action(self.params(params, rank), rank)
685
686 def __repr__(self):
687 return "%s(params=%r, action=%r)" % (
688 type(self).__name__, self.params, self.action)
689
690 class Offset(object):
691 """Provide an offset to a bullet's initial position."""
692
693 VALID_TYPES = ["relative", "absolute"]
694
695 def __init__(self, type, x, y):
696 if type not in self.VALID_TYPES:
697 raise ValueError("invalid type %r" % type)
698 self.type = intern(type)
699 self.x = x
700 self.y = y
701
702 def __getstate__(self):
703 state = [('type', self.type)]
704 if self.x:
705 state.append(('x', self.x.expr))
706 if self.y:
707 state.append(('y', self.y.expr))
708 return state
709
710 def __setstate__(self, state):
711 state = dict(state)
712 x = NumberDef(state["x"]) if "x" in state else None
713 y = NumberDef(state["y"]) if "y" in state else None
714 self.__init__(state["type"], x, y)
715
716 @classmethod
717 def FromXML(cls, doc, element):
718 """Construct using an ElementTree-style element."""
719 type = element.get("type", "relative")
720 x = None
721 y = None
722 for subelem in element:
723 tag = realtag(subelem)
724 if tag == "x":
725 x = NumberDef(subelem.text)
726 elif tag == "y":
727 y = NumberDef(subelem.text)
728 return cls(type, x, y)
729
730 def __call__(self, params, rank):
731 return (self.x(params, rank) if self.x else 0,
732 self.y(params, rank) if self.y else 0)
733
734 class FireDef(object):
735 """Fire definition (creates a bullet)."""
736
737 def __init__(self, bullet, direction=None, speed=None, offset=None,
738 tags=(), appearance=None):
739 self.bullet = bullet
740 self.direction = direction
741 self.speed = speed
742 self.offset = offset
743 self.tags = set(tags)
744 self.appearance = appearance
745
746 def __getstate__(self):
747 state = []
748 if self.direction:
749 state.append(("direction", self.direction))
750 if self.speed:
751 state.append(("speed", self.speed))
752 if self.offset:
753 state.append(("offset", self.offset))
754 if self.tags:
755 state.append(("tags", list(self.tags)))
756 if self.appearance:
757 state.append(("appearance", self.appearance))
758 try:
759 params = self.bullet.params
760 except AttributeError:
761 state.append(('bullet', self.bullet))
762 else:
763 if params.params:
764 state.append(('bullet', self.bullet))
765 else:
766 # Strip out empty BulletRefs.
767 state.append(('bullet', self.bullet.bullet))
768 return state
769
770 def __setstate__(self, state):
771 state = dict(state)
772 self.__init__(**state)
773
774 @classmethod
775 def FromXML(cls, doc, element):
776 """Construct using an ElementTree-style element."""
777 direction = None
778 speed = None
779 offset = None
780 tags = set()
781 appearance = None
782
783 for subelem in element.getchildren():
784 tag = realtag(subelem)
785 if tag == "direction":
786 direction = Direction.FromXML(doc, subelem, "aim")
787 elif tag == "speed":
788 speed = Speed.FromXML(doc, subelem)
789 elif tag == "bullet":
790 bullet = BulletDef.FromXML(doc, subelem)
791 elif tag == "bulletRef":
792 bullet = BulletRef.FromXML(doc, subelem)
793 elif tag == "offset":
794 offset = Offset.FromXML(doc, subelem)
795 elif tag == "tag":
796 tags.add(subelem.text)
797 elif tag == "appearance":
798 appearance = subelem.text
799 try:
800 fire = cls(bullet, direction, speed, offset, tags, appearance)
801 except UnboundLocalError as exc:
802 raise ParseError(str(exc))
803 else:
804 doc._fires[element.get("label")] = fire
805 return fire
806
807 def __call__(self, owner, action, params, rank, created):
808 direction, speed, tags, appearance, actions = self.bullet(params, rank)
809 if self.direction:
810 direction = self.direction(params, rank)
811 if self.speed:
812 speed = self.speed(params, rank)
813 tags = tags.union(self.tags)
814 if self.appearance:
815 appearance = self.appearance
816
817 if direction:
818 direction, type = direction
819 if type == "aim" or type is None:
820 direction += owner.aim
821 elif type == "sequence":
822 direction += action.previous_fire_direction
823 elif type == "relative":
824 direction += owner.direction
825 else:
826 direction = owner.aim
827 action.previous_fire_direction = direction
828
829 if speed:
830 speed, type = speed
831 if type == "sequence":
832 speed += action.previous_fire_speed
833 elif type == "relative":
834 # The reference Noiz implementation uses
835 # prvFireSpeed here, but the standard is
836 # pretty clear -- "In case of the type is
837 # "relative", ... the speed is relative to the
838 # speed of this bullet."
839 speed += owner.speed
840 else:
841 speed = 1
842 action.previous_fire_speed = speed
843
844 x, y = owner.x, owner.y
845 if self.offset:
846 off_x, off_y = self.offset(params, rank)
847 if self.offset.type == "relative":
848 s = sin(direction)
849 c = cos(direction)
850 x += c * off_x + s * off_y
851 y += s * off_x - c * off_y
852 else:
853 x += off_x
854 y += off_y
855
856 if appearance is None:
857 appearance = owner.appearance
858 bullet = owner.__class__(
859 x=x, y=y, direction=direction, speed=speed,
860 target=owner.target, actions=actions, rank=rank,
861 appearance=appearance, tags=tags, Action=action.__class__)
862 created.append(bullet)
863
864 def __repr__(self):
865 return "%s(direction=%r, speed=%r, bullet=%r)" % (
866 type(self).__name__, self.direction, self.speed, self.bullet)
867
868 class FireRef(object):
869 """Fire a bullet by name with parameters."""
870
871 def __init__(self, fire, params=None):
872 self.fire = fire
873 self.params = params or ParamList()
874
875 def __getstate__(self):
876 state = []
877 if self.params.params:
878 params = [param.expr for param in self.params.params]
879 state.append(("params", params))
880 state.append(('fire', self.fire))
881 return state
882
883 def __setstate__(self, state):
884 state = dict(state)
885 fire = state["fire"]
886 params = [NumberDef(param) for param in state.get("params", [])]
887 self.__init__(fire, ParamList(params))
888
889 @classmethod
890 def FromXML(cls, doc, element):
891 """Construct using an ElementTree-style element."""
892 fired = cls(element.get("label"), ParamList.FromXML(doc, element))
893 doc._fire_refs.append(fired)
894 return fired
895
896 def __call__(self, owner, action, params, rank, created):
897 params = self.params(params, rank)
898 return self.fire(owner, action, params, rank, created)
899
900 def __repr__(self):
901 return "%s(params=%r, fire=%r)" % (
902 type(self).__name__, self.params, self.fire)
903
904 class BulletML(object):
905 """BulletML document.
906
907 A BulletML document is a collection of top-level actions and the
908 base game type.
909
910 You can add tags to the BulletML.CONSTRUCTORS dictionary to extend
911 its parsing. It maps tag names to classes with a FromXML
912 classmethod, which take the BulletML instance and ElementTree
913 element as arguments.
914
915 """
916
917 CONSTRUCTORS = dict(
918 bullet=BulletDef,
919 action=ActionDef,
920 fire=FireDef,
921 )
922
923 def __init__(self, type="none", actions=None):
924 self.type = intern(type)
925 self.actions = [] if actions is None else actions
926
927 def __getstate__(self):
928 return [('type', self.type), ('actions', self.actions)]
929
930 def __setstate__(self, state):
931 state = dict(state)
932 self.__init__(state["type"], actions=state.get("actions"))
933
934 @classmethod
935 def FromXML(cls, source):
936 """Return a BulletML instance based on XML."""
937 if not hasattr(source, 'read'):
938 source = StringIO(source)
939
940 tree = ElementTree()
941 root = tree.parse(source)
942
943 doc = cls(type=root.get("type", "none"))
944
945 doc._bullets = {}
946 doc._actions = {}
947 doc._fires = {}
948 doc._bullet_refs = []
949 doc._action_refs = []
950 doc._fire_refs = []
951
952 for element in root.getchildren():
953 tag = realtag(element)
954 if tag in doc.CONSTRUCTORS:
955 doc.CONSTRUCTORS[tag].FromXML(doc, element)
956
957 try:
958 for ref in doc._bullet_refs:
959 ref.bullet = doc._bullets[ref.bullet]
960 for ref in doc._fire_refs:
961 ref.fire = doc._fires[ref.fire]
962 for ref in doc._action_refs:
963 ref.action = doc._actions[ref.action]
964 except KeyError as exc:
965 raise ParseError("unknown reference %s" % exc)
966
967 doc.actions = [act for name, act in doc._actions.items()
968 if name and name.startswith("top")]
969
970 del(doc._bullet_refs)
971 del(doc._action_refs)
972 del(doc._fire_refs)
973 del(doc._bullets)
974 del(doc._actions)
975 del(doc._fires)
976
977 return doc
978
979 @classmethod
980 def FromYAML(cls, source):
981 """Create a BulletML instance based on YAML."""
982
983 # Late import to avoid a circular dependency.
984 try:
985 import bulletml.bulletyaml
986 import yaml
987 except ImportError:
988 raise ParseError("PyYAML is not available")
989 else:
990 try:
991 return yaml.load(source)
992 except Exception as exc:
993 raise ParseError(str(exc))
994
995 @classmethod
996 def FromDocument(cls, source):
997 """Create a BulletML instance based on a seekable file or string.
998
999 This attempts to autodetect if the stream is XML or YAML.
1000 """
1001 if not hasattr(source, 'read'):
1002 source = StringIO(source)
1003 start = source.read(1)
1004 source.seek(0)
1005 if start == "<":
1006 return cls.FromXML(source)
1007 elif start == "!" or start == "#":
1008 return cls.FromYAML(source)
1009 else:
1010 raise ParseError("unknown initial character %r" % start)
1011
1012 def __repr__(self):
1013 return "%s(type=%r, actions=%r)" % (
1014 type(self).__name__, self.type, self.actions)
1015
1016 ActionDef.CONSTRUCTORS = dict(
1017 repeat=Repeat,
1018 fire=FireDef,
1019 fireRef=FireRef,
1020 changeSpeed=ChangeSpeed,
1021 changeDirection=ChangeDirection,
1022 accel=Accel,
1023 wait=Wait,
1024 vanish=Vanish,
1025 tag=Tag,
1026 appearance=Appearance,
1027 untag=Untag,
1028 action=ActionDef,
1029 actionRef=ActionRef)
1030 ActionDef.CONSTRUCTORS["if"] = If