Lenard Lindstrom avatar Lenard Lindstrom committed c0d170c

all standard modules build with Python 3.1. Optional movie module adapted. setup.py skips unsupported files for Python 3

Comments (0)

Files changed (18)

examples/blend_fill.py

 from pygame.locals import *
 
 def usage ():
-    print "Press R, G, B to increase the color channel values,"
-    print "1-9 to set the step range for the increment,"
-    print "A - ADD, S- SUB, M- MULT, - MIN, + MAX"
-    print "  to change the blend modes"
+    print ("Press R, G, B to increase the color channel values,")
+    print ("1-9 to set the step range for the increment,")
+    print ("A - ADD, S- SUB, M- MULT, - MIN, + MAX")
+    print ("  to change the blend modes")
 
 
 main_dir = os.path.split(os.path.abspath(__file__))[0]
                 #blendimage.fill (color, (0, 0, 20, 20), blendtype)
                 blendimage.fill (color, None, blendtype)
                 screen.blit (blendimage, (200, 10))
-                print "Color: %s, Pixel (0,0): %s" % (tuple(color),
-                                                      [blendimage.get_at ((0, 0))])
+                print ("Color: %s, Pixel (0,0): %s" %
+                       (tuple(color),
+                        [blendimage.get_at ((0, 0))]))
                 changed = False
                 pygame.display.flip ()
 

examples/blit_blends.py

     import pygame.surfarray
     import Numeric
 except:
-    print "no surfarray for you!  install Numeric"
+    print ("no surfarray for you!  install Numeric")
 
 import time
         
     screen.blit(im1, (0, 0))
     pygame.display.flip()
     clock = pygame.time.Clock()
-    print "one pixel is:%s:" % [im1.get_at((0,0))]
+    print ("one pixel is:%s:" % [im1.get_at((0,0))])
 
     going = True
     while going:
                 # blits is a dict keyed with key -> blit flag.  eg BLEND_ADD.
                 im1.blit(img_to_blit, (0,0), None, blits[event.key])
                 t2 = time.time()
-                print "one pixel is:%s:" % [im1.get_at((0,0))]
-                print "time to do:%s:" % (t2-t1)
+                print ("one pixel is:%s:" % [im1.get_at((0,0))])
+                print ("time to do:%s:" % (t2-t1))
 
 
             elif event.type == KEYDOWN and event.key in [K_t]:
 
                     # show which key we're doing...
                     onedoing = blitsn[bkey]
-                    print "time to do :%s: is :%s:" % (onedoing, t2-t1)
+                    print ("time to do :%s: is :%s:" % (onedoing, t2-t1))
 
 
             elif event.type == KEYDOWN and event.key in [K_o]:
                 # blits is a dict keyed with key -> blit flag.  eg BLEND_ADD.
                 im1.blit(iaa, (0,0))
                 t2 = time.time()
-                print "one pixel is:%s:" % [im1.get_at((0,0))]
-                print "time to do:%s:" % (t2-t1)
+                print ("one pixel is:%s:" % [im1.get_at((0,0))])
+                print ("time to do:%s:" % (t2-t1))
 
 
             elif event.type == KEYDOWN and event.key == K_SPACE:
                 del im1p
                 del im2p
                 t2 = time.time()
-                print "one pixel is:%s:" % [im1.get_at((0,0))]
-                print "time to do:%s:" % (t2-t1)
+                print ("one pixel is:%s:" % [im1.get_at((0,0))])
+                print ("time to do:%s:" % (t2-t1))
 
             elif event.type == KEYDOWN and event.key in [K_z]:
                 t1 = time.time()
                 del im1p
                 del im2p
                 t2 = time.time()
-                print "one pixel is:%s:" % [im1.get_at((0,0))]
-                print "time to do:%s:" % (t2-t1)
+                print ("one pixel is:%s:" % [im1.get_at((0,0))])
+                print ("time to do:%s:" % (t2-t1))
 
             elif event.type == KEYDOWN and event.key in [K_r, K_g, K_b]:
                 # this adds one to each pixel.
                 im1p = pygame.surfarray.pixels2d(im1)
                 im1p += colmap[event.key]
                 del im1p
-                print "one pixel is:%s:" % [im1.get_at((0,0))]
+                print ("one pixel is:%s:" % [im1.get_at((0,0))])
 
             elif event.type == KEYDOWN and event.key == K_p:
-                print "one pixel is:%s:" % [im1.get_at((0,0))]
+                print ("one pixel is:%s:" % [im1.get_at((0,0))])
 
 
 
                 im1.set_alpha(255)
 
                 t2 = time.time()
-                print "one pixel is:%s:" % [im1.get_at((0,0))]
-                print "time to do:%s:" % (t2-t1)
+                print ("one pixel is:%s:" % [im1.get_at((0,0))])
+                print ("time to do:%s:" % (t2-t1))
 
 
         screen.blit(im1, (0, 0))
     pygame.quit()
 
 def usage():
-    print "press keys 1-5 to change image to blit."
-    print "A - ADD, S- SUB, M- MULT, - MIN, + MAX"
-    print "T - timing test for special blend modes."
+    print ("press keys 1-5 to change image to blit.")
+    print ("A - ADD, S- SUB, M- MULT, - MIN, + MAX")
+    print ("T - timing test for special blend modes.")
 
 if __name__ == '__main__': 
     usage()

examples/headless_no_windows_needed.py

         w, h = map(int, [w,h])
         main(fin, fout, w,h)
     else:
-        print useage
+        print (useage)
 
 
 

examples/movieplayer.py

+import pygame
+from pygame.locals import *
+
+import sys
+try:
+    from cStringIO import StringIO as BytesIO
+except ImportError:
+    from io import BytesIO
+from pygame.compat import unicode_
+
+QUIT_CHAR = unicode_('q')
+
+usage = """\
+python movieplayer.py <movie file>
+
+A simple movie player that plays an MPEG movie in a Pygame window. It showcases
+the pygame.movie module. The window adjusts to the size of the movie image. It
+is given a boarder to demonstrate that a movie can play autonomously in a sub-
+window. Also, the file is copied to a file like object to show that not just
+Python files can be used as a movie source.
+"""
+
+def main(filepath):
+    pygame.init()
+    pygame.mixer.quit()
+
+    f = BytesIO(open(filepath, 'rb').read())
+    movie = pygame.movie.Movie(f)
+    w, h = movie.get_size()
+    w = int(w * 1.3 + 0.5)
+    h = int(h * 1.3 + 0.5)
+    wsize = (w+10, h+10)
+    msize = (w, h)
+    screen = pygame.display.set_mode(wsize)
+    movie.set_display(screen, Rect((5, 5), msize))
+
+    pygame.event.set_allowed((QUIT, KEYDOWN))
+    pygame.time.set_timer(USEREVENT, 1000)
+    movie.play()
+    while movie.get_busy():
+        evt = pygame.event.wait()
+        if evt.type == QUIT:
+            break
+        if evt.type == KEYDOWN and evt.unicode == QUIT_CHAR:
+            break
+    if movie.get_busy():
+        movie.stop()
+    pygame.time.set_timer(USEREVENT, 0)
+
+if __name__ == '__main__':
+    if len(sys.argv) != 2:
+        print (usage)
+    else:
+        main(sys.argv[1])

examples/oldalien.py

 from pygame.locals import *
 
 if not pygame.image.get_extended():
-    raise SystemExit, "Requires the extended image loading from SDL_image"
+    raise SystemExit("Requires the extended image loading from SDL_image")
 
 
 #constants
     try:
         surface = pygame.image.load(file)
     except pygame.error:
