Anonymous avatar Anonymous committed f09214d

Added deprecation warning support. Marked several packages and modules as deprecated. Fixed various issues and bugs after linting.

Comments (0)

Files changed (24)

 * Check trunk 1953 (blit blend operations).
 * Check trunk rev. 1937, 1947 (blit blend for self).
 * Mark methods, which are limited to certain bpp ranges.
-* math module changes in rev. 2777
 * freetype: rendering size should use the bbox height for correct ascent/descent
   values, not the real size
 * freetype: correct error messages (e.g. on trying to scale pcf fonts)

doc/src/resources.xml

   </class>
 
   <func name="open_tarfile">
-    <call>open_tarfile (archive, filename, dir=None, type=None) -> StringIO or BytesIO</call>
+    <call>open_tarfile (archive, filename, directory=None, ftype=None) -> StringIO or BytesIO</call>
     <desc>Opens and reads a certain file from a TAR archive.
 
       Opens and reads a certain file from a TAR archive. The result is returned
       as StringIO stream. *filename* can be a relative or absolute path within
-      the TAR archive. The optional *dir* argument can be used to supply a
+      the TAR archive. The optional *directory* argument can be used to supply a
       relative directory path, under which *filename* will be tried to retrieved.
 
-      *type* is used to supply additional compression information, in case the
+      *ftype* is used to supply additional compression information, in case the
       system cannot determine the compression type itself, and can be either
       'gz' for gzip compression or 'bz2' for bzip2 compression.
 
     </desc>
   </func>
   <func name="open_zipfile">
-    <call>open_zipfile (archive, filename, dir=None) -> StringIO or BytesIO</call>
+    <call>open_zipfile (archive, filename, directory=None) -> StringIO or BytesIO</call>
     <desc>Opens and reads a certain file from a ZIP archive.
 
       Opens and reads a certain file from a ZIP archive. The result is returned
       as StringIO stream. *filename* can be a relative or absolute path within
-      the ZIP archive. The optional *dir* argument can be used to supply a
+      the ZIP archive. The optional *directory* argument can be used to supply a
       relative directory path, under which *filename* will be tried to retrieved.
 
       If the *filename* could not be found or an error occured on reading it,

doc/src/sdlextnumericsurfarray.xml

       allows you to write compatible code for various platforms having
       either Numeric *or* numpy installed.
 
+    .. note::
+    
+      The module is subject to change in future version and thus is
+      marked as deprecated.
+
     Functions to convert pixel data between pygame Surfaces and Numeric
     arrays. This module will only be available when pygame is built with
     support for the external Numeric package.

doc/src/sdlextnumpysurfarray.xml

       allows you to write compatible code for various platforms having
       either Numeric *or* numpy installed.
 
+    .. note::
+    
+      The module is subject to change in future version and thus is
+      marked as deprecated.
+
     Functions to convert pixel data between pygame Surfaces and Numpy
     arrays. This module will only be available when pygame can use the
     external Numpy package.

doc/src/sdlextsurfarray.xml

 
 <module name="pygame2.sdlext.surfarray">
   <short>
-    module for accessing surface pixel data using numeric array interfaces
+    module for accessing surface pixel data using numeric array interfaces.
   </short>
   <desc>
+    .. note::
+    
+      The module is subject to change in future version and thus is
+      marked as deprecated.
+
     Functions to convert pixel data between pygame Surfaces and arrays. This
     module will only be functional when pygame can use the external Numpy or
     Numeric packages.

doc/src/sdlmixernumericsndarray.xml

 
 <module name="pygame2.sdlmixer.numericsndarray">
   <short>SDL_mixer chunk arrays using Numeric</short>
-  <desc></desc>
+  <desc>
+    .. note::
+    
+      The module is subject to change in future version and thus is
+      marked as deprecated.
+  </desc>
 
-  <func name="array">
+  <func name="make_array">
     <call></call>
     <desc></desc>
   </func>

doc/tutorial/pygame.rst

   :func:`pygame2.sdlmixer.was_init`
 
 pygame.mixer.stop
-  Use :meth:`pygame2.sdlmixer.Channel.stop`.
+  Use :meth:`pygame2.sdlmixer.Channel.halt` or
+  :func:`pygame2.sdlmixer.channel.halt`.
+
 pygame.mixer.pause
-  Use :meth:`pygame2.sdlmixer.Channel.stop`.
+  Use :meth:`pygame2.sdlmixer.Channel.pause` or
+  :func:`pygame2.sdlmixer.channel.pause`.
+
 pygame.mixer.unpause
-  Use :meth:`pygame2.sdlmixer.Channel.resume`.
+  Use :meth:`pygame2.sdlmixer.Channel.resume` or
+  :func:`pygame2.sdlmixer.channel.resume`.
+
 pygame.mixer.fadeout
-  Use :meth:`pygame2.sdlmixer.Channel.fade_out`.
+  Use :meth:`pygame2.sdlmixer.Channel.fade_out` or
+  :func:`pygame2.sdlmixer.channel.fade_out`.
 
 pygame.mixer.set_num_channels
    There is no similar function or attribute in Pygame2. Use
 
 pygame.mixer.Sound.stop
   There is no similar function or attribute in Pygame2. Use
-  :meth:`pygame2.sdlmixer.Channel.stop`.
+  :meth:`pygame2.sdlmixer.Channel.halt`.
 
 pygame.mixer.Sound.fadeout
    There is no similar function or attribute in Pygame2. Use
