Commits

Lenard Lindstrom committed 7076791

adapt mask module for Python 3.1

Comments (0)

Files changed (7)

     def collide(self,s):
         """Test if the sprites are colliding and
         resolve the collision in this case."""
-        offset = map(int,vsub(s.pos,self.pos))
+        offset = [int(x) for x in vsub(s.pos,self.pos)]
         overlap = self.mask.overlap_area(s.mask,offset)
         if overlap == 0:
             return
     
     if len(args) == 0:
         raise ValueError("Require at least one image file name: non given")
-    print 'Press any key to quit'
+    print ('Press any key to quit')
     screen = pygame.display.set_mode((640,480))
     images = []
     masks = []
         m = maskFromSurface(images[-1])
     t2 = time.time()
 
-    print "python maskFromSurface :%s" % (t2-t1)
+    print ("python maskFromSurface :%s" % (t2-t1))
 
     t1 = time.time()
     for x in range(numtimes):
         m = pygame.mask.from_surface(images[-1])
     t2 = time.time()
 
-    print "C pygame.mask.from_surface :%s" % (t2-t1)
+    print ("C pygame.mask.from_surface :%s" % (t2-t1))
 
     sprites = []
     for i in range(20):
 
 if __name__ == '__main__':
     if len(sys.argv) < 2:
-        print 'Usage: mask.py <IMAGE> [<IMAGE> ...]'
-        print 'Let many copies of IMAGE(s) bounce against each other'
-        print 'Press any key to quit'
+        print ('Usage: mask.py <IMAGE> [<IMAGE> ...]')
+        print ('Let many copies of IMAGE(s) bounce against each other')
+        print ('Press any key to quit')
     else:
         main(*sys.argv[1:])
 
    #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 "+`size`
+       raise ValueError("cursor string sizes must be divisible by 8 %s" %
+                        size)
    for s in strings[1:]:
        if len(s) != size[0]:
-           raise ValueError, "Cursor strings are inconsistent lengths"
+           raise ValueError("Cursor strings are inconsistent lengths")
 
    #create the data arrays.
    #this could stand a little optimizing
     __hasnumeric = True
     if not __hasnumpy:
         __arraytype = "numeric"
-except ImportError, msg:
+except ImportError:
     __hasnumeric = False
 
 if not __hasnumpy and not __hasnumeric:
-    raise ImportError, "no module named numpy or Numeric found"
+    raise ImportError("no module named numpy or Numeric found")
 
 from _arraysurfarray import blit_array
 
         return numericsf.array2d (surface)
     elif __arraytype == "numpy":
         return numpysf.array2d (surface)
-    raise NotImplementedError, "surface arrays are not supported"
+    raise NotImplementedError("surface arrays are not supported")
 
 def pixels2d (surface):
     """pygame.surfarray.pixels2d (Surface): return array
         return numericsf.pixels2d (surface)
     elif __arraytype == "numpy":
         return numpysf.pixels2d (surface)
-    raise NotImplementedError, "surface arrays are not supported"
+    raise NotImplementedError("surface arrays are not supported")
 
 def array3d (surface):
     """pygame.surfarray.array3d (Surface): return array
         return numericsf.array3d (surface)
     elif __arraytype == "numpy":
         return numpysf.array3d (surface)
-    raise NotImplementedError, "surface arrays are not supported"
+    raise NotImplementedError("surface arrays are not supported")
 
 def pixels3d (surface):
     """pygame.surfarray.pixels3d (Surface): return array
         return numericsf.pixels3d (surface)
     elif __arraytype == "numpy":
         return numpysf.pixels3d (surface)
-    raise NotImplementedError, "surface arrays are not supported"
+    raise NotImplementedError("surface arrays are not supported")
 
 def array_alpha (surface):
     """pygame.surfarray.array_alpha (Surface): return array
         return numericsf.array_alpha (surface)
     elif __arraytype == "numpy":
         return numpysf.array_alpha (surface)
-    raise NotImplementedError, "surface arrays are not supported"
+    raise NotImplementedError("surface arrays are not supported")
 
 def pixels_alpha (surface):
     """pygame.surfarray.pixels_alpha (Surface): return array
         return numericsf.pixels_alpha (surface)
     elif __arraytype == "numpy":
         return numpysf.pixels_alpha (surface)
-    raise NotImplementedError, "surface arrays are not supported"
+    raise NotImplementedError("surface arrays are not supported")
 
 def array_colorkey (surface):
     """pygame.surfarray.array_colorkey (Surface): return array
         return numericsf.array_colorkey (surface)
     elif __arraytype == "numpy":
         return numpysf.array_colorkey (surface)
