From d679e625ef188d192301fae25d7d8f330abc0a11 Mon Sep 17 00:00:00 2001 From: Anthony Briggs Date: Thu, 13 Sep 2018 13:59:40 +1000 Subject: [PATCH] Added support for flipping Actor images horizontally and vertically. --- doc/builtins.rst | 23 +++++++++++++++++++++++ pgzero/actor.py | 22 +++++++++++++++++++--- 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/doc/builtins.rst b/doc/builtins.rst index 20202352..7aa19290 100644 --- a/doc/builtins.rst +++ b/doc/builtins.rst @@ -526,6 +526,29 @@ be floats or the strings ``left``, ``center``/``middle``, ``right``, ``top`` or ``bottom`` as appropriate. +.. _flipping: + +Flipping +'''''''' + +Actors can be flipped, so that their image is mirrored horizontally or +vertically (or both). You can use this to save creating and loading a +separate set of images if you want an Actor to move in both directions. + +To flip an Actor horizontally, just set its ``flip`` property to ``True``. +Since our alien faces right, the following will make it face left:: + + alien = Actor('alien') + alien.flip = True + +If you want the alien to flip vertically too (maybe it can walk on the +ceiling?), pass it a tuple ``(horizontal, vertical)`` with the vertical value +set to True:: + + alien.flip = (True, True) + alien.flip = (False, True) + + .. _rotation: Rotation diff --git a/pgzero/actor.py b/pgzero/actor.py index 6bd79542..7d530412 100644 --- a/pgzero/actor.py +++ b/pgzero/actor.py @@ -77,7 +77,8 @@ class Actor: _anchor = _anchor_value = (0, 0) _angle = 0.0 - + _flip = (False, False) + def __init__(self, image, pos=POS_TOPLEFT, anchor=ANCHOR_CENTER, **kwargs): self._handle_unexpected_kwargs(kwargs) @@ -127,7 +128,9 @@ def _init_position(self, pos, anchor, **kwargs): if anchor is None: anchor = ("center", "center") self.anchor = anchor - + + self.flip = (False, False) + symbolic_pos_args = { k: kwargs[k] for k in kwargs if k in SYMBOLIC_POSITIONS} @@ -184,7 +187,15 @@ def angle(self, angle): ax, ay = self._untransformed_anchor self._anchor = transform_anchor(ax, ay, w, h, angle) self.pos = p + + @property + def flip(self): + return self._flip + @flip.setter + def flip(self, horizontal, vertical=False): + self._flip = (bool(horizontal), bool(vertical)) + @property def pos(self): px, py = self.topleft @@ -232,7 +243,12 @@ def _update_pos(self): self.pos = p def draw(self): - game.screen.blit(self._surf, self.topleft) + if self._flip == (False, False): + game.screen.blit(self._surf, self.topleft) + else: + flipped = pygame.transform.flip(self._surf, *self.flip) + game.screen.blit(flipped, self.topleft) + def angle_to(self, target): """Return the angle from this actors position to target, in degrees."""