+##    pygame - Python Game Library
+##    Copyright (C) 2009 Marcus von Appen
+##
+##    This library is free software; you can redistribute it and/or
+##    modify it under the terms of the GNU Library General Public
+##    License as published by the Free Software Foundation; either
+##    version 2 of the License, or (at your option) any later version.
+##
+##    This library is distributed in the hope that it will be useful,
+##    but WITHOUT ANY WARRANTY; without even the implied warranty of
+##    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+##    Library General Public License for more details.
+##
+##    You should have received a copy of the GNU Library General Public
+##    License along with this library; if not, write to the Free
+##    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+##
+
+##
+## This file is placed under the Public Domain.
+##
+
+"""Simple deprecation helper and compatibility functions."""
+
+import warnings
+
+class deprecated (object):
+    """deprecated () -> decorator
+
+    A simple decorator to mark functions and methods as deprecated.
+    """
+    def __init__ (self):
+        pass
+
+    def __call__ (self, func):
+        def wrapper (*fargs, **kw):
+            warnings.warn ("%s is deprecated." % func.__name__,
+                           category=DeprecationWarning, stacklevel=2)
+            return func (*fargs, **kw)
+        wrapper.__name__ = func.__name__
+        wrapper.__doc__ = func.__doc__
+        wrapper.__dict__.update (func.__dict__)
+
+def deprecation (message):
+    """deprecation (message) -> None
+    
+    Prints a deprecation message.
+    """
+    warnings.warn (message, category=DeprecationWarning, stacklevel=2)
             pass
 
     for key in keys:
-        fontdict = {}
         for i in range (_winreg.QueryInfoKey (key)[1]):
-            name, font, t = None, None, None
+            name, font = None, None
             try:
-                name, font, t = _winreg.EnumValue (key, i)
+                name, font = _winreg.EnumValue (key, i)[0:2]
             except EnvironmentError:
                 break
 
         for k, apath in details.items ():
             if os.path.exists (apath):
                 bold, italic = k
-                ftype = _gettype (font)
-                _addfont(apath, name, dtype, "", bold, italic) 
+                ftype = _gettype (apath)
+                _addfont(apath, name, ftype, "", bold, italic) 
 
 def _initunix ():
     """_initunix () -> None
     """
     output = ""
     try:
-        p = subprocess.Popen \
+        proc = subprocess.Popen \
 		("fc-list : file family style fullname fullnamelang",
                  shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
-        output = p.communicate()[0]
-        retcode = p.returncode
+        output = proc.communicate()[0]
         if sys.version_info[0] >= 3:
             output = str (output, "utf-8")
     except OSError:
     try:
         for line in output.split ("\n"):
             if line.strip () == "":
-               continue 
+                continue 
             values = line.split (":")
             fullnames, fulllang, name = None, None, None
             filename, family, style = values[0:3]
             ftype = _gettype (filename)
             bold, italic = _getstyle (style)
             _addfont (filename, name, ftype, family, bold, italic)
-    except Exception:
+    except:
         _families.clear ()
         _fonts.clear ()
         _families[None] = None
             continue
 
         if fullname != name and name not in fname:
-            nl = name.lower ()
-            fl = fullname.lower ()
-            if nl not in fl and nl not in fname.lower():
+            namel = name.lower ()
+            fulll = fullname.lower ()
+            if namel not in fulll and namel not in fname.lower ():
                 continue
         if ftype and ftype != filetype:
             # The user requires a certain font filetype.
         iodata = io.StringIO (data)
     return iodata
 
-def open_zipfile (archive, filename, dir=None):
-    """open_zipfile (archive, filename, dir=None) -> StringIO or BytesIO
+def open_zipfile (archive, filename, directory=None):
+    """open_zipfile (archive, filename, directory=None) -> StringIO or BytesIO
     
     Opens and reads a certain file from a ZIP archive.
     
     Opens and reads a certain file from a ZIP archive. The result is returned
     as StringIO stream. *filename* can be a relative or absolute path within
-    the ZIP archive. The optional *dir* argument can be used to supply a
+    the ZIP archive. The optional *directory* argument can be used to supply a
     relative directory path, under which *filename* will be tried to retrieved.
     
     If the *filename* could not be found or an error occured on reading it,
     
     apath = filename
     if dir:
-        apath = "%s/%s" % (dir, filename)
+        apath = "%s/%s" % (directory, filename)
     
     try:
         dmpdata = archive.open (apath)
             archive.close ()
     return data
 
-def open_tarfile (archive, filename, dir=None, type=None):
-    """open_tarfile (archive, filename, dir=None, type=None) -> StringIO or BytesIO
+def open_tarfile (archive, filename, directory=None, ftype=None):
+    """open_tarfile (archive, filename, directory=None, ftype=None) -> StringIO or BytesIO
     
     Opens and reads a certain file from a TAR archive.
     
     Opens and reads a certain file from a TAR archive. The result is returned
     as StringIO stream. *filename* can be a relative or absolute path within
-    the TAR archive. The optional *dir* argument can be used to supply a
+    the TAR archive. The optional *directory* argument can be used to supply a
     relative directory path, under which *filename* will be tried to retrieved.
 
-    *type* is used to supply additional compression information, in case the
+    *ftype* is used to supply additional compression information, in case the
     system cannot determine the compression type itself, and can be either
     'gz' for gzip compression or 'bz2' for bzip2 compression.
     
     Note:
       
-      If *type* is supplied, the compreesion mode will be enforced for opening
+      If *ftype* is supplied, the compreesion mode will be enforced for opening
       and reading.
     
     If the *filename* could not be found or an error occured on reading it,
     opened = False
     
     mode = 'r'
-    if type:
-        if type not in ('gz', 'bz2'):
+    if ftype:
+        if ftype not in ('gz', 'bz2'):
             raise TypeError ("invalid TAR compression type")
-        mode = "r:%s" % type
+        mode = "r:%s" % ftype
     
     if not isinstance (archive, tarfile.TarFile):
         if not tarfile.is_tarfile (archive):
     
     apath = filename
     if dir:
-        apath = "%s/%s" % (dir, filename)
+        apath = "%s/%s" % (directory, filename)
     
     try:
         dmpdata = archive.extractfile (apath)
         if not zipfile.is_zipfile (filename):
             raise TypeError ("file '%s' is not a valid ZIP archive" % filename)
         archname = os.path.abspath (filename)
-        zip = zipfile.ZipFile (filename, 'r')
-        for path in zip.namelist ():
-            dirname, fname = os.path.split (path)
+        zipf = zipfile.ZipFile (filename, 'r')
+        for path in zipf.namelist ():
+            fname = os.path.split (path)[1]
             if fname:
                 self.files[fname] = (archname, 'zip', path)
-        zip.close ()
+        zipf.close ()
     
-    def _scantar (self, filename, type=None):
-        """_scantar (filename, type=None) -> None
+    def _scantar (self, filename, ftype=None):
+        """_scantar (filename, ftype=None) -> None
         
         Scans the passed TAR archive and indexes all the files contained by it.
         """
         if not tarfile.is_tarfile (filename):
             raise TypeError ("file '%s' is not a valid TAR archive" % filename)
         mode = 'r'
-        if type:
-            if type not in ('gz', 'bz2'):
+        if ftype:
+            if ftype not in ('gz', 'bz2'):
                 raise TypeError ("invalid TAR compression type")
-            mode = "r:%s" % type
+            mode = "r:%s" % ftype
         archname = os.path.abspath (filename)
         archtype = 'tar'
-        if type:
-            archtype = 'tar%s' % type
+        if ftype:
+            archtype = 'tar%s' % ftype
         tar = tarfile.open (filename, mode)
         for path in tar.getnames ():
-            dirname, fname = os.path.split (path)
+            fname = os.path.split (path)[1]
             self.files[fname] = (archname, archtype, path)
         tar.close ()
     
         a stream for availability.
         """
         abspath = os.path.abspath (filename)
-        dirname, fname = os.path.split (abspath)
+        fname = os.path.split (abspath)[1]
         if not fname:
             raise ValueError ("invalid file path")
         self.files[fname] = (None, None, abspath)
         
         Raises a KeyError, if *filename* could not be found.
         """
-        archive, type, pathname = self.files[filename]
+        archive, ftype, pathname = self.files[filename]
         if archive:
-            if type == 'zip':
+            if ftype == 'zip':
                 return open_zipfile (archive, pathname)
-            elif type == 'tar':
+            elif ftype == 'tar':
                 return open_tarfile (archive, pathname)
-            elif type == 'tarbz2':
+            elif ftype == 'tarbz2':
                 return open_tarfile (archive, pathname, 'bz2')
-            elif type == 'targz':
+            elif ftype == 'targz':
                 return open_tarfile (archive, pathname, 'gz')
             else:
                 raise ValueError ("unsupported archive type")
         
         Raises a KeyError, if *filename* could not be found.
         """
-        archive, type, pathname = self.files[filename]
+        archive, ftype, pathname = self.files[filename]
         if archive:
-            if type == 'zip':
+            if ftype == 'zip':
                 return open_zipfile (archive, pathname)
-            elif type == 'tar':
+            elif ftype == 'tar':
                 return open_tarfile (archive, pathname)
-            elif type == 'tarbz2':
+            elif ftype == 'tarbz2':
                 return open_tarfile (archive, pathname, 'bz2')
-            elif type == 'targz':
+            elif ftype == 'targz':
                 return open_tarfile (archive, pathname, 'gz')
             else:
                 raise ValueError ("unsupported archive type")
         
         Raises a KeyError, if *filename* could not be found.
         """
-        archive, type, pathname = self.files[filename]
+        archive, ftype, pathname = self.files[filename]
         if archive:
             return '%s@%s' % (pathname, archive)
         return pathname
         join = os.path.join
         add = self.add
         abspath = os.path.abspath (path)
-        for (p, dirnames, filenames) in os.walk (abspath):
-            if match and match(p) is not None:
+        for (pdir, dirnames, filenames) in os.walk (abspath):
+            if match and match(pdir) is not None:
                 continue
             for fname in filenames:
-                add (join (p, fname))
+                add (join (pdir, fname))

lib/sdl/cursors.py

 
 
 
-def compile(strings, black='X', white='.',xor='o'):
-   """compile(strings, black, white,xor) -> data, mask
+def compile(strings, black='X', white='.', xor='o'):
+    """compile(strings, black, white,xor) -> data, mask
+    
+    Compile cursor strings into cursor data
+    
+    This takes a set of strings with equal length and computes
+    the binary data for that cursor. The string widths must be
+    divisible by 8.
+    
+    The black and white arguments are single letter strings that
+    tells which characters will represent black pixels, and which
+    characters represent white pixels. All other characters are
+    considered clear.
+    
+    This returns a tuple containing the cursor data and cursor mask
+    data. Both these arguments are used when setting a cursor with
+    pygame2.sdl.mouse.set_cursor().
+    """
 
-   Compile cursor strings into cursor data
-   
-   This takes a set of strings with equal length and computes
-   the binary data for that cursor. The string widths must be
-   divisible by 8.
-   
-   The black and white arguments are single letter strings that
-   tells which characters will represent black pixels, and which
-   characters represent white pixels. All other characters are
-   considered clear.
-   
-   This returns a tuple containing the cursor data and cursor mask
-   data. Both these arguments are used when setting a cursor with
-   pygame2.sdl.mouse.set_cursor().
-   """
+    #first check for consistent lengths
+    size = len(strings[0]), len(strings)
+    if size[0] % 8 or size[1] % 8:
+        raise ValueError ("cursor string sizes must be divisible by 8")
+    for s in strings[1:]:
+        if len(s) != size[0]:
+            raise ValueError ("Cursor strings are inconsistent lengths")
 
-   #first check for consistent lengths
-   size = len(strings[0]), len(strings)
-   if size[0] % 8 or size[1] % 8:
-       raise ValueError ("cursor string sizes must be divisible by 8")
-   for s in strings[1:]:
-       if len(s) != size[0]:
-           raise ValueError ("Cursor strings are inconsistent lengths")
-
-   #create the data arrays.
-   #this could stand a little optimizing
-   maskdata = []
-   filldata = []
-   maskitem = fillitem = 0
-   step = 8
-   for s in strings:
-       for c in s:
-           maskitem = maskitem << 1
-           fillitem = fillitem << 1
-           step = step - 1
-           if c == black:
-               maskitem = maskitem | 1
-           elif c == white:
-               maskitem = maskitem | 1
-               fillitem = fillitem | 1
-           elif c == xor:
-               fillitem = fillitem | 1
-           if not step:
-               maskdata.append(maskitem)
-               filldata.append(fillitem)
-               maskitem = fillitem = 0
-               step = 8
-   return tuple(filldata), tuple(maskdata)
+    #create the data arrays.
+    #this could stand a little optimizing
+    maskdata = []
+    filldata = []
+    maskitem = fillitem = 0
+    step = 8
+    for s in strings:
+        for c in s:
+            maskitem = maskitem << 1
+            fillitem = fillitem << 1
+            step = step - 1
+            if c == black:
+                maskitem = maskitem | 1
+            elif c == white:
+                maskitem = maskitem | 1
+                fillitem = fillitem | 1
+            elif c == xor:
+                fillitem = fillitem | 1
+            if not step:
+                maskdata.append(maskitem)
+                filldata.append(fillitem)
+                maskitem = fillitem = 0
+                step = 8
+    return tuple(filldata), tuple(maskdata)
 
 def load_xbm(curs, mask):
     """load_xbm(cursorfile, maskfile) -> cursor_args
     should work with typical XBM files.
     """
     def bitswap(num):
+        """simple bit swapper"""
         val = 0
         for x in range(8):
-            b = num&(1<<x) != 0
-            val = val<<1 | b
+            b = num & (1 << x) != 0
+            val = val << 1 | b
         return val
-    if type(curs) is type(''): curs = open(curs)
-    if type(mask) is type(''): mask = open(mask)
+    if type(curs) is type(''):
+       curs = open(curs)
+    if type(mask) is type(''):
+       mask = open(mask)
     curs = curs.readlines()
     mask = mask.readlines()
     #avoid comments

lib/sdlext/font.py

 """
 
 import os
-from pygame2 import Rect, FRect, Color
+from pygame2 import Rect, FRect
 from pygame2.sdl.video import Surface
 
 DEFAULTMAP = [ "0123456789",
         self._calculate_offsets ()
     
     def _calculate_offsets (self):
-        """
+        """calculate_offsets () -> None
+        
+        Calculates the internal character offsets for each line.
         """
         self.offsets = {}
         offsets = self.offsets

lib/sdlext/numpysurfarray.py

 with 16bit data will be treated as unsigned integers.
 """
 
-import pygame2.sdl
+import pygame2.compat
+pygame2.compat.deprecation ("""The numpysurfarray package is deprecated and
+will be changed or removed in future versions""")
+
+import pygame2.sdl.video as video
+import pygame2.sdl.constants as sdlconst
 import numpy
 import re
 
     (see the Surface.lock - lock the Surface memory for pixel access
     method).
     """
-    format = surface.format
-    bpp = format.bytes_per_pixel
+    sformat = surface.format
+    bpp = sformat.bytes_per_pixel
     if bpp <= 0 or bpp > 4:
         raise ValueError ("unsupported bit depth for 2D array")
 
         
     # Remove extra pitch from each row.
     width = surface.width
-    pitchdiff = format.pitch - width * bpp
+    pitchdiff = sformat.pitch - width * bpp
     if pitchdiff > 0:
         pattern = re.compile ('(%s)%s' % ('.' * width * bpp, '.' * pitchdiff),
                               flags=re.DOTALL)
         # Pad each triplet of bytes with another zero
         pattern = re.compile ('...', flags=re.DOTALL)
         data = '\0'.join (pattern.findall (data))
-        if pygame2.sdl.BYTEORDER == pygame2.sdl.LIL_ENDIAN:
+        if sdlconst.BYTEORDER == sdlconst.LIL_ENDIAN:
             data += '\0'
         else:
             data = '\0' + data
     the array (see the Surface.lock - lock the Surface memory for pixel
     access method).
     """
-    format = surface.format
-    bpp = format.bytes_per_pixel
+    sformat = surface.format
+    bpp = sformat.bytes_per_pixel
     if bpp == 3 or bpp < 1 or bpp > 4:
         raise ValueError ("unsupported bit depth for 2D reference array")
 
     typecode = (numpy.uint8, numpy.uint16, None, numpy.uint32)[bpp - 1]
     array = numpy.frombuffer (surface.pixels, typecode)
-    array.shape = surface.height, format.pitch / bpp
+    array.shape = surface.height, sformat.pitch / bpp
 
     # Padding correction for certain depth due to padding bytes.
-    array = array[:,:surface.width]
+    array = array[:, :surface.width]
     array = numpy.transpose (array)
     return array
 
     (see the Surface.lock - lock the Surface memory for pixel access
     method).
     """
-    format = surface.format
-    bpp = format.bytes_per_pixel
+    sformat = surface.format
+    bpp = sformat.bytes_per_pixel
     array = array2d (surface)
 
     # Taken from from Alex Holkner's pygame-ctypes package. Thanks a
         array = numpy.transpose (array, (1, 2, 0))
         return array
     else:
-        masks = format.masks
-        shifts = format.shifts
-        losses = format.losses
+        masks = sformat.masks
+        shifts = sformat.shifts
+        losses = sformat.losses
         planes = [((array & masks[0]) >> shifts[0]) << losses[0],
                   ((array & masks[1]) >> shifts[1]) << losses[1],
                   ((array & masks[2]) >> shifts[2]) << losses[2]]
     the array (see the Surface.lock - lock the Surface memory for pixel
     access method).
     """
-    format = surface.format
-    bpp = format.bytes_per_pixel
+    sformat = surface.format
+    bpp = sformat.bytes_per_pixel
     if bpp < 3 or bpp > 4:
         raise ValueError ("unsupported bit depth for 3D reference array")
-    lilendian = pygame2.sdl.BYTEORDER == pygame2.sdl.LIL_ENDIAN
+    lilendian = sdlconst.BYTEORDER == sdlconst.LIL_ENDIAN
 
     start = 0
     step = 0
 
     # Check for RGB or BGR surface.
-    shifts = format.shifts
+    shifts = sformat.shifts
     if shifts[0] == 16 and shifts[1] == 8 and shifts[2] == 0:
         # RGB 
         if lilendian:
     array = numpy.ndarray \
             (shape=(surface.width, surface.height, 3),
              dtype=numpy.uint8, buffer=surface.pixels,
-             offset=start, strides=(bpp, format.pitch, step))
+             offset=start, strides=(bpp, sformat.pitch, step))
     return array
 
 def array_alpha (surface):
     (see the Surface.lock - lock the Surface memory for pixel access
     method).
     """
-    format = surface.format
-    if format.bytes_per_pixel == 1 or not surface.get_alpha ():
+    sformat = surface.format
+    if sformat.bytes_per_pixel == 1 or not surface.get_alpha ():
         # 1 bpp surfaces and surfaces without alpha are always fully
         # opaque.
         array = numpy.empty (surface.width * surface.height, numpy.uint8)
     array = array2d (surface)
     # Those shifts match the results from the old numeric system
     # exactly.
-    array = array >> format.shifts[3] << format.losses[3]
+    array = array >> sformat.shifts[3] << sformat.losses[3]
     array = array.astype (numpy.uint8)
     return array
 
     The Surface this array references will remain locked for the
     lifetime of the array.
     """
-    format = surface.format
-    if format.bytes_per_pixel != 4:
+    sformat = surface.format
+    if sformat.bytes_per_pixel != 4:
         raise ValueError ("unsupported bit depth for alpha reference array")
-    lilendian = pygame2.sdl.BYTEORDER == pygame2.sdl.LIL_ENDIAN
+    lilendian = sdlconst.BYTEORDER == sdlconst.LIL_ENDIAN
 
     # ARGB surface.
     start = 0
     
-    if format.shifts[3] == 24 and lilendian:
+    if sformat.shifts[3] == 24 and lilendian:
         # RGBA surface.
         start = 3
-    elif format.shifts[3] == 0 and not lilendian:
+    elif sformat.shifts[3] == 0 and not lilendian:
         start = 3
     else:
         raise ValueError ("unsupported colormasks for alpha reference array")
     array = numpy.ndarray \
             (shape=(surface.width, surface.height),
              dtype=numpy.uint8, buffer=surface.pixels,
-             offset=start, strides=(4, format.pitch))
+             offset=start, strides=(4, sformat.pitch))
     return array
 
 def array_colorkey (surface):
     else:
         raise ValueError ("must be a valid 2d or 3d array")
 