-    raise NotImplementedError, "surface arrays are not supported"
+    raise NotImplementedError("surface arrays are not supported")
 
 def make_surface (array):
     """pygame.surfarray.make_surface (array): return Surface
         return numericsf.make_surface (array)
     elif __arraytype == "numpy":
         return numpysf.make_surface (array)
-    raise NotImplementedError, "surface arrays are not supported"
+    raise NotImplementedError("surface arrays are not supported")
 
 ##def blit_array (surface, array):
 ##    """pygame.surfarray.blit_array (Surface, array): return None
 ##        return numericsf.blit_array (surface, array)
 ##    elif __arraytype == "numpy":
 ##        return numpysf.blit_array (surface, array)
-##    raise NotImplementedError, "surface arrays are not supported"
+##    raise NotImplementedError("surface arrays are not supported")
 
 def map_array (surface, array):
     """pygame.surfarray.map_array (Surface, array3d): return array2d
         return numericsf.map_array (surface, array)
     elif __arraytype == "numpy":
         return numpysf.map_array (surface, array)
-    raise NotImplementedError, "surface arrays are not supported"
+    raise NotImplementedError("surface arrays are not supported")
 
 def use_arraytype (arraytype):
     """pygame.surfarray.use_arraytype (arraytype): return None
         if __hasnumeric:
             __arraytype = arraytype
         else:
-            raise ValueError, "Numeric arrays are not available"
+            raise ValueError("Numeric arrays are not available")
         
     elif arraytype == "numpy":
         if __hasnumpy:
             __arraytype = arraytype
         else:
-            raise ValueError, "numpy arrays are not available"
+            raise ValueError("numpy arrays are not available")
     else:
