Commits

Nick Efford  committed deece2f

Added Label & Integer sprites and an example of use.

  • Participants
  • Parent commits a1c8769

Comments (0)

Files changed (4)

File easypg/sprites.py

-# Copyright (c) 2007-2011 Nick Efford <nick.efford (at) gmail.com>
+# Copyright (c) 2007-2012 Nick Efford <nick.efford (at) gmail.com>
 #
 # Permission is hereby granted, free of charge, to any person
 # obtaining a copy of this software and associated documentation
 
            [<state>]_[<direction>]_<num>
 
-
        <state> is optional.  If present, it consists of a short string of
        ASCII alphabetic characters.
 
            The implementation provided here is a stub that can be
            overridden in subclasses.
         """
+
+
+class Label(pygame.sprite.Sprite):
+    """A sprite for a text label - e.g., a score or timer.
+
+       A display surface, some initial text, a Font object, a colour
+       (RGB 3-tuple) and a position (2-tuple) must be provided when
+       creating a Label object.  An anchor point may optionally be
+       specified (this is the point on the label boundary corresponding
+       to the given position).
+
+       To update a Label object, simply assign a string to its 'text'
+       field; the assigned text will be rendered on the next update of
+       the sprite.
+    """
+
+    def __init__(self, screen, text, font, colour, position, anchor='c'):
+        """Creates a Label for the given Pygame display surface, using
+           the string, font, colour and position provided.
+
+           By default, the Label will be centered at the given position
+           (anchor='c'), but other anchor points are possible:
+
+               'tr' - top right
+               'mr' - middle right
+               'br' - bottom right
+               'mb' - middle bottom
+               'bl' - bottom left
+               'ml' - middle left
+               'tl' - top left
+               'mt' - middle top
+        """
+
+        super().__init__()
+
+        self.screen = screen
+        self._text = text
+        self.font = font
+        self.colour = colour
+        self.position = position
+        self.anchor = anchor.lower()
+
+        self._create_image()
+        self.refresh = False
+
+    @property
+    def text(self):
+        return self._text
+
+    @text.setter
+    def text(self, new_text):
+        self._text = new_text
+        self.refresh = True
+
+    def _create_image(self):
+        self.image = self.font.render(self.text, True, self.colour)
+        self.rect = self.image.get_rect()
+
+        if self.anchor == 'tr':
+            self.rect.topright = self.position
+        elif self.anchor == 'mr':
+            self.rect.midright = self.position
+        elif self.anchor == 'br':
+            self.rect.bottomright = self.position
+        elif self.anchor == 'mb':
+            self.rect.midbottom = self.position
+        elif self.anchor == 'bl':
+            self.rect.bottomleft = self.position
+        elif self.anchor == 'ml':
+            self.rect.midleft = self.position
+        elif self.anchor == 'tl':
+            self.rect.topleft = self.position
+        elif self.anchor == 'mt':
+            self.rect.midtop = self.position
+        else:
+            # default to centre
+            self.rect.center = self.position
+
+        self.refresh = False
+
+    def update(self):
+        """Updates this Label, rendering its image again if the text
+           has changed since it was last rendered.
+        """
+
+        if self.refresh:
+            self._create_image()
+
+
+class Integer(Label):
+    """A specialisation of Label, better suited to integer scores, etc.
+
+       This class adds a 'value' field, to which an integer can be assigned.
+       The field can also be incremented & decremented using += & -=.
+       The formatting used to convert the value into text can be specified
+       when creating the label, or by assigning a format to the 'fmt' field.
+    """
+
+    def __init__(
+      self, screen, value, font, colour, position, anchor='c', fmt='d'):
+        """Creates an Integer for the given Pygame display surface,
+           using the value, font, colour and position provided.
+
+           As with Label, an optional anchor point can be specified.
+           A format can also be specified if required, using standard
+           Python format specifier syntax.
+        """
+
+        self._value = value
+        self.fmt = fmt
+        text = format(value, fmt)
+
+        super().__init__(screen, text, font, colour, position, anchor)
+
+    @property
+    def value(self):
+        return self._value
+
+    @value.setter
+    def value(self, new_value):
+        self._value = new_value
+        self.text = format(new_value, self.fmt)

File examples/arrowkeys.py

 # running this program; the resulting displacement vector will be
 # displayed in the Pygame window.
 #
-# Copyright (c) 2011 Nick Efford <nick.efford (at) gmail.com>
+# Copyright (c) 2011-12 Nick Efford <nick.efford (at) gmail.com>
 #
 # Permission is hereby granted, free of charge, to any person obtaining
 # a copy of this software and associated documentation files (the
 import pygame
 
 from easypg.colours import WHITE
-from easypg.drawing import draw_text, fonts
+from easypg.drawing import draw_text
+from easypg.fonts import FONTS
 from easypg.utils import Window, read_arrow_keys
 
 
 
     def __init__(self):
         super().__init__((320, 240), 'Arrow Keys Example')
-        fonts.set_font(44, 'Mono')
+        FONTS.set_font(44, 'Mono')
 
     def update(self):
         dx, dy = read_arrow_keys()

File examples/labels.py

+# Example of using Label sprites in easypg.
+#
+# You can toggle the text label between two different strings by
+# pressing and releasing the space bar.  You can increment or
+# decrement the integer value by pressing the up or down arrow keys.
+#
+# Copyright (c) 2012 Nick Efford <nick.efford (at) gmail.com>
+#
+# Permission is hereby granted, free of charge, to any person obtaining
+# a copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+#
+# The above copyright notice and this permission notice shall be
+# included in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+import pygame
+
+from easypg.colours import BLACK, RED, YELLOW
+from easypg.sprites import Label, Integer
+from easypg.utils import Window, create_surface
+
+
+class ExampleWindow(Window):
+
+    def __init__(self, size):
+        super().__init__(size, title='Label & Integer Example')
+        font = pygame.font.SysFont('Sans', 40)
+        word_pos = (size[0]/2, size[1]/2)
+        self.word = Label(self.screen, 'Yes', font, RED, word_pos)
+        number_pos = (size[0] - 10, size[1] - 10)
+        self.number = Integer(self.screen, 0, font, YELLOW,
+          number_pos, anchor='br')
+        self.sprites = pygame.sprite.Group(self.word, self.number)
+
+    def handle_event(self, event):
+        if event.type == pygame.KEYUP and event.key == pygame.K_SPACE:
+            if self.word.text == 'Yes':
+                self.word.text = 'No'
+            else:
+                self.word.text = 'Yes'
+
+    def update(self):
+        keys = pygame.key.get_pressed()
+        if keys[pygame.K_UP]:
+            self.number.value += 1
+        if keys[pygame.K_DOWN]:
+            self.number.value -= 1
+
+        self.sprites.clear(self.screen, self.background)
+        self.sprites.update()
+        self.sprites.draw(self.screen)
+
+
+if __name__ == '__main__':
+    pygame.init()
+    size = (320, 240)
+    window = ExampleWindow(size)
+    background = create_surface(size, BLACK)
+    window.display(background)

File examples/picture.py

 # Example of drawing a simple picture using easypg.
 #
-# Copyright (c) 2011-2012 Nick Efford <nick.efford (at) gmail.com>
+# Copyright (c) 2011-12 Nick Efford <nick.efford (at) gmail.com>
 #
 # Permission is hereby granted, free of charge, to any person obtaining
 # a copy of this software and associated documentation files (the
 draw_rect(background, RED, (80, 75, 120, 165))
 draw_ellipse(background, GREEN, (120, 45, 190, 130))
 
-points = [ (290, 380), (400, 190), (510, 380) ]
+points = ((290, 380), (400, 190), (510, 380))
 draw_polygon(background, AQUA, points)
 draw_lines(background, NAVY, points, closed=True, antialias=True)