-    surface = pygame2.sdl.Surface ((shape[0], shape[1]), 0, bpp, (r, g, b, 0))
+    surface = video.Surface ((shape[0], shape[1]), 0, bpp, (r, g, b, 0))
     blit_array (surface, array)
     return surface
 
     This function will temporarily lock the Surface as the new values
     are copied.
     """
-    format = surface.format
-    bpp = format.bytes_per_pixel
+    sformat = surface.format
+    bpp = sformat.bytes_per_pixel
     if bpp <= 0 or bpp > 4:
         raise ValueError ("unsupported bit depth for surface")
     
     # lot.
     if len(shape) == 3 and shape[2] == 3:
         array = numpy.transpose (array, (1, 0, 2))
-        shifts = format.shifts
-        losses = format.losses
-        array = (array[:,:,::3] >> losses[0] << shifts[0]) | \
-                (array[:,:,1::3] >> losses[1] << shifts[1]) | \
-                (array[:,:,2::3] >> losses[2] << shifts[2])
+        shifts = sformat.shifts
+        losses = sformat.losses
+        array = (array[:, :, ::3] >> losses[0] << shifts[0]) | \
+                (array[:, :, 1::3] >> losses[1] << shifts[1]) | \
+                (array[:, :, 2::3] >> losses[2] << shifts[2])
     elif len (shape) == 2:
         array = numpy.transpose (array)
     else:
     if itemsize > bpp:
         # Trim bytes from each element, keep least significant byte(s)
         pattern = '%s(%s)' % ('.' * (itemsize - bpp), '.' * bpp)
-        if pygame2.sdl.BYTEORDER == pygame2.sdl.LIL_ENDIAN:
+        if sdlconst.BYTEORDER == sdlconst.LIL_ENDIAN:
             pattern = '(%s)%s' % ('.' * bpp, '.' * (itemsize - bpp))
         data = ''.join (re.compile (pattern, flags=re.DOTALL).findall (data))
     elif itemsize < bpp:
         pad = '\0' * (bpp - itemsize)
         pixels = re.compile ('.' * itemsize, flags=re.DOTALL).findall (data)
         data = pad.join (pixels)
-        if pygame2.sdl.BYTEORDER == pygame2.sdl.LIL_ENDIAN:
+        if sdlconst.BYTEORDER == sdlconst.LIL_ENDIAN:
             data = data + pad
         else:
             data = pad + data
 
     # Add zeros pad for pitch correction
-    pitchdiff = format.pitch - width * bpp
+    pitchdiff = sformat.pitch - width * bpp
     if pitchdiff > 0:
         pad = '\0' * pitchdiff
         rows = re.compile ('.' * width * bpp, flags=re.DOTALL).findall (data)
     """
     # Taken from from Alex Holkner's pygame-ctypes package. Thanks a
     # lot.
-    format = surface.format
-    bpp = format.bytes_per_pixel
+    sformat = surface.format
+    bpp = sformat.bytes_per_pixel
     if bpp <= 0 or bpp > 4:
         raise ValueError ("unsupported bit depth for surface array")
 
     if shape[-1] != 3:
         raise ValueError ("array must be a 3d array of 3-value color data")
 
-    shifts = format.shifts
-    losses = format.losses
-    array = (array[:,:,::3] >> losses[0] << shifts[0]) | \
-            (array[:,:,1::3] >> losses[1] << shifts[1]) | \
-            (array[:,:,2::3] >> losses[2] << shifts[2])
+    shifts = sformat.shifts
+    losses = sformat.losses
+    array = (array[:, :, ::3] >> losses[0] << shifts[0]) | \
+            (array[:, :, 1::3] >> losses[1] << shifts[1]) | \
+            (array[:, :, 2::3] >> losses[2] << shifts[2])
     return array

lib/sdlext/surfarray.py

 and wonder about the values.
 """
 
+import pygame2.compat
+pygame2.compat.deprecation ("""The surfarray package is deprecated and
+will be changed or removed in future versions""")
+
 # Global array type setting. See use_arraytype().
 __arraytype = None
 

lib/sdlmixer/numpysndarray.py

 only has one.
 """
 
+import pygame2.compat
+pygame2.compat.deprecation ("""The numpysndarray package is deprecated and
+will be changed or removed in future versions""")
+
 import pygame2
-from base import *
+import pygame2.sdlmixer as mixer
 import numpy
 
 
 def _array_samples(sound, raw):
     # Info is a (freq, format, stereo) tuple
-    info = mixer.get_init ()
+    info = mixer.query_spec ()[1:]
     if not info:
         raise pygame2.Error ("Mixer not initialized")
     fmtbytes = (abs (info[1]) & 0xff) >> 3
     array.shape = shape
     return array
 
-def array (sound):
-    """pygame2._numpysndarray.array(Sound): return array
+def make_array (sound):
+    """pygame2._numpysndarray.make_array(Sound): return array
 
     Copy Sound samples into an array.
 
     always be in the format returned from pygame2.mixer.get_init().
     """
     # Info is a (freq, format, stereo) tuple
-    info = pygame2.mixer.get_init ()
+    info = mixer.query_spec ()[1:]
     if not info:
         raise pygame2.Error ("Mixer not initialized")
     fmtbytes = (abs (info[1]) & 0xff) >> 3
                  -16 : numpy.int16  # AUDUI_S16
                  }[info[1]]
 
-    array = numpy.frombuffer (data, typecode)
-    array.shape = shape
-    return array
+    soundarray = numpy.frombuffer (data, typecode)
+    soundarray.shape = shape
+    return soundarray
 
-def make_sound (array):
-    """pygame2._numpysndarray.make_sound(array): return Sound
+def make_sound (soundarray):
+    """pygame2._numpysndarray.make_sound(soundarray): return Sound
 
     Convert an array into a Sound object.
     
     audio format.
     """
     # Info is a (freq, format, stereo) tuple
-    info = pygame2.mixer.get_init ()
+    info = mixer.query_spec ()[1:]
     if not info:
-        raise pygame2.error ("Mixer not initialized")
+        raise pygame2.Error ("Mixer not initialized")
     channels = info[2]
 
-    shape = array.shape
+    shape = soundarray.shape
     if channels == 1:
         if len (shape) != 1:
             raise ValueError ("Array must be 1-dimensional for mono mixer")
             raise ValueError ("Array must be 2-dimensional for stereo mixer")
         elif shape[1] != channels:
             raise ValueError ("Array depth must match number of mixer channels")
-    return mixer.Sound (array)
+    return mixer.Sound (soundarray)

lib/sdlmixer/sndarray.py

 mind, if you use the module's functions and wonder about the values.
 """
 
+import pygame2.compat
+pygame2.compat.deprecation ("""The sndarray package is deprecated and
+will be changed or removed in future versions""")
+
 # Global array type setting. See use_arraytype().
 __arraytype = None
 
 # Try to import the necessary modules.
 try:
-    import numericsndarray as numericsnd
+    import pygame2.sdlmixer.numericsndarray as numericsnd
     __hasnumeric = True
     __arraytype = "numeric"
 except ImportError:
     __hasnumeric = False
 
 try:
-    import numpysndarray as numpysnd
+    import pygame2.sdlmixer.numpysndarray as numpysnd
     __hasnumpy = True
     if not __hasnumeric:
         __arraytype = "numpy"
 #if not __hasnumpy and not __hasnumeric:
 #    raise ImportError ("no module named numpy or Numeric found")
 
-def array (sound):
-    """pygame2.sndarray.array(Sound): return array
+def make_array (sound):
+    """pygame2.sndarray.make_array(Sound): return array
 
     Copy Sound samples into an array.
 
     Creates a new array for the sound data and copies the samples. The
     array will always be in the format returned from
-    pygame2.mixer.get_init().
+    pygame2.sdlmixer.get_init().
     """
     if __arraytype == "numeric":
-        return numericsnd.array (sound)
+        return numericsnd.make_array (sound)
     elif __arraytype == "numpy":
-        return numpysnd.array (sound)
+        return numpysnd.make_array (sound)
     raise NotImplementedError ("sound arrays are not supported")
 
 def samples (sound):

lib/sdlttf/sysfont.py

