2075ac961ae06715a4ffe899541667053fa8e563
[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.__class__(
372 owner, action, actions, params, rank, repeat)
373 owner.replace(action, child)
374 child.step(owner, created)
375 return True
376
377 def __repr__(self):
378 return "%s(%r, %r)" % (type(self).__name__, self.times, self.action)
379
380 class If(object):
381 """Conditional actions."""
382
383 def __init__(self, cond, then, else_=None):
384 self.cond = cond
385 self.then = then
386 self.else_ = else_
387
388 def __getstate__(self):
389 if self.else_:
390 return [('cond', self.cond.expr),
391 ('then', self.then),
392 ('else', self.else_)]
393 else:
394 return [('cond', self.cond.expr), ('then', self.then)]
395
396 def __setstate__(self, state):
397 state = dict(state)
398 state["else_"] = state.pop("else", None)
399 state["cond"] = INumberDef(state["cond"])
400 self.__init__(**state)
401
402 @classmethod
403 def FromXML(cls, doc, element):
404 """Construct using an ElementTree-style element."""
405 else_ = None
406 for subelem in element.getchildren():
407 tag = realtag(subelem)
408 if tag == "cond":
409 cond = INumberDef(subelem.text)
410 elif tag == "then":
411 then = ActionDef.FromXML(doc, subelem)
412 elif tag == "else":
413 else_ = ActionDef.FromXML(doc, subelem)
414 try:
415 return cls(cond, then, else_)
416 except UnboundLocalError as exc:
417 raise ParseError(str(exc))
418
419 def __call__(self, owner, action, params, rank, created):
420 if self.cond(params, rank):
421 branch = self.then
422 else:
423 branch = self.else_
424
425 if branch:
426 actions, params = branch(params, rank)
427 child = action.__class__(owner, action, actions, params, rank)
428 owner.replace(action, child)
429 child.step(owner, created)
430 return True
431
432 class Accel(object):
433 """Accelerate over some time."""
434
435 horizontal = None
436 vertical = None
437
438 def __init__(self, term, horizontal=None, vertical=None):
439 self.term = term
440 self.horizontal = horizontal
441 self.vertical = vertical
442
443 def __getstate__(self):
444 state = [('frames', self.term.expr)]
445 if self.horizontal:
446 state.append(('horizontal', self.horizontal))
447 if self.vertical:
448 state.append(('vertical', self.vertical))
449 return state
450
451 def __setstate__(self, state):
452 state = dict(state)
453 self.__init__(INumberDef(state["frames"]), state.get("horizontal"),
454 state.get("vertical"))
455
456 @classmethod
457 def FromXML(cls, doc, element):
458 """Construct using an ElementTree-style element."""
459 horizontal = None
460 vertical = None
461
462 for subelem in element.getchildren():
463 tag = realtag(subelem)
464 if tag == "term":
465 term = INumberDef(subelem.text)
466 elif tag == "horizontal":
467 horizontal = Speed.FromXML(doc, subelem)
468 elif tag == "vertical":
469 vertical = Speed.FromXML(doc, subelem)
470
471 try:
472 return cls(term, horizontal, vertical)
473 except AttributeError:
474 raise ParseError
475
476 def __call__(self, owner, action, params, rank, created):
477 frames = self.term(params, rank)
478 horizontal = self.horizontal and self.horizontal(params, rank)
479 vertical = self.vertical and self.vertical(params, rank)
480 action.accel_frames = frames
481 if horizontal:
482 mx, type = horizontal
483 if frames <= 0:
484 if type == "absolute":
485 owner.mx = mx
486 elif type == "relative":
487 owner.mx += mx
488 elif type == "sequence":
489 action.mx = mx
490 elif type == "absolute":
491 action.mx = (mx - owner.mx) / frames
492 elif type == "relative":
493 action.mx = mx / frames
494 if vertical:
495 my, type = vertical
496 if frames <= 0:
497 if type == "absolute":
498 owner.my = my
499 elif type == "relative":
500 owner.my += my
501 elif type == "sequence":
502 action.my = my
503 elif type == "absolute":
504 action.my = (my - owner.my) / frames
505 elif type == "relative":
506 action.my = my / frames
507
508 def __repr__(self):
509 return "%s(%r, horizontal=%r, vertical=%r)" % (
510 type(self).__name__, self.term, self.horizontal, self.vertical)
511
512 class BulletDef(object):
513 """Bullet definition."""
514
515 def __init__(self, actions=(), direction=None, speed=None, tags=(),
516 appearance=None):
517 self.direction = direction
518 self.speed = speed
519 self.actions = list(actions)
520 self.tags = set(tags)
521 self.appearance = appearance
522
523 def __getstate__(self):
524 state = []
525 if self.direction:
526 state.append(("direction", self.direction))
527 if self.speed:
528 state.append(("speed", self.speed))
529 if self.actions:
530 state.append(("actions", self.actions))
531 if self.tags:
532 state.append(("tags", list(self.tags)))
533 if self.appearance:
534 state.append(("appearance", self.appearance))
535 return state
536
537 def __setstate__(self, state):
538 state = dict(state)
539 self.__init__(**state)
540
541 @classmethod
542 def FromXML(cls, doc, element):
543 """Construct using an ElementTree-style element."""
544 actions = []
545 speed = None
546 direction = None
547 tags = set()
548 for subelem in element.getchildren():
549 tag = realtag(subelem)
550 if tag == "direction":
551 direction = Direction.FromXML(doc, subelem)
552 elif tag == "speed":
553 speed = Speed.FromXML(doc, subelem)
554 elif tag == "action":
555 actions.append(ActionDef.FromXML(doc, subelem))
556 elif tag == "actionRef":
557 actions.append(ActionRef.FromXML(doc, subelem))
558 elif tag == "tag":
559 tags.add(subelem.text)
560 dfn = cls(actions, direction, speed, tags)
561 doc._bullets[element.get("label")] = dfn
562 return dfn
563
564 def __call__(self, params, rank):
565 actions = [action(params, rank) for action in self.actions]
566 return (
567 self.direction and self.direction(params, rank),
568 self.speed and self.speed(params, rank),
569 self.tags,
570 self.appearance,
571 actions)
572
573 def __repr__(self):
574 return "%s(direction=%r, speed=%r, actions=%r)" % (
575 type(self).__name__, self.direction, self.speed, self.actions)
576
577 class BulletRef(object):
578 """Create a bullet by name with parameters."""
579
580 def __init__(self, bullet, params=None):
581 self.bullet = bullet
582 self.params = ParamList() if params is None else params
583
584 def __getstate__(self):
585 state = []
586 if self.params.params:
587 params = [param.expr for param in self.params.params]
588 state.append(("params", params))
589 state.append(('bullet', self.bullet))
590 return state
591
592 def __setstate__(self, state):
593 state = dict(state)
594 bullet = state["bullet"]
595 params = [NumberDef(param) for param in state.get("params", [])]
596 self.__init__(bullet, ParamList(params))
597
598 @classmethod
599 def FromXML(cls, doc, element):
600 """Construct using an ElementTree-style element."""
601 bullet = cls(element.get("label"), ParamList.FromXML(doc, element))
602 doc._bullet_refs.append(bullet)
603 return bullet
604
605 def __call__(self, params, rank):
606 return self.bullet(self.params(params, rank), rank)
607
608 def __repr__(self):
609 return "%s(params=%r, bullet=%r)" % (
610 type(self).__name__, self.params, self.bullet)
611
612 class ActionDef(object):
613 """Action definition.
614
615 To support parsing new actions, add tags to
616 ActionDef.CONSTRUCTORS. It maps tag names to classes with a
617 FromXML classmethod, which take the BulletML instance and
618 ElementTree element as arguments.
619 """
620
621 # This is self-referential, so it's filled in later.
622 CONSTRUCTORS = dict()
623
624 def __init__(self, actions):
625 self.actions = list(actions)
626
627 def __getstate__(self):
628 return dict(actions=self.actions)
629
630 def __setstate__(self, state):
631 state = dict(state)
632 self.__init__(state["actions"])
633
634 @classmethod
635 def FromXML(cls, doc, element):
636 """Construct using an ElementTree-style element."""
637 actions = []
638 for subelem in element.getchildren():
639 tag = realtag(subelem)
640 try:
641 ctr = cls.CONSTRUCTORS[tag]
642 except KeyError:
643 continue
644 else:
645 actions.append(ctr.FromXML(doc, subelem))
646 dfn = cls(actions)
647 doc._actions[element.get("label")] = dfn
648 return dfn
649
650 def __call__(self, params, rank):
651 return self.actions, params
652
653 def __repr__(self):
654 return "%s(%r)" % (type(self).__name__, self.actions)
655
656 class ActionRef(object):
657 """Run an action by name with parameters."""
658
659 def __init__(self, action, params=None):
660 self.action = action
661 self.params = params or ParamList()
662
663 def __getstate__(self):
664 state = []
665 if self.params.params:
666 params = [param.expr for param in self.params.params]
667 state.append(("params", params))
668 state.append(('action', self.action))
669 return state
670
671 def __setstate__(self, state):
672 state = dict(state)
673 action = state["action"]
674 params = [NumberDef(param) for param in state.get("params", [])]
675 self.__init__(action, ParamList(params))
676
677 @classmethod
678 def FromXML(cls, doc, element):
679 """Construct using an ElementTree-style element."""
680 action = cls(element.get("label"), ParamList.FromXML(doc, element))
681 doc._action_refs.append(action)
682 return action
683
684 def __call__(self, params, rank):
685 return self.action(self.params(params, rank), rank)
686
687 def __repr__(self):
688 return "%s(params=%r, action=%r)" % (
689 type(self).__name__, self.params, self.action)
690
691 class Offset(object):
692 """Provide an offset to a bullet's initial position."""
693
694 VALID_TYPES = ["relative", "absolute"]
695
696 def __init__(self, type, x, y):
697 if type not in self.VALID_TYPES:
698 raise ValueError("invalid type %r" % type)
699 self.type = intern(type)
700 self.x = x
701 self.y = y
702
703 def __getstate__(self):
704 state = [('type', self.type)]
705 if self.x:
706 state.append(('x', self.x.expr))
707 if self.y:
708 state.append(('y', self.y.expr))
709 return state
710
711 def __setstate__(self, state):
712 state = dict(state)
713 x = NumberDef(state["x"]) if "x" in state else None
714 y = NumberDef(state["y"]) if "y" in state else None
715 self.__init__(state["type"], x, y)
716
717 @classmethod
718 def FromXML(cls, doc, element):
719 """Construct using an ElementTree-style element."""
720 type = element.get("type", "relative")
721 x = None
722 y = None
723 for subelem in element:
724 tag = realtag(subelem)
725 if tag == "x":
726 x = NumberDef(subelem.text)
727 elif tag == "y":
728 y = NumberDef(subelem.text)
729 return cls(type, x, y)
730
731 def __call__(self, params, rank):
732 return (self.x(params, rank) if self.x else 0,
733 self.y(params, rank) if self.y else 0)
734
735 class FireDef(object):
736 """Fire definition (creates a bullet)."""
737
738 def __init__(self, bullet, direction=None, speed=None, offset=None,
739 tags=(), appearance=None):
740 self.bullet = bullet
741 self.direction = direction
742 self.speed = speed
743 self.offset = offset
744 self.tags = set(tags)
745 self.appearance = appearance
746
747 def __getstate__(self):
748 state = []
749 if self.direction:
750 state.append(("direction", self.direction))
751 if self.speed:
752 state.append(("speed", self.speed))
753 if self.offset:
754 state.append(("offset", self.offset))
755 if self.tags:
756 state.append(("tags", list(self.tags)))
757 if self.appearance:
758 state.append(("appearance", self.appearance))
759 try:
760 params = self.bullet.params
761 except AttributeError:
762 state.append(('bullet', self.bullet))
763 else:
764 if params.params:
765 state.append(('bullet', self.bullet))
766 else:
767 # Strip out empty BulletRefs.
768 state.append(('bullet', self.bullet.bullet))
769 return state
770
771 def __setstate__(self, state):
772 state = dict(state)
773 self.__init__(**state)
774
775 @classmethod
776 def FromXML(cls, doc, element):
777 """Construct using an ElementTree-style element."""
778 direction = None
779 speed = None
780 offset = None
781 tags = set()
782 appearance = None
783
784 for subelem in element.getchildren():
785 tag = realtag(subelem)
786 if tag == "direction":
787 direction = Direction.FromXML(doc, subelem, "aim")
788 elif tag == "speed":
789 speed = Speed.FromXML(doc, subelem)
790 elif tag == "bullet":
791 bullet = BulletDef.FromXML(doc, subelem)
792 elif tag == "bulletRef":
793 bullet = BulletRef.FromXML(doc, subelem)
794 elif tag == "offset":
795 offset = Offset.FromXML(doc, subelem)
796 elif tag == "tag":
797 tags.add(subelem.text)
798 elif tag == "appearance":
799 appearance = subelem.text
800 try:
801 fire = cls(bullet, direction, speed, offset, tags, appearance)
802 except UnboundLocalError as exc:
803 raise ParseError(str(exc))
804 else:
805 doc._fires[element.get("label")] = fire
806 return fire
807
808 def __call__(self, owner, action, params, rank, created):
809 direction, speed, tags, appearance, actions = self.bullet(params, rank)
810 if self.direction:
811 direction = self.direction(params, rank)
812 if self.speed:
813 speed = self.speed(params, rank)
814 tags = tags.union(self.tags)
815 if self.appearance:
816 appearance = self.appearance
817
818 if direction:
819 direction, type = direction
820 if type == "aim" or type is None:
821 direction += owner.aim
822 elif type == "sequence":
823 direction += action.previous_fire_direction
824 elif type == "relative":
825 direction += owner.direction
826 else:
827 direction = owner.aim
828 action.previous_fire_direction = direction
829
830 if speed:
831 speed, type = speed
832 if type == "sequence":
833 speed += action.previous_fire_speed
834 elif type == "relative":
835 # The reference Noiz implementation uses
836 # prvFireSpeed here, but the standard is
837 # pretty clear -- "In case of the type is
838 # "relative", ... the speed is relative to the
839 # speed of this bullet."
840 speed += owner.speed
841 else:
842 speed = 1
843 action.previous_fire_speed = speed
844
845 x, y = owner.x, owner.y
846 if self.offset:
847 off_x, off_y = self.offset(params, rank)
848 if self.offset.type == "relative":
849 s = sin(direction)
850 c = cos(direction)
851 x += c * off_x + s * off_y
852 y += s * off_x - c * off_y
853 else:
854 x += off_x
855 y += off_y
856
857 if appearance is None:
858 appearance = owner.appearance
859 bullet = owner.__class__(
860 x=x, y=y, direction=direction, speed=speed,
861 target=owner.target, actions=actions, rank=rank,
862 appearance=appearance, tags=tags, Action=action.__class__)
863 created.append(bullet)
864
865 def __repr__(self):
866 return "%s(direction=%r, speed=%r, bullet=%r)" % (
867 type(self).__name__, self.direction, self.speed, self.bullet)
868
869 class FireRef(object):
870 """Fire a bullet by name with parameters."""
871
872 def __init__(self, fire, params=None):
873 self.fire = fire
874 self.params = params or ParamList()
875
876 def __getstate__(self):
877 state = []
878 if self.params.params:
879 params = [param.expr for param in self.params.params]
880 state.append(("params", params))
881 state.append(('fire', self.fire))
882 return state
883
884 def __setstate__(self, state):
885 state = dict(state)
886 fire = state["fire"]
887 params = [NumberDef(param) for param in state.get("params", [])]
888 self.__init__(fire, ParamList(params))
889
890 @classmethod
891 def FromXML(cls, doc, element):
892 """Construct using an ElementTree-style element."""
893 fired = cls(element.get("label"), ParamList.FromXML(doc, element))
894 doc._fire_refs.append(fired)
895 return fired
896
897 def __call__(self, owner, action, params, rank, created):
898 params = self.params(params, rank)
899 return self.fire(owner, action, params, rank, created)
900
901 def __repr__(self):
902 return "%s(params=%r, fire=%r)" % (
903 type(self).__name__, self.params, self.fire)
904
905 class BulletML(object):
906 """BulletML document.
907
908 A BulletML document is a collection of top-level actions and the
909 base game type.
910
911 You can add tags to the BulletML.CONSTRUCTORS dictionary to extend
912 its parsing. It maps tag names to classes with a FromXML
913 classmethod, which take the BulletML instance and ElementTree
914 element as arguments.
915
916 """
917
918 CONSTRUCTORS = dict(
919 bullet=BulletDef,
920 action=ActionDef,
921 fire=FireDef,
922 )
923
924 def __init__(self, type="none", actions=None):
925 self.type = intern(type)
926 self.actions = [] if actions is None else actions
927
928 def __getstate__(self):
929 return [('type', self.type), ('actions', self.actions)]
930
931 def __setstate__(self, state):
932 state = dict(state)
933 self.__init__(state["type"], actions=state.get("actions"))
934
935 @classmethod
936 def FromXML(cls, source):
937 """Return a BulletML instance based on XML."""
938 if not hasattr(source, 'read'):
939 source = StringIO(source)
940
941 tree = ElementTree()
942 root = tree.parse(source)
943
944 doc = cls(type=root.get("type", "none"))
945
946 doc._bullets = {}
947 doc._actions = {}
948 doc._fires = {}
949 doc._bullet_refs = []
950 doc._action_refs = []
951 doc._fire_refs = []
952
953 for element in root.getchildren():
954 tag = realtag(element)
955 if tag in doc.CONSTRUCTORS:
956 doc.CONSTRUCTORS[tag].FromXML(doc, element)
957
958 try:
959 for ref in doc._bullet_refs:
960 ref.bullet = doc._bullets[ref.bullet]
961 for ref in doc._fire_refs:
962 ref.fire = doc._fires[ref.fire]
963 for ref in doc._action_refs:
964 ref.action = doc._actions[ref.action]
965 except KeyError as exc:
966 raise ParseError("unknown reference %s" % exc)
967
968 doc.actions = [act for name, act in doc._actions.items()
969 if name and name.startswith("top")]
970
971 del(doc._bullet_refs)
972 del(doc._action_refs)
973 del(doc._fire_refs)
974 del(doc._bullets)
975 del(doc._actions)
976 del(doc._fires)
977
978 return doc
979
980 @classmethod
981 def FromYAML(cls, source):
982 """Create a BulletML instance based on YAML."""
983
984 # Late import to avoid a circular dependency.
985 try:
986 import bulletml.bulletyaml
987 import yaml
988 except ImportError:
989 raise ParseError("PyYAML is not available")
990 else:
991 try:
992 return yaml.load(source)
993 except Exception as exc:
994 raise ParseError(str(exc))
995
996 @classmethod
997 def FromDocument(cls, source):
998 """Create a BulletML instance based on a seekable file or string.
999
1000 This attempts to autodetect if the stream is XML or YAML.
1001 """
1002 if not hasattr(source, 'read'):
1003 source = StringIO(source)
1004 start = source.read(1)
1005 source.seek(0)
1006 if start == "<":
1007 return cls.FromXML(source)
1008 elif start == "!" or start == "#":
1009 return cls.FromYAML(source)
1010 else:
1011 raise ParseError("unknown initial character %r" % start)
1012
1013 def __repr__(self):
1014 return "%s(type=%r, actions=%r)" % (
1015 type(self).__name__, self.type, self.actions)
1016
1017 ActionDef.CONSTRUCTORS = dict(
1018 repeat=Repeat,
1019 fire=FireDef,
1020 fireRef=FireRef,
1021 changeSpeed=ChangeSpeed,
1022 changeDirection=ChangeDirection,
1023 accel=Accel,
1024 wait=Wait,
1025 vanish=Vanish,
1026 tag=Tag,
1027 appearance=Appearance,
1028 untag=Untag,
1029 action=ActionDef,
1030 actionRef=ActionRef)
1031 ActionDef.CONSTRUCTORS["if"] = If