-        raise ValueError, "invalid array type"
+        raise ValueError("invalid array type")
 
 def get_arraytype ():
     """pygame.surfarray.get_arraytype (): return str
 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)
+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)
 ###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.cursors
+except (ImportError,IOError):cursors=MissingModule("cursors", geterror(), 1)
 
 try: import pygame.display
 except (ImportError,IOError):display=MissingModule("display", geterror(), 1)
 #define PYGAMEAPI_MASK_INTERNAL 1
 #include "mask.h"
 #include "pygame.h"
+#include "pgcompat.h"
 #include "pygamedocs.h"
 #include "structmember.h"
 #include "bitmask.h"
 #define M_PI 3.14159265358979323846
 #endif
 
-staticforward PyTypeObject PyMask_Type;
+static PyTypeObject PyMask_Type;
 
 /* mask object methods */
 
 }
 
 
-static PyMethodDef maskobj_builtins[] =
+static PyMethodDef mask_methods[] =
 {
     { "get_size", mask_get_size, METH_VARARGS, DOC_MASKGETSIZE},
     { "get_at", mask_get_at, METH_VARARGS, DOC_MASKGETAT },
 }
 
 
-static PyObject* mask_getattr(PyObject* self, char* attrname)
-{
-    return Py_FindMethod(maskobj_builtins, self, attrname);
-}
-
 
 static PyTypeObject PyMask_Type =
 {
-    PyObject_HEAD_INIT(NULL)
-    0,
+    TYPE_HEAD (NULL, 0)
     "pygame.mask.Mask",
     sizeof(PyMaskObject),
     0,
     mask_dealloc,
     0,
-    mask_getattr,
+    0,
     0,
     0,
     0,
     (ternaryfunc)NULL,
     (reprfunc)NULL,
     0L,0L,0L,0L,
-    DOC_PYGAMEMASKMASK /* Documentation string */
+    DOC_PYGAMEMASKMASK,                 /* Documentation string */
+    0,                                  /* tp_traverse */
+    0,				        /* tp_clear */
+    0,				        /* tp_richcompare */
+    0,                                  /* tp_weaklistoffset */
+    0,				        /* tp_iter */
+    0,				        /* tp_iternext */
+    mask_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 */
 };
 
 
 
 
 
-static PyMethodDef mask_builtins[] =
+static PyMethodDef _mask_methods[] =
 {
     { "Mask", Mask, METH_VARARGS, DOC_PYGAMEMASKMASK },
     { "from_surface", mask_from_surface, METH_VARARGS,
     { NULL, NULL, 0, NULL }
 };
 
-void initmask(void)
+MODINIT_DEFINE (mask)
 {
-  PyObject *module, *dict, *apiobj;
-  static void* c_api[PYGAMEAPI_MASK_NUMSLOTS];
+    PyObject *module, *dict, *apiobj;
+    static void* c_api[PYGAMEAPI_MASK_NUMSLOTS];
 
-  /* imported needed apis; Do this first so if there is an error
-     the module is not loaded.
-  */
-  import_pygame_base ();
-  if (PyErr_Occurred ()) {
-    return;
-  } 
-  import_pygame_color ();
-  if (PyErr_Occurred ()) {
-    return;
-  }
-  import_pygame_surface ();
-  if (PyErr_Occurred ()) {
-    return;
-  }
-  import_pygame_rect ();
-  if (PyErr_Occurred ()) {
-    return;
-  }
+#if PY3
+    static struct PyModuleDef _module = {
+        PyModuleDef_HEAD_INIT,
+        "mask",
+        DOC_PYGAMEMASK,
+        -1,
+        _mask_methods,
+        NULL, NULL, NULL, NULL
+    };
+#endif
 
-  /* create the mask type */
-  PyType_Init(PyMask_Type);
+    /* imported needed apis; Do this first so if there is an error
+       the module is not loaded.
+    */
+    import_pygame_base ();
+    if (PyErr_Occurred ()) {
+        MODINIT_ERROR;
+    } 
+    import_pygame_color ();
+    if (PyErr_Occurred ()) {
+        MODINIT_ERROR;
+    }
+    import_pygame_surface ();
+    if (PyErr_Occurred ()) {
+        MODINIT_ERROR;
+    }
+    import_pygame_rect ();
+    if (PyErr_Occurred ()) {
+        MODINIT_ERROR;
+    }
 
-  /* create the module */
-  module = Py_InitModule3("mask", mask_builtins, DOC_PYGAMEMASK);
-  dict = PyModule_GetDict(module);
-  PyDict_SetItemString(dict, "MaskType", (PyObject *)&PyMask_Type);
+    /* create the mask type */
+    if (PyType_Ready (&PyMask_Type) < 0) {
+        MODINIT_ERROR;
+    }
 
-  /* export the c api */
-  Py_INCREF((PyObject*) &PyMask_Type);
-  c_api[0] = &PyMask_Type;
-  apiobj   = PyCObject_FromVoidPtr (c_api, NULL);
-  PyModule_AddObject (module, PYGAMEAPI_LOCAL_ENTRY, apiobj);
+    /* create the module */
+#if PY3
+    module = PyModule_Create (&_module);
+#else
+    module = Py_InitModule3("mask", _mask_methods, DOC_PYGAMEMASK);
+#endif
+    if (module == NULL) {
+        MODINIT_ERROR;
+    }
+    dict = PyModule_GetDict(module);
+    if (PyDict_SetItemString (dict, "MaskType",
+                              (PyObject *)&PyMask_Type) == -1) {
+        MODINIT_ERROR;
+    }
+    /* export the c api */
+    c_api[0] = &PyMask_Type;
+    apiobj = PyCObject_FromVoidPtr (c_api, NULL);
+    if (apiobj == NULL) {
+        DECREF_MOD (module);
+        MODINIT_ERROR;
+    }
+    if (PyModule_AddObject (module, PYGAMEAPI_LOCAL_ENTRY, apiobj) == -1) {
+        DECREF_MOD (module);
+        MODINIT_ERROR;
+    }
+    MODINIT_RETURN (module);
 }
 
     """random_mask(size=(100,100)): return Mask
     Create a mask of the given size, with roughly half the bits set at random."""
     m = pygame.Mask(size)
-    for i in range(size[0] * size[1] / 2):
+    for i in range(size[0] * size[1] // 2):
         x, y = random.randint(0,size[0] - 1), random.randint(0, size[1] - 1)
         m.set_at((x,y))
     return m
         surf = pygame.Surface((70,70), SRCALPHA, 32)
         #surf = surf.convert_alpha()
         surf.set_at((0,0), (255,255,255,0))
-        print surf.get_at((0,0))
+        print (surf.get_at((0,0)))
 
-        print "asdf"
-        print surf
+        print ("asdf")
+        print (surf)