+##    pygame - Python Game Library
+##    Copyright (C) 2000-2003  Pete Shinners
+##
+##    This library is free software; you can redistribute it and/or
+##    modify it under the terms of the GNU Library General Public
+##    License as published by the Free Software Foundation; either
+##    version 2 of the License, or (at your option) any later version.
+##
+##    This library is distributed in the hope that it will be useful,
+##    but WITHOUT ANY WARRANTY; without even the implied warranty of
+##    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+##    Library General Public License for more details.
+##
+##    You should have received a copy of the GNU Library General Public
+##    License along with this library; if not, write to the Free
+##    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+##
+
+"""Simple module for creating SDL_ttf Font objects from system fonts."""
+
 import pygame2.font
 from pygame2.sdlttf import constants
 from pygame2.sdlttf.base import Font

lib/sprite/__init__.py

 Sprites are not thread safe.  So lock them yourself if using threads.
 """
 
+import pygame2.compat
+pygame2.compat.deprecation \
+    ("The sprite package is deprecated and will change in future versions")
+
 ##todo
 ## a group that holds only the 'n' most recent elements.
 ## sort of like the GroupSingle class, but holding more

lib/sprite/collision.py

 
 # some different collision detection functions that could be used.
 
+"""Collision handling for sprite objects"""
+
+import pygame2.compat
+pygame2.compat.deprecation \
+    ("The sprite package is deprecated and will change in future versions")
+
 try:
     from pygame2.mask import from_surface
 except:
     """
     return left.rect.colliderect(right.rect)
 
-class collide_rect_ratio:
+class collide_rect_ratio (object):
     """A callable class that checks for collisions between
     two sprites, using a scaled version of the sprites
     rects.
         leftrect = left.rect
         width = leftrect.width
         height = leftrect.height
-        leftrect = leftrect.inflate( width * ratio - width, height * ratio - height )
+        leftrect = leftrect.inflate(width * ratio - width,
+                                    height * ratio - height)
         
         rightrect = right.rect
         width = rightrect.width
         height = rightrect.height
-        rightrect = rightrect.inflate( width * ratio - width, height * ratio - height )
+        rightrect = rightrect.inflate(width * ratio - width,
+                                      height * ratio - height)
         
         return leftrect.colliderect( rightrect )
 
         rightradiussquared = right.radius ** 2
     except AttributeError:
         rightrect = right.rect
-        rightradiussquared = ( rightrect.width ** 2 + rightrect.height ** 2 ) / 4
+        rightradiussquared = (rightrect.width ** 2 + rightrect.height ** 2) / 4
     return distancesquared < leftradiussquared + rightradiussquared
 
 class collide_circle_ratio( object ):
             else:
                 halfratio = self.halfratio
                 rightrect = right.rect
-                rightradiussquared = (rightrect.width ** 2 + rightrect.height ** 2) * halfratio
+                rightradiussquared = \
+                    (rightrect.width ** 2 + rightrect.height ** 2) * halfratio
         else:
             halfratio = self.halfratio
             leftrect = left.rect
-            leftradiussquared = (leftrect.width ** 2 + leftrect.height ** 2) * halfratio
+            leftradiussquared = \
+                (leftrect.width ** 2 + leftrect.height ** 2) * halfratio
             
             if hasattr( right, "radius" ):
                 rightradiussquared = (right.radius * ratio) ** 2
             else:
                 rightrect = right.rect
-                rightradiussquared = (rightrect.width ** 2 + rightrect.height ** 2) * halfratio
+                rightradiussquared = \
+                    (rightrect.width ** 2 + rightrect.height ** 2) * halfratio
         return distancesquared < leftradiussquared + rightradiussquared
 
 def collide_mask(left, right):
     The dokill argument is a bool. If set to True, all Sprites that collide
     will be removed from the Group.
 
-    The collided argument is a callback function used to calculate if two sprites 
-    are colliding. it should take two sprites as values, and return a bool 
-    value indicating if they are colliding. If collided is not passed, all sprites 
-    must have a "rect" value, which is a rectangle of the sprite area, which will 
-    be used to calculate the collision.
+    The collided argument is a callback function used to calculate if
+    two sprites are colliding. it should take two sprites as values, and
+    return a bool value indicating if they are colliding. If collided is
+    not passed, all sprites must have a "rect" value, which is a
+    rectangle of the sprite area, which will be used to calculate the
+    collision.
     """
     crashed = []
     if collided is None:
         # Special case old behaviour for speed.
-        spritecollide = sprite.rect.colliderect
+        collide = sprite.rect.colliderect
         if dokill:
             for s in group.sprites():
-                if spritecollide(s.rect):
+                if collide(s.rect):
                     s.kill()
                     crashed.append(s)
         else:
             for s in group:
-                if spritecollide(s.rect):
+                if collide(s.rect):
                     crashed.append(s)
     else:
         if dokill:
        to calculate the collision."""
     if collided is None:
         # Special case old behaviour for speed.
-        spritecollide = sprite.rect.colliderect
+        collide = sprite.rect.colliderect
         for s in group:
-            if spritecollide(s.rect):
+            if collide(s.rect):
                 return s
     else:
         for s in group:

lib/sprite/groups.py

 ##    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 ##
 
+"""Sprite groups"""
+
+import pygame2.compat
+pygame2.compat.deprecation \
+    ("The sprite package is deprecated and will change in future versions")
+
 from pygame2.sprite.sprites import Sprite
 
 class AbstractGroup(object):
         return self.spritedict.keys()
 
     def add_internal(self, sprite):
+        """Adds a dummy sprite entry."""
         self.spritedict[sprite] = 0
 
     def remove_internal(self, sprite):
+        """Removes a sprite"""
         r = self.spritedict[sprite]
         if r is not 0:
             self.lostsprites.append(r)
         del(self.spritedict[sprite])
 
     def has_internal(self, sprite):
+        """Checks, whether the passed sprite exists"""
         return self.spritedict.has_key(sprite)
 
     def copy(self):
                     sprite.remove_internal(self)
             else:
                 try:
-                    for spr in sprite: self.remove(spr)
+                    for spr in sprite:
+                        self.remove(spr)
                 except (TypeError, AttributeError):
                     if hasattr(sprite, '_spritegroup'):
                         for spr in sprite.sprites():
 
            calls the update method for all sprites in the group.
            Passes all arguments on to the Sprite update function."""