-        raise SystemExit, 'Could not load image "%s" %s'%(file, pygame.get_error())
+        raise SystemExit('Could not load image "%s" %s' %
+                         (file, pygame.get_error()))
     if transparent:
         corner = surface.get_at((0, 0))
         surface.set_colorkey(corner, RLEACCEL)

examples/pixelarray.py

 #!/usr/bin/env python
 import os, pygame
+from pygame.compat import xrange_
 
 main_dir = os.path.split(os.path.abspath(__file__))[0]
 data_dir = os.path.join(main_dir, 'data')
     ar = pygame.PixelArray (surface)
     r, g, b = 0, 0, 0
     # Do some easy gradient effect.
-    for y in xrange (255):
+    for y in xrange_ (255):
         r, g, b = y, y, y
         ar[:,y] = (r, g, b)
     del ar

examples/sound.py

 
 
     #start playing
-    print 'Playing Sound...'
+    print ('Playing Sound...')
     channel = sound.play()
 
 
     #poll until finished
     while channel.get_busy(): #still playing
-        print '  ...still going...'
+        print ('  ...still going...')
         time.wait(1000)
-    print '...Finished'
+    print ('...Finished')
 
 if __name__ == '__main__':
     if len(sys.argv) > 1:

python3/README

-These are special versions of the Setup.in and lib/__init__.py files for 
-building Pygame with Python 3.x. For now only a limited version of 
-Pygame is provided. Just replace the existing Setup.in and 
-lib/__init__.py files with these, then run "python config.py" and 
-"python setup.py ..." as usual.
-
-Though all Python modules (.py files) will install and compile without 
-error, some may still not work correctly. But the following modules do: 
-display, image, mixer, mixer.music, transform, gfxdraw, font, event, 
-key, sprites, mask, cursor, fastevent, joystick and cdrom. The Surface, 
-Rect and Color types are also available. The following example programs 
-have also been ported: aliens.py, chimp.py, stars.py, fonty.py, 
-scaletest.py, scroll.py, mask.py, fastevents.py, cursors.py, moveit.py 
-and spritetest.py.
-
-May 5, 2009
-

python3/Setup.in

-#This Setup file is used by the setup.py script to configure the
-#python extensions. You will likely use the "config.py" which will
-#build a correct Setup file for you based on your system settings.
-#If not, the format is simple enough to edit by hand. First change
-#the needed commandline flags for each dependency, then comment out
-#any unavailable optional modules in the first optional section.
-
-
-#Optional macros: these may be overridden.
-PORTTIME =
-
-#--StartConfig
-SDL = -I/usr/include/SDL -D_REENTRANT -lSDL
-FONT = -lSDL_ttf
-IMAGE = -lSDL_image
-MIXER = -lSDL_mixer
-SMPEG = -lsmpeg
-PNG = -lpng
-JPEG = -ljpeg
-SCRAP = -lX11
-PORTMIDI = -lportmidi
-PORTTIME = -lporttime
-#--EndConfig
-
-#DEBUG = -C-W -C-Wall
-DEBUG = 
-
-#the following modules are optional. you will want to compile
-#everything you can, but you can ignore ones you don't have
-#dependencies for, just comment them out
-
-imageext src/imageext.c $(SDL) $(IMAGE) $(PNG) $(JPEG) $(DEBUG)
-font src/font.c $(SDL) $(FONT) $(DEBUG)
-mixer src/mixer.c $(SDL) $(MIXER) $(DEBUG)
-mixer_music src/music.c $(SDL) $(MIXER) $(DEBUG)
-#_numericsurfarray src/_numericsurfarray.c $(SDL) $(DEBUG)
-#_numericsndarray src/_numericsndarray.c $(SDL) $(MIXER) $(DEBUG)
-#movie src/movie.c $(SDL) $(SMPEG) $(DEBUG)
-#scrap src/scrap.c $(SDL) $(SCRAP) $(DEBUG)
-#_camera src/_camera.c src/camera_v4l2.c src/camera_v4l.c $(SDL) $(DEBUG)
-#pypm src/pypm.c $(SDL) $(PORTMIDI) $(PORTTIME) $(DEBUG)
-
-GFX = src/SDL_gfx/SDL_gfxPrimitives.c 
-#GFX = src/SDL_gfx/SDL_gfxBlitFunc.c src/SDL_gfx/SDL_gfxPrimitives.c 
-gfxdraw src/gfxdraw.c $(SDL) $(GFX) $(DEBUG)
-
-
-
-#experimental new movie movie. requires libavcodec and libavformat.
-#add any necessary compile flags to this line and uncomment.
-#movieext src/movie.c  src/ffmovie.c $(SDL) -lavcodec -lavformat
-
-#these modules are required for pygame to run. they only require
-#SDL as a dependency. these should not be altered
-
-base src/base.c $(SDL) $(DEBUG)
-cdrom src/cdrom.c $(SDL) $(DEBUG)
-color src/color.c $(SDL) $(DEBUG)
-constants src/constants.c $(SDL) $(DEBUG)
-display src/display.c $(SDL) $(DEBUG)
-event src/event.c $(SDL) $(DEBUG)
-fastevent src/fastevent.c src/fastevents.c $(SDL) $(DEBUG)
-key src/key.c $(SDL) $(DEBUG)
-mouse src/mouse.c $(SDL) $(DEBUG)
-rect src/rect.c $(SDL) $(DEBUG)
-rwobject src/rwobject.c $(SDL) $(DEBUG)
-surface src/surface.c src/alphablit.c src/surface_fill.c $(SDL) $(DEBUG)
-surflock src/surflock.c $(SDL) $(DEBUG)
-time src/time.c $(SDL) $(DEBUG)
-joystick src/joystick.c $(SDL) $(DEBUG)
-draw src/draw.c $(SDL) $(DEBUG)
-image src/image.c $(SDL) $(DEBUG)
-overlay src/overlay.c $(SDL) $(DEBUG)
-transform src/transform.c src/rotozoom.c src/scale2x.c src/scale_mmx.c $(SDL) $(DEBUG)
-mask src/mask.c src/bitmask.c $(SDL) $(DEBUG)
-#bufferproxy src/bufferproxy.c $(SDL) $(DEBUG)
-#pixelarray src/pixelarray.c $(SDL) $(DEBUG)
-#_arraysurfarray src/_arraysurfarray.c $(SDL) $(DEBUG)
-

python3/__init__.py