-        for s in self.sprites(): s.update(*args)
+        for s in self.sprites():
+            s.update(*args)
 
     def draw(self, surface):
         """draw(surface)
             for r in self.lostsprites:
                 bgd(surface, r)
             for r in self.spritedict.values():
-                if r is not 0: bgd(surface, r)
+                if r is not 0:
+                    bgd(surface, r)
         else:
             surface_blit = surface.blit
             for r in self.lostsprites:
                 surface_blit(bgd, r, r)
             for r in self.spritedict.values():
-                if r is not 0: surface_blit(bgd, r, r)
+                if r is not 0:
+                    surface_blit(bgd, r, r)
 
     def empty(self):
         """empty()
     def __init__(self, sprite = None):
         AbstractGroup.__init__(self)
         self.__sprite = None
-        if sprite is not None: self.add(sprite)
+        if sprite is not None:
+            self.add(sprite)
 
     def copy(self):
+        """Copies the Group."""
         return GroupSingle(self.__sprite)
 
     def sprites(self):
-        if self.__sprite is not None: return [self.__sprite]
-        else: return []
+        """Returns the sprites of the Group as list."""
+        if self.__sprite is not None:
+            return [self.__sprite]
+        else:
+            return []
 
     def add_internal(self, sprite):
+        """Adds a sprite."""
         if self.__sprite is not None:
             self.__sprite.remove_internal(self)
         self.__sprite = sprite
 
-    def __nonzero__(self): return (self.__sprite is not None)
+    def __nonzero__(self):
+        return (self.__sprite is not None)
 
     def _get_sprite(self):
+        """Gets the sprite container"""
         return self.__sprite
 
     def _set_sprite(self, sprite):
+        """Sets (adds) a sprite"""
         self.add_internal(sprite)
         sprite.add_internal(self)
         return sprite
                       "The sprite contained in this group")
     
     def remove_internal(self, sprite):
-        if sprite is self.__sprite: self.__sprite = None
+        """Removes a sprite"""
+        if sprite is self.__sprite:
+            self.__sprite = None
 
     def has_internal(self, sprite):
+        """Checks whether the sprite exists in the Group"""
         return (self.__sprite is sprite)
 
     # Optimizations...
-    def __contains__(self, sprite): return (self.__sprite is sprite)
+    def __contains__(self, sprite):
+        return (self.__sprite is sprite)

lib/sprite/layeredgroups.py

 ##    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 ##
 
+"""Specialized rendering- and layer-aware groups"""
+
+import pygame2.compat
+pygame2.compat.deprecation \
+    ("The sprite package is deprecated and will change in future versions")
+
 try:
     from pygame2.sdl.time import get_ticks
     __hassdl = True

lib/sprite/rendergroups.py

 ##    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 ##
 
+"""Specialized rendering-enabled sprite groups"""
+
+import pygame2.compat
+pygame2.compat.deprecation \
+    ("The sprite package is deprecated and will change in future versions")
+
 from pygame2.sprite.groups import Group
 
 RenderPlain = Group
     """
     
     def draw(self, surface):
-       spritedict = self.spritedict
-       surface_blit = surface.blit
-       dirty = self.lostsprites
-       self.lostsprites = []
-       dirty_append = dirty.append
-       for s in self.sprites():
-           r = spritedict[s]
-           newrect = surface_blit(s.image, s.rect)
-           if r is 0:
-               dirty_append(newrect)
-           else:
-               if newrect.colliderect(r):
-                   dirty_append(newrect.union(r))
-               else:
-                   dirty_append(newrect)
-                   dirty_append(r)
-           spritedict[s] = newrect
-       return dirty
+        spritedict = self.spritedict
+        surface_blit = surface.blit
+        dirty = self.lostsprites
+        self.lostsprites = []
+        dirty_append = dirty.append
+        for s in self.sprites():
+            r = spritedict[s]
+            newrect = surface_blit(s.image, s.rect)
+            if r is 0:
+                dirty_append(newrect)
+            else:
+                if newrect.colliderect(r):
+                    dirty_append(newrect.union(r))
+                else:
+                    dirty_append(newrect)
+                    dirty_append(r)
+            spritedict[s] = newrect
+        return dirty
 
 class OrderedUpdates(RenderUpdates):
     """RenderUpdates class that draws Sprites in order of addition

lib/sprite/sprites.py

 ##    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 ##
 
+"""Sprite objects"""
+
+import pygame2.compat
+pygame2.compat.deprecation \
+    ("The sprite package is deprecated and will change in future versions")
+
 class Sprite(object):
     """simple base class for visible game objects
     pygame2.sprite.Sprite(*groups): return Sprite
 
     def __init__(self, *groups):
         self.__g = {} # The groups the sprite is in
-        if groups: self.add(groups)
+        if groups:
+            self.add (groups)
 
     def add(self, *groups):
         """add the sprite to groups
             else: self.remove(*group)
 
     def add_internal(self, group):
+        """Adds a dummy group"""
         self.__g[group] = 0
 
     def remove_internal(self, group):
+        """Removes a group"""
         del self.__g[group]
 
     def update(self, *args):

src/sdlmixer/numericsndarraymod.c

 static PyMethodDef _sndarray_methods[] =
 {
     { "samples", _sndarray_samples, METH_VARARGS, "" },
-    { "array", _sndarray_array, METH_VARARGS, "" },
+    { "make_array", _sndarray_array, METH_VARARGS, "" },
     { "make_sound", _sndarray_make_sound, METH_VARARGS, "" },
     { NULL, NULL, 0, NULL},
 };
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.