-##    pygame - Python Game Library
-##    Copyright (C) 2000-2001  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
-##
-##    Pete Shinners
-##    pete@shinners.org
-"""Pygame is a set of Python modules designed for writing games.
-It is written on top of the excellent SDL library. This allows you
-to create fully featured games and multimedia programs in the python
-language. The package is highly portable, with games running on
-Windows, MacOS, OS X, BeOS, FreeBSD, IRIX, and Linux.
-"""
-
-import sys, os, string
-
-# check if is old windows... if so use directx video driver by default.
-# if someone sets this respect their setting...
-if not 'SDL_VIDEODRIVER' in os.environ:
-    # http://docs.python.org/lib/module-sys.html
-    # 0 (VER_PLATFORM_WIN32s) 	Win32s on Windows 3.1
-    # 1 (VER_PLATFORM_WIN32_WINDOWS) 	Windows 95/98/ME
-    # 2 (VER_PLATFORM_WIN32_NT) 	Windows NT/2000/XP
-    # 3 (VER_PLATFORM_WIN32_CE) 	Windows CE
-    if hasattr(sys, "getwindowsversion"):
-        try:
-            if (sys.getwindowsversion()[3] in [1,2] and
-                sys.getwindowsversion()[0] in [0,1,2,3,4,5]):
-                os.environ['SDL_VIDEODRIVER'] = 'directx'
-        except:
-            pass
-
-
-class MissingModule:
-    def __init__(self, name, info='', urgent=0):
-        self.name = name
-        self.info = str(info)
-        try:
-            exc = sys.exc_info()
-            if exc[0] != None:
-                self.reason = "%s: %s" % (exc[0].__name__, str(exc[1]))
-            else:
-                self.reason = ""
-        finally:
-            del exc
-        self.urgent = urgent
-        if urgent:
-            self.warn()
-
-    def __getattr__(self, var):
-        if not self.urgent:
-            self.warn()
-            self.urgent = 1
-        MissingPygameModule = "%s module not available" % self.name
-        if self.reason:
-            MissingPygameModule += "\n(%s)" % self.reason
-        raise NotImplementedError(MissingPygameModule)
-
-    def __nonzero__(self):
-        return 0
-
-    def warn(self):
-        if self.urgent: type = 'import'
-        else: type = 'use'
-        message = '%s %s: %s' % (type, self.name, self.info)
-        if self.reason:
-            message += "\n(%s)" % self.reason
-        try:
-            import warnings
-            if self.urgent: level = 4
-            else: level = 3
-            warnings.warn(message, RuntimeWarning, level)
-        except ImportError:
-            print (message)
-
-
-
-#we need to import like this, each at a time. the cleanest way to import
-#our modules is with the import command (not the __import__ function)
-
-#first, the "required" modules
-from pygame.base import *
-from pygame.constants import *
-from pygame.version import *
-from pygame.rect import Rect
-from pygame.compat import geterror
-import pygame.rwobject
-import pygame.surflock
-import pygame.color
-Color = color.Color
-__version__ = ver
-
-#next, the "standard" modules
-#we still allow them to be missing for stripped down pygame distributions
-try: import pygame.cdrom
-except (ImportError,IOError):cdrom=MissingModule("cdrom", geterror(), 1)
-
-try: import pygame.cursors
-except (ImportError,IOError):cursors=MissingModule("cursors", geterror(), 1)
-
-try: import pygame.display
-except (ImportError,IOError):display=MissingModule("display", geterror(), 1)
-
-try: import pygame.draw
-except (ImportError,IOError):draw=MissingModule("draw", geterror(), 1)
-
-try: import pygame.event
-except (ImportError,IOError):event=MissingModule("event", geterror(), 1)
-
-try: import pygame.image
-except (ImportError,IOError):image=MissingModule("image", geterror(), 1)
-
-try: import pygame.joystick
-except (ImportError,IOError):joystick=MissingModule("joystick", geterror(), 1)
-
-try: import pygame.key
-except (ImportError,IOError):key=MissingModule("key", geterror(), 1)
-
-try: import pygame.mouse
-except (ImportError,IOError):mouse=MissingModule("mouse", geterror(), 1)
-
-try: import pygame.sprite
-except (ImportError,IOError):sprite=MissingModule("sprite", geterror(), 1)
-
-
-###try: import pygame.threads
-###except (ImportError,IOError):threads=MissingModule("threads", geterror(), 1)
-
-
-def warn_unwanted_files():
-    """ Used to warn about unneeded old files.
-    """
-
-    # a temporary hack to warn about camera.so and camera.pyd.
-    install_path= os.path.split(pygame.base.__file__)[0]
-    extension_ext = os.path.splitext(pygame.base.__file__)[1]
-
-    # here are the .so/.pyd files we need to ask to remove.
-    ext_to_remove = ["camera"]
-
-    # here are the .py/.pyo/.pyc files we need to ask to remove.
-    py_to_remove = ["color"]
-
-
-    # See if any of the files are there.
-    extension_files = ["%s%s" % (x, extension_ext) for x in ext_to_remove]
-
-    py_files = ["%s%s" % (x, py_ext)
-                for py_ext in [".py", ".pyc", ".pyo"]
-                for x in py_to_remove]
-
-    files = py_files + extension_files
-
-    unwanted_files = []
-    for f in files:
-        unwanted_files.append( os.path.join( install_path, f ) )
-
-
-
-    ask_remove = []
-    for f in unwanted_files:
-        if os.path.exists(f):
-            ask_remove.append(f)
-
-
-    if ask_remove:
-        message = "Detected old file(s).  Please remove the old files:\n"
-
-        for f in ask_remove:
-            message += "%s " % f
-        message += "\nLeaving them there might break pygame.  Cheers!\n\n"
-
-        try:
-            import warnings
-            level = 4
-            warnings.warn(message, RuntimeWarning, level)
-        except ImportError:
-            print (message)
-        
-warn_unwanted_files()
-
-
-
-try: from pygame.surface import *
-except (ImportError,IOError):Surface = lambda:Missing_Function
-
-
-try:
-    import pygame.mask
-    from pygame.mask import Mask
-except (ImportError,IOError):Mask = lambda:Missing_Function
-
-try: from pygame.pixelarray import *
-except (ImportError,IOError): PixelArray = lambda:Missing_Function
-
-try: from pygame.overlay import *
-except (ImportError,IOError):Overlay = lambda:Missing_Function
-
-try: import pygame.time
-except (ImportError,IOError):time=MissingModule("time", geterror(), 1)
-
-try: import pygame.transform
-except (ImportError,IOError):transform=MissingModule("transform", geterror(), 1)
-
-#lastly, the "optional" pygame modules
-try:
-    import pygame.font
-    import pygame.sysfont
-    pygame.font.SysFont = pygame.sysfont.SysFont
-    pygame.font.get_fonts = pygame.sysfont.get_fonts
-    pygame.font.match_font = pygame.sysfont.match_font
-except (ImportError,IOError):font=MissingModule("font", geterror(), 0)
-
-# try and load pygame.mixer_music before mixer, for py2app...
-try:
-    import pygame.mixer_music
-    #del pygame.mixer_music
-    #print ("NOTE2: failed importing pygame.mixer_music in lib/__init__.py")
-except (ImportError,IOError):
-    pass
-
-try: import pygame.mixer
-except (ImportError,IOError):mixer=MissingModule("mixer", geterror(), 0)
-
-try: import pygame.movie
-except (ImportError,IOError):movie=MissingModule("movie", geterror(), 0)
-
-#try: import pygame.movieext
-#except (ImportError,IOError):movieext=MissingModule("movieext", geterror(), 0)
-
-try: import pygame.scrap
-except (ImportError,IOError):scrap=MissingModule("scrap", geterror(), 0)
-
-###try: import pygame.surfarray
-###except (ImportError,IOError):surfarray=MissingModule("surfarray", geterror(), 0)
-
-###try: import pygame.sndarray
-###except (ImportError,IOError):sndarray=MissingModule("sndarray", geterror(), 0)
-
-try: import pygame.fastevent
-except (ImportError,IOError):fastevent=MissingModule("fastevent", geterror(), 0)
-
-#there's also a couple "internal" modules not needed
-#by users, but putting them here helps "dependency finder"
-#programs get everything they need (like py2exe)
-###try: import pygame.imageext; del pygame.imageext
-###except (ImportError,IOError):pass
-
-def packager_imports():
-    """
-    Some additional things that py2app/py2exe will want to see
-    """
-    import atexit
-    import Numeric
-    import numpy
-    import OpenGL.GL
-    import pygame.macosx
-    import pygame.mac_scrap
-    import pygame.bufferproxy
-    import pygame.colordict
-    import pygame.compat
-
-#make Rects pickleable
-try:
-    import copy_reg
-except ImportError:
-    import copyreg as copy_reg
-def __rect_constructor(x,y,w,h):
-	return Rect(x,y,w,h)
-def __rect_reduce(r):
-	assert type(r) == Rect
-	return __rect_constructor, (r.x, r.y, r.w, r.h)
-copy_reg.pickle(Rect, __rect_reduce, __rect_constructor)
-
-#cleanup namespace
-###del pygame, os, sys, rwobject, surflock, MissingModule, copy_reg, geterror
-del pygame, os, sys, MissingModule, copy_reg, geterror
 perhaps make a clean copy from "Setup.in".""")
     raise
 
+#python 3.x: remove modules not yet ported
+if sys.version_info >= (3, 0, 0):
+    python3_skip = ['scrap',
+                    '_camera',
+                    'pypm',
+                    'movieext',
+                    '_numericsurfarray',
+                    '_numericsndarray',
+                    ]
+    tmp_extensions = extensions
+    extensions = []
+    for e in tmp_extensions:
+        if e.name in python3_skip:
+            print ("Skipping module %s for Python %s build." %
+                   (e.name, sys.version))
+        else:
+            extensions.append(e)
+    del tmp_extensions
 
 #extra files to install
 data_path = os.path.join(distutils.sysconfig.get_python_lib(), 'pygame')

src/_arraysurfarray.c

 
 #include <stddef.h>
 #include "pygame.h"
+#include "pgcompat.h"
 #include "pygamedocs.h"
 #include "pgarrinter.h"
 #include <SDL_byteorder.h>
     Py_RETURN_NONE;
 }
 
-static PyMethodDef surfarray_builtins[] =
+static PyMethodDef _arraysurfarray_methods[] =
 {
     { "blit_array", blit_array, METH_VARARGS, DOC_PYGAMESURFARRAYBLITARRAY },
     { NULL, NULL, 0, NULL}
 };
 
-PYGAME_EXPORT
-void init_arraysurfarray(void)
+MODINIT_DEFINE (_arraysurfarray)
 {
+    PyObject *module;
+
+#if PY3
+    static struct PyModuleDef _module = {
+        PyModuleDef_HEAD_INIT,
+        "_arraysurfarray",
+        DOC_PYGAMESURFARRAY,
+        -1,
+        _arraysurfarray_methods,
+        NULL, NULL, NULL, NULL
+    };
+#endif
+
     /* imported needed apis; Do this first so if there is an error
        the module is not loaded.
     */
     import_pygame_base();
     if (PyErr_Occurred ()) {
-	return;
+	MODINIT_ERROR;
     }
     import_pygame_surface();
     if (PyErr_Occurred ()) {
-	return;
+	MODINIT_ERROR;
     }
 
-    Py_InitModule3("_arraysurfarray", surfarray_builtins, DOC_PYGAMESURFARRAY);
+#if PY3
+    module = PyModule_Create(&_module);
+#else
+    module = Py_InitModule3("_arraysurfarray",
+                            _arraysurfarray_methods,
+                            DOC_PYGAMESURFARRAY);
+#endif
+    MODINIT_RETURN(module);
 }

src/bufferproxy.c

 #define PYGAMEAPI_BUFFERPROXY_INTERNAL
 
 #include "pygame.h"
+#include "pgcompat.h"
 #include "pygamedocs.h"
 
 static PyObject* _bufferproxy_new (PyTypeObject *type, PyObject *args,
 static PyObject* _bufferproxy_write (PyBufferProxy *buffer, PyObject *args);
 
 /* Buffer methods */
+#if PY3
+static int _bufferproxy_getbuffer (PyBufferProxy *self, Py_buffer *view,
+                                   int flags);
+static void _bufferproxy_releasebuffer (PyBufferProxy *self, Py_buffer *view);
+#else
 static Py_ssize_t _bufferproxy_getreadbuf (PyBufferProxy *buffer,
                                            Py_ssize_t _index,
                                            const void **ptr);
                                             const void **ptr);
 static Py_ssize_t _bufferproxy_getsegcount (PyBufferProxy *buffer,
                                             Py_ssize_t *lenp);
+#endif
 
 /* C API interfaces */
 static PyObject* PyBufferProxy_New (PyObject *parent, void *buffer,
 /**
  * Buffer interface support for the PyBufferProxy.
  */
+#if PY3
 static PyBufferProcs _bufferproxy_as_buffer =
 {
-        (readbufferproc) _bufferproxy_getreadbuf,
-        (writebufferproc) _bufferproxy_getwritebuf,
-        (segcountproc) _bufferproxy_getsegcount,
-        NULL,
+    (getbufferproc) _bufferproxy_getbuffer,
+    (releasebufferproc) _bufferproxy_releasebuffer
 };
+#else
+static PyBufferProcs _bufferproxy_as_buffer =
+{
+    (readbufferproc) _bufferproxy_getreadbuf,
+    (writebufferproc) _bufferproxy_getwritebuf,
+    (segcountproc) _bufferproxy_getsegcount,
+    NULL,
+#if PY_VERSION_HEX >= 0x02060000
+    NULL,
+    NULL
+#endif
+};
+#endif
 
 static PyTypeObject PyBufferProxy_Type =
 {
-    PyObject_HEAD_INIT(NULL)
-    0,
+    TYPE_HEAD (NULL, 0)
     "pygame.bufferproxy.BufferProxy", /* tp_name */
     sizeof (PyBufferProxy),     /* tp_basicsize */
     0,                          /* tp_itemsize */
 
     Py_XDECREF (self->lock);
     Py_XDECREF (self->dict);
-    self->ob_type->tp_free ((PyObject *) self);
+    Py_TYPE(self)->tp_free ((PyObject *) self);
 }
 
 /**** Getter and setter access ****/
 static PyObject*
 _bufferproxy_get_raw (PyBufferProxy *self, void *closure)
 {
-    return PyString_FromStringAndSize (self->buffer, self->length);
+    return Bytes_FromStringAndSize (self->buffer, self->length);
 }
 
 /**
 #if PY_VERSION_HEX < 0x02050000
     return PyString_FromFormat("<BufferProxy(%d)>", self->length);
 #else
-    return PyString_FromFormat("<BufferProxy(%zd)>", self->length);
+    return Text_FromFormat("<BufferProxy(%zd)>", self->length);
 #endif
 }
 
 
 /**** Buffer interfaces ****/
 
+#if PY3
+static int
+_bufferproxy_getbuffer (PyBufferProxy *self, Py_buffer *view, int flags)
+{
+    if (!view)
+        return 0;
+    Py_INCREF (self); /* Guarantee that the object does not get destroyed */
+    return PyBuffer_FillInfo (view, (PyObject*)self, self->buffer,
+                              self->length, 0, flags);
+}
+
+static void
+_bufferproxy_releasebuffer (PyBufferProxy *self, Py_buffer *view)
+{
+    Py_DECREF (self);
+}
+#else /* PY3 */
 static Py_ssize_t
 _bufferproxy_getreadbuf (PyBufferProxy *buffer, Py_ssize_t _index,
                          const void **ptr)
         *lenp = buffer->length;
     return 1;
 }
+#endif /* PY3 */
 
 static PyObject*
 PyBufferProxy_New (PyObject *parent, void *buffer, Py_ssize_t length,
     return (PyObject *) buf;
 }
 
-PYGAME_EXPORT
-void initbufferproxy (void)
+/*DOC*/ static char _bufferproxy_doc[] =
+/*DOC*/    "A generic proxy module that can spend arbitrary " \
+/*DOC*/    "objects a buffer interface";
+
+MODINIT_DEFINE (bufferproxy)
 {
     PyObject *module;
     PyObject *dict;
     PyObject *apiobj;
+    int ecode;
     static void* c_api[PYGAMEAPI_BUFFERPROXY_NUMSLOTS];
 
+#if PY3
+    static struct PyModuleDef _module = {
+        PyModuleDef_HEAD_INIT,
+        "bufferproxy",
+        _bufferproxy_doc,
+        -1,
+        _bufferproxy_methods,
+        NULL, NULL, NULL, NULL
+    };
+#endif
+
     if (PyType_Ready (&PyBufferProxy_Type) < 0)
-        return;
+        MODINIT_ERROR;
 
     /* create the module */
-    module = Py_InitModule3 ("bufferproxy", NULL,
-        "A generic proxy module that can spend arbitrary " \
-        "objects a buffer interface");
+#if PY3
+    module = PyModule_Create (&_module);
+#else
+    module = Py_InitModule3 ("bufferproxy", NULL, _bufferproxy_doc);
+#endif
     PyBufferProxy_Type.tp_getattro = PyObject_GenericGetAttr;
     Py_INCREF (&PyBufferProxy_Type);
-    PyModule_AddObject (module, "BufferProxy", (PyObject *)&PyBufferProxy_Type);
+    if (PyModule_AddObject (module, "BufferProxy",
+                            (PyObject *)&PyBufferProxy_Type) == -1) {
+        Py_DECREF ((PyObject *)&PyBufferProxy_Type);
+        DECREF_MOD (module);
+        MODINIT_ERROR;
+    }
     dict = PyModule_GetDict (module);
 
     c_api[0] = &PyBufferProxy_Type;
     c_api[1] = PyBufferProxy_New;
     apiobj = PyCObject_FromVoidPtr (c_api, NULL);
-    PyDict_SetItemString (dict, PYGAMEAPI_LOCAL_ENTRY, apiobj);
+    if (apiobj == NULL) {
+        DECREF_MOD (module);
+        MODINIT_ERROR;
+    }
+    ecode = PyDict_SetItemString (dict, PYGAMEAPI_LOCAL_ENTRY, apiobj);
     Py_DECREF (apiobj);
+    if (ecode == -1) {
+        DECREF_MOD (module);
+        MODINIT_ERROR;
+    }
+    MODINIT_RETURN (module);
 }
     return PyFloat_FromDouble ((float)numsamples / (float)freq);
 }
 
-#if !PY3 /* Not ready for the Python 3 buffer interface just yet. */
 static PyObject*
 snd_get_buffer (PyObject* self)
 {
         return RAISE (PyExc_SDLError, "could acquire a buffer for the sound");
     return buffer;
 }
-#endif
 
 static PyMethodDef sound_methods[] =
 {
       DOC_SOUNDGETVOLUME },
     { "get_length", (PyCFunction) snd_get_length, METH_NOARGS,
       DOC_SOUNDGETLENGTH },
-#if !PY3 /* Not ready for Python 3 buffer interface just yet. */
     { "get_buffer", (PyCFunction) snd_get_buffer, METH_NOARGS,
       DOC_SOUNDGETBUFFER },
-#endif
     { NULL, NULL, 0, NULL }
 };
 
     if (PyErr_Occurred ()) {
 	MODINIT_ERROR;
     }
-#if !PY3 /* Not ready for the Python 3 buffer interface just yet. */
     import_pygame_bufferproxy ();
     if (PyErr_Occurred ()) {
 	MODINIT_ERROR;
     }
-#endif
 
     /* type preparation */
     if (PyType_Ready (&PySound_Type) < 0) {
  *  movie playback for pygame
  */
 #include "pygame.h"
+#include "pgcompat.h"
 #include "pygamedocs.h"
 #include "smpeg.h"
 
 } PyMovieObject;
 #define PyMovie_AsSMPEG(x) (((PyMovieObject*)x)->movie)
 
-staticforward PyTypeObject PyMovie_Type;
+static PyTypeObject PyMovie_Type;
 static PyObject* PyMovie_New (SMPEG*);
 #define PyMovie_Check(x) ((x)->ob_type == &PyMovie_Type)
 
     return PyInt_FromLong (info.current_frame);
 }
 
-static PyMethodDef movie_builtins[] =
+static PyMethodDef movie_methods[] =
 {
     { "play", (PyCFunction)movie_play, METH_NOARGS, DOC_MOVIEPLAY },
     { "stop", (PyCFunction) movie_stop, METH_NOARGS, DOC_MOVIESTOP },
     PyObject_DEL (self);
 }
 
-static PyObject*
-movie_getattr (PyObject* self, char* attrname)
-{
-    return Py_FindMethod (movie_builtins, self, attrname);
-}
-
 static PyTypeObject PyMovie_Type =
 {
-    PyObject_HEAD_INIT(NULL)
-    0,
-    "Movie",
-    sizeof(PyMovieObject),
-    0,
-    movie_dealloc,
-    0,
-    movie_getattr,
-    NULL,					/*setattr*/
-    NULL,					/*compare*/
-    NULL,					/*repr*/
-    NULL,					/*as_number*/
-    NULL,					/*as_sequence*/
-    NULL,					/*as_mapping*/
-    (hashfunc)NULL, 		/*hash*/
-    (ternaryfunc)NULL,		/*call*/
-    (reprfunc)NULL, 		/*str*/
-    0L,0L,0L,0L,
-    DOC_PYGAMEMOVIEMOVIE /* Documentation string */
+    TYPE_HEAD (NULL, 0)
+    "movie",                    /* name */
+    sizeof(PyMovieObject),      /* basic size */
+    0,                          /* itemsize */
+    movie_dealloc,              /* dealloc */
+    0,                          /* print */
+    0,                          /* getattr */
+    0,                          /* setattr */
+    0,                          /* compare */
+    0,                          /* repr */
+    0,                          /* as_number */
+    0,                          /* as_sequence */
+    0,                          /* as_mapping */
+    0,                          /* hash */
+    0,                          /* call */
+    0,                          /* str */
+    0,                          /* tp_getattro */
+    0,                          /* tp_setattro */
+    0,                          /* tp_as_buffer */
+    0,                          /* flags */
+    DOC_PYGAMEMOVIEMOVIE,       /* Documentation string */
+    0,                          /* tp_traverse */
+    0,                          /* tp_clear */
+    0,                          /* tp_richcompare */
+    0,                          /* tp_weaklistoffset */
+    0,	                        /* tp_iter */
+    0,                          /* tp_iternext */
+    movie_methods,              /* tp_methods */
+    0,                          /* tp_members */
+    0,                          /* tp_getset */
+    0,                          /* tp_base */
+    0,                          /* tp_dict */
+    0,                          /* tp_descr_get */
+    0,                          /* tp_descr_set */
+    0,                          /* tp_dictoffset */
+    0,                          /* tp_init */
+    0,				/* tp_alloc */
+    0,			        /* tp_new */
 };
 
 /*movie module methods*/
     if (!SDL_WasInit (SDL_INIT_AUDIO))
         audioavail = 1;
 
-    if (PyString_Check (file) || PyUnicode_Check (file))
+    if (Bytes_Check (file) || PyUnicode_Check (file))
     {
         if (!PyArg_ParseTuple (arg, "s", &name))
             return NULL;
         movie = SMPEG_new (name, &info, audioavail);
     }
+#if !PY3
     else if (PyFile_Check (file))
     {
         SDL_RWops *rw = SDL_RWFromFP (PyFile_AsFile (file), 0);
         filesource = file;
         Py_INCREF (file);
     }
+#endif
     else
     {
         SDL_RWops *rw;
     return final;
 }
 
-static PyMethodDef mixer_builtins[] =
+static PyMethodDef _movie_methods[] =
 {
     { "Movie", Movie, METH_VARARGS, DOC_PYGAMEMOVIEMOVIE },
     { NULL, NULL, 0, NULL }
     return (PyObject*)movieobj;
 }
 
-PYGAME_EXPORT
-void initmovie (void)
+MODINIT_DEFINE (movie)
 {
     PyObject *module, *dict;
 
+#if PY3
+    static struct PyModuleDef _module = {
+        PyModuleDef_HEAD_INIT,
+        "movie",
+        DOC_PYGAMEMOVIE,
+        -1,
+        _movie_methods,
+        NULL, NULL, NULL, NULL
+    };
+#endif
+
     /* imported needed apis; Do this first so if there is an error
        the module is not loaded.
     */
     import_pygame_base ();
     if (PyErr_Occurred ()) {
-	return;
+	MODINIT_ERROR;
     }
     import_pygame_surface ();
     if (PyErr_Occurred ()) {
-	return;
+	MODINIT_ERROR;
     }
     import_pygame_rwobject ();
     if (PyErr_Occurred ()) {
-	return;
+	MODINIT_ERROR;
     }
     import_pygame_rect ();
     if (PyErr_Occurred ()) {
-	return;
+	MODINIT_ERROR;
     }
 
     /* type preparation */
-    PyType_Init (PyMovie_Type);
+    if (PyType_Ready (&PyMovie_Type) == -1) {
+        MODINIT_ERROR;
+    }
 
     /* create the module */
-    module = Py_InitModule3 ("movie", mixer_builtins, DOC_PYGAMEMOVIE);
+#if PY3
+    module = PyModule_Create (&_module);
+#else
+    module = Py_InitModule3 ("movie", _movie_methods, DOC_PYGAMEMOVIE);
+#endif
+    if (module == NULL) {
+        MODINIT_ERROR;
+    }
     dict = PyModule_GetDict (module);
 
-    PyDict_SetItemString (dict, "MovieType", (PyObject *)&PyMovie_Type);
+    if (PyDict_SetItemString (dict, "MovieType",
+                              (PyObject *)&PyMovie_Type) == -1) {
+        DECREF_MOD (module);
+        MODINIT_ERROR;
+    }
+
+    MODINIT_RETURN (module);
 }
 #define PYGAMEAPI_PIXELARRAY_INTERNAL
 
 #include "pygame.h"
+#include "pgcompat.h"
 #include "pygamedocs.h"
 #include "surface.h"
 
 /* Sequence methods */
 static Py_ssize_t _pxarray_length (PyPixelArray *array);
 static PyObject* _pxarray_item (PyPixelArray *array, Py_ssize_t _index);
+#if !PY3
 static PyObject* _pxarray_slice (PyPixelArray *array, Py_ssize_t low,
     Py_ssize_t high);
+#endif
 static int _array_assign_array (PyPixelArray *array, Py_ssize_t low,
     Py_ssize_t high, PyPixelArray *val);
 static int _array_assign_sequence (PyPixelArray *array, Py_ssize_t low,
 /* Incomplete forward declaration so we can use it in the methods included
  * below.
  */
-staticforward PyTypeObject PyPixelArray_Type;
+static PyTypeObject PyPixelArray_Type;
 #define PyPixelArray_Check(o) \
-    ((o)->ob_type == (PyTypeObject *) &PyPixelArray_Type)
+    (Py_TYPE (o) == (PyTypeObject *) &PyPixelArray_Type)
 
 #define SURFACE_EQUALS(x,y) \
     (((PyPixelArray *)x)->surface == ((PyPixelArray *)y)->surface)
  */
 static PyMethodDef _pxarray_methods[] =
 {
-    { "compare", (PyCFunction) _compare, METH_KEYWORDS,
+    { "compare", (PyCFunction) _compare, METH_VARARGS | METH_KEYWORDS,
       DOC_PIXELARRAYCOMPARE },
-    { "extract", (PyCFunction) _extract_color, METH_KEYWORDS,
+    { "extract", (PyCFunction) _extract_color, METH_VARARGS | METH_KEYWORDS,
       DOC_PIXELARRAYEXTRACT },
-    { "make_surface", (PyCFunction) _make_surface, METH_NOARGS,
+    { "make_surface", (PyCFunction) _make_surface, METH_VARARGS | METH_NOARGS,
       DOC_PIXELARRAYMAKESURFACE },
-    { "replace", (PyCFunction) _replace_color, METH_KEYWORDS,
+    { "replace", (PyCFunction) _replace_color, METH_VARARGS | METH_KEYWORDS,
       DOC_PIXELARRAYREPLACE },
     { NULL, NULL, 0, NULL }
 };
 
+#if PY3
+static void
+Text_ConcatAndDel (PyObject **string, PyObject *newpart)
+{
+    PyObject *result = NULL;
+    if (*string != NULL && newpart != NULL) {
+        PyUnicode_Concat (*string, newpart);
+        Py_DECREF (*string);
+        Py_DECREF (newpart);
+    }
+    else {
+        Py_XDECREF (*string);
+        Py_XDECREF (newpart);
+    }
+    *string = result;
+}
+#else
+#define Text_ConcatAndDel PyString_ConcatAndDel
+#endif
+
 /**
  * Getters and setters for the PyPixelArray.
  */
     NULL, /*sq_concat*/
     NULL, /*sq_repeat*/
     (ssizeargfunc) _pxarray_item,               /*sq_item*/
+#if PY3
+    NULL,
+#else
     (ssizessizeargfunc) _pxarray_slice,         /*sq_slice*/
+#endif
     (ssizeobjargproc) _pxarray_ass_item,        /*sq_ass_item*/
+#if PY3
+    NULL,
+#else
     (ssizessizeobjargproc) _pxarray_ass_slice,  /*sq_ass_slice*/
+#endif
     (objobjproc) _pxarray_contains,             /*sq_contains*/
     NULL, /*sq_inplace_concat*/
     NULL, /*sq_inplace_repeat*/
 
 static PyTypeObject PyPixelArray_Type =
 {
-    PyObject_HEAD_INIT(NULL)
-    0,
+    TYPE_HEAD (NULL, 0)
     "pygame.PixelArray",        /* tp_name */
     sizeof (PyPixelArray),      /* tp_basicsize */
     0,                          /* tp_itemsize */
             if (!self->lock)
             {
                 Py_DECREF (surface);
-                self->ob_type->tp_free ((PyObject *) self);
+                Py_TYPE (self)->tp_free ((PyObject *) self);
                 return NULL;
             }
         }
     Py_XDECREF (self->parent);
     Py_XDECREF (self->dict);
     Py_DECREF (self->surface);
-    self->ob_type->tp_free ((PyObject *) self);
+    Py_TYPE (self)->tp_free ((PyObject *) self);
 }
 
 /**** Getter and setter access ****/
         array->xstart, array->xlen, array->xstep, array->ystart, 
         array->ylen, array->ystep, array->padding);
 */
-    string = PyString_FromString ("PixelArray(");
+    string = Text_FromUTF8 ("PixelArray(");
 
     absxstep = ABS (array->xstep);
     absystep = ABS (array->ystep);
         while (posy < array->ylen)
         {
             /* Construct the rows */
-            PyString_ConcatAndDel (&string, PyString_FromString ("\n  ["));
+            Text_ConcatAndDel (&string, Text_FromUTF8 ("\n  ["));
+            if (string == NULL)
+            {
+                return NULL;
+            }
             posx = 0;
             x = array->xstart;
             while (posx < (Uint32)xlen)
             {
                 /* Construct the columns */
                 pixel = (Uint32) *((Uint8 *) pixels + x + y * array->padding);
-                PyString_ConcatAndDel (&string, PyString_FromFormat
-                    ("%ld, ", (long)pixel));
+                Text_ConcatAndDel (&string,
+                                   Text_FromFormat ("%ld, ", (long)pixel));
+                if (string == NULL)
+                {
+                    return NULL;
+                }
                 x += array->xstep;
                 posx += absxstep;
             }
             pixel = (Uint32) *((Uint8 *) pixels + x + y * array->padding);
-            PyString_ConcatAndDel (&string,
-                PyString_FromFormat ("%ld]", (long)pixel));
+            Text_ConcatAndDel (&string,
+                               Text_FromFormat ("%ld]", (long)pixel));
+            if (string == NULL)
+            {
+                return NULL;
+            }
             y += array->ystep;
             posy += absystep;
         }
         while (posy < array->ylen)
         {
             /* Construct the rows */
-            PyString_ConcatAndDel (&string, PyString_FromString ("\n  ["));
+            Text_ConcatAndDel (&string, Text_FromUTF8 ("\n  ["));
+            if (string == NULL)
+            {
+                return NULL;
+            }
             posx = 0;
             x = array->xstart;
             while (posx < (Uint32)xlen)
                 /* Construct the columns */
                 pixel = (Uint32)
                     *((Uint16 *) (pixels + y * array->padding) + x);
-                PyString_ConcatAndDel (&string, PyString_FromFormat
-                    ("%ld, ", (long)pixel));
+                Text_ConcatAndDel (&string,
+                                   Text_FromFormat ("%ld, ", (long)pixel));
+                if (string == NULL)
+                {
+                    return NULL;
+                }
                 x += array->xstep;
                 posx += absxstep;
             }
             pixel = (Uint32) *((Uint16 *) (pixels + y * array->padding) + x);
-            PyString_ConcatAndDel (&string,
-                PyString_FromFormat ("%ld]", (long)pixel));
+            Text_ConcatAndDel (&string,
+                               Text_FromFormat ("%ld]", (long)pixel));
+            if (string == NULL)
+            {
+                return NULL;
+            }
             y += array->ystep;
             posy += absystep;
         }
         while (posy < array->ylen)
         {
             /* Construct the rows */
-            PyString_ConcatAndDel (&string, PyString_FromString ("\n  ["));
+            Text_ConcatAndDel (&string, Text_FromUTF8 ("\n  ["));
+            if (string == NULL)
+            {
+                return NULL;
+            }
             posx = 0;
             x = array->xstart;
             while (posx < (Uint32)xlen)
 #else
                 pixel = (px24[2]) + (px24[1] << 8) + (px24[0] << 16);
 #endif
-                PyString_ConcatAndDel (&string, PyString_FromFormat
-                    ("%ld, ", (long)pixel));
+                Text_ConcatAndDel (&string,
+                                   Text_FromFormat ("%ld, ", (long)pixel));
+                if (string == NULL)
+                {
+                    return NULL;
+                }
                 x += array->xstep;
                 posx += absxstep;
             }
 #else
             pixel = (px24[2]) + (px24[1] << 8) + (px24[0] << 16);
 #endif
-            PyString_ConcatAndDel (&string,
-                PyString_FromFormat ("%ld]", (long)pixel));
+            Text_ConcatAndDel (&string,
+                               Text_FromFormat ("%ld]", (long)pixel));
+            if (string == NULL)
+            {
+                return NULL;
+            }
             y += array->ystep;
             posy += absystep;
         }
         while (posy < array->ylen)
         {
             /* Construct the rows */
-            PyString_ConcatAndDel (&string, PyString_FromString ("\n  ["));
+            Text_ConcatAndDel (&string, Text_FromUTF8 ("\n  ["));
+            if (string == NULL)
+            {
+                return NULL;
+            }
             posx = 0;
             x = array->xstart;
             while (posx < (Uint32)xlen)
             {
                 /* Construct the columns */
                 pixel = *((Uint32 *) (pixels + y * array->padding) + x);
-                PyString_ConcatAndDel (&string, PyString_FromFormat
-                    ("%ld, ", (long)pixel));
+                Text_ConcatAndDel (&string,
+                                   Text_FromFormat ("%ld, ", (long)pixel));
+                if (string == NULL)
+                {
+                    return NULL;
+                }
                 x += array->xstep;
                 posx += absxstep;
             }
             pixel = *((Uint32 *) (pixels + y * array->padding) + x);
-            PyString_ConcatAndDel (&string,
-                PyString_FromFormat ("%ld]", (long)pixel));
+            Text_ConcatAndDel (&string,
+                               Text_FromFormat ("%ld]", (long)pixel));
+            if (string == NULL)
+            {
+                return NULL;
+            }
             y += array->ystep;
             posy += absystep;
         }
         break;
     }
-    PyString_ConcatAndDel (&string, PyString_FromString ("\n)"));
+    Text_ConcatAndDel (&string, Text_FromUTF8 ("\n)"));
     return string;
 }
 
     return _array_slice_internal (array, _index, _index + 1, 1);
 }
 
+#if !PY3
 /**
  * array[x:y]
  */
 
     return _array_slice_internal (array, low, high, 1);
 }
+#endif
 
 static int
 _array_assign_array (PyPixelArray *array, Py_ssize_t low, Py_ssize_t high,
             (Uint32) surface->pitch, NULL);
 }
 
-PYGAME_EXPORT
-void initpixelarray (void)
+MODINIT_DEFINE (pixelarray)
 {
     PyObject *module;
     PyObject *dict;
     PyObject *apiobj;
+    int ecode;
     static void* c_api[PYGAMEAPI_PIXELARRAY_NUMSLOTS];
 
+#if PY3
+    static struct PyModuleDef _module = {
+        PyModuleDef_HEAD_INIT,
+        "pixelarray",
+        NULL,
+        -1,
+        NULL,
+        NULL, NULL, NULL, NULL
+    };
+#endif
+
     /* imported needed apis; Do this first so if there is an error
        the module is not loaded.
     */
     import_pygame_base ();
     if (PyErr_Occurred ()) {
-	return;
+	MODINIT_ERROR;
     }
     import_pygame_color();
     if (PyErr_Occurred ()) {
-	return;
+	MODINIT_ERROR;
     }
     import_pygame_surface ();
     if (PyErr_Occurred ()) {
-	return;
+	MODINIT_ERROR;
     }
 
     /* type preparation */
     if (PyType_Ready (&PyPixelArray_Type) < 0)
-        return;
+    {
+        MODINIT_ERROR;
+    }
     
     /* create the module */
+#if PY3
+    module = PyModule_Create (&_module);
+#else
     module = Py_InitModule3 ("pixelarray", NULL, NULL);
+#endif
+    if (module == NULL)
+    {
+        MODINIT_ERROR;
+    }
     Py_INCREF (&PyPixelArray_Type);
-    PyModule_AddObject (module, "PixelArray", (PyObject *) &PyPixelArray_Type);
+    if (PyModule_AddObject (module, "PixelArray",
+                            (PyObject *) &PyPixelArray_Type) == -1)
+    {
+        DECREF_MOD (module);
+        MODINIT_ERROR;
+    }
     PyPixelArray_Type.tp_getattro = PyObject_GenericGetAttr;
     dict = PyModule_GetDict (module);
 
     c_api[0] = &PyPixelArray_Type;
     c_api[1] = PyPixelArray_New;
     apiobj = PyCObject_FromVoidPtr (c_api, NULL);
-    PyDict_SetItemString (dict, PYGAMEAPI_LOCAL_ENTRY, apiobj);
+    if (apiobj == NULL)
+    {
+        DECREF_MOD (module);
+        MODINIT_ERROR;
+    }
+    ecode = PyDict_SetItemString (dict, PYGAMEAPI_LOCAL_ENTRY, apiobj);
     Py_DECREF (apiobj);
+    if (ecode == -1)
+    {
+        DECREF_MOD (module);
+        MODINIT_ERROR;
+    }
+    MODINIT_RETURN (module);
 }
 static PyObject *surf_get_offset (PyObject *self);
 static PyObject *surf_get_parent (PyObject *self);
 static PyObject *surf_subsurface (PyObject *self, PyObject *args);
-#if !PY3
 static PyObject *surf_get_buffer (PyObject *self);
-#endif
 static PyObject *surf_get_bounding_rect (PyObject *self, PyObject *args,
                                           PyObject *kwargs);
 
     { "get_bounding_rect", (PyCFunction) surf_get_bounding_rect,
       METH_VARARGS | METH_KEYWORDS,
       DOC_SURFACEGETBOUNDINGRECT},
-#if !PY3
     { "get_buffer", (PyCFunction) surf_get_buffer, METH_NOARGS,
       DOC_SURFACEGETBUFFER},
-#endif
 
     { NULL, NULL, 0, NULL }
 };
     SDL_Surface *surf = PySurface_AsSurface (self);
 
     if (PyTuple_GET_SIZE (args) > 0) {
-        return PyErr_Format (PyExc_TypeError,
-                             "get_rect only accepts keyword arguments",
-                             PyTuple_GET_SIZE (args));
+        return RAISE (PyExc_TypeError,
+                      "get_rect only accepts keyword arguments");
     }
 
     if (!surf)
     return rect;
 }
 
-#if !PY3
 static PyObject
 *surf_get_buffer (PyObject *self)
 {
 
     return buffer;
 }
-#endif
 
 static void
 surface_move (Uint8 *src, Uint8 *dst, int h, int span,
     if (PyErr_Occurred ()) {
         MODINIT_ERROR;
     }
-    #if !PY3
     import_pygame_bufferproxy();
     if (PyErr_Occurred ()) {
         MODINIT_ERROR;
     }
-    #endif
 
     /* import the surflock module manually */
     lockmodule = PyImport_ImportModule ("pygame.surflock");

test/pixelarray_test.py

+import sys
 if __name__ == '__main__':
-    import sys
     import os
     pkg_dir = os.path.split(os.path.abspath(__file__))[0]
     parent_dir, pkg_name = os.path.split(pkg_dir)
 else:
     from test.test_utils import test_not_implemented, unittest
 import pygame
+from pygame.compat import xrange_
+
+PY3 = sys.version_info >= (3, 0, 0)
 
 class PixelArrayTypeTest (unittest.TestCase):
     def todo_test_compare(self):
         for bpp in (8, 16, 24, 32):
             sf = pygame.Surface ((10, 20), 0, bpp)
             sf.fill ((0, 0, 255))
-            for x in xrange (20):
+            for x in xrange_ (20):
                 sf.set_at ((1, x), (0, 0, 11))
-            for x in xrange (10):
+            for x in xrange_ (10):
                 sf.set_at ((x, 1), (0, 0, 11))
 
             ar = pygame.PixelArray (sf)
             sf = pygame.Surface ((10, 20), 0, bpp)
             sf.fill ((0, 0, 0))
             ar = pygame.PixelArray (sf)
+
+            if PY3:
+                self.assertEqual (len (ar[0:2]), 2)
+                self.assertEqual (len (ar[3:7][3]), 20)
+
+                self.assertEqual (ar[0:0], None)
+                self.assertEqual (ar[5:5], None)
+                self.assertEqual (ar[9:9], None)
+            else:
+                self.assertEqual (len (ar.__getslice__ (0, 2)), 2)
+                self.assertEqual (len (ar.__getslice__ (3, 7)[3]), 20)
         
-            self.assertEqual (len (ar.__getslice__ (0, 2)), 2)
-            self.assertEqual (len (ar.__getslice__ (3, 7)[3]), 20)
-        
-            self.assertEqual (ar.__getslice__ (0, 0), None)
-            self.assertEqual (ar.__getslice__ (5, 5), None)
-            self.assertEqual (ar.__getslice__ (9, 9), None)
+                self.assertEqual (ar.__getslice__ (0, 0), None)
+                self.assertEqual (ar.__getslice__ (5, 5), None)
+                self.assertEqual (ar.__getslice__ (9, 9), None)
         
             # Has to resolve to ar[7:8]
             self.assertEqual (len (ar[-3:-2]), 20)
             # Try assignments.
 
             # 2D assignment.
-            ar.__setslice__ (2, 5, (255, 255, 255))
+            if PY3:
+                ar[2:5] = (255, 255, 255)
+            else:
+                ar.__setslice__ (2, 5, (255, 255, 255))
             self.assertEqual (ar[3][3], sf.map_rgb ((255, 255, 255)))
 
             # 1D assignment
-            ar[3].__setslice__ (3, 7, (10, 10, 10))
+            if PY3:
+                ar[3][3:7] = (10, 10, 10)
+            else:
+                ar[3].__setslice__ (3, 7, (10, 10, 10))
+                
             self.assertEqual (ar[3][5], sf.map_rgb ((10, 10, 10)))
             self.assertEqual (ar[3][6], sf.map_rgb ((10, 10, 10)))
 
 
             # Test single value assignment
             val = sf.map_rgb ((128, 128, 128))
-            ar.__setslice__ (0, 2, val)
+            if PY3:
+                ar[0:2] = val
+            else:
+                ar.__setslice__ (0, 2, val)
             self.assertEqual (ar[0][0], val)
             self.assertEqual (ar[0][1], val)
             self.assertEqual (ar[1][0], val)
 
             # Test list assignment, this is a vertical assignment.
             val = sf.map_rgb ((0, 255, 0))
-            ar.__setslice__ (2, 4, [val] * 8)
+            if PY3:
+                ar[2:4] = [val] * 8
+            else:
+                ar.__setslice__ (2, 4, [val] * 8)
             self.assertEqual (ar[2][0], val)
             self.assertEqual (ar[2][1], val)
             self.assertEqual (ar[2][4], val)
             # And the horizontal assignment.
             val = sf.map_rgb ((255, 0, 0))
             val2 = sf.map_rgb ((128, 0, 255))
-            ar.__setslice__ (0, 2, [val, val2])
+            if PY3:
+                ar[0:2] = [val, val2]
+            else:
+                ar.__setslice__ (0, 2, [val, val2])
             self.assertEqual (ar[0][0], val)
             self.assertEqual (ar[1][0], val2)
             self.assertEqual (ar[0][1], val)
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.