def test_to_string__premultiplied(self): """ test to make sure we can export a surface to a premultiplied alpha string """ def convertRGBAtoPremultiplied(surface_to_modify): for x in xrange_(surface_to_modify.get_width()): for y in xrange_(surface_to_modify.get_height()): color = surface_to_modify.get_at((x, y)) premult_color = (color[0] * color[3] // 255, color[1] * color[3] // 255, color[2] * color[3] // 255, color[3]) surface_to_modify.set_at((x, y), premult_color) test_surface = pygame.Surface((256, 256), pygame.SRCALPHA, 32) for x in xrange_(test_surface.get_width()): for y in xrange_(test_surface.get_height()): i = x + y*test_surface.get_width() test_surface.set_at((x,y), ((i*7) % 256, (i*13) % 256, (i*27) % 256, y)) premultiplied_copy = test_surface.copy() convertRGBAtoPremultiplied(premultiplied_copy) self.assertPremultipliedAreEqual(pygame.image.tostring(test_surface, "RGBA_PREMULT"), pygame.image.tostring(premultiplied_copy, "RGBA"), pygame.image.tostring(test_surface, "RGBA")) self.assertPremultipliedAreEqual(pygame.image.tostring(test_surface, "ARGB_PREMULT"), pygame.image.tostring(premultiplied_copy, "ARGB"), pygame.image.tostring(test_surface, "ARGB")) no_alpha_surface = pygame.Surface((256, 256), 0, 24) self.assertRaises(ValueError, pygame.image.tostring, no_alpha_surface, "RGBA_PREMULT")
def AreSurfacesIdentical(surf_a, surf_b): if surf_a.get_width() != surf_b.get_width() or surf_a.get_height() != surf_b.get_height(): return False for y in xrange_(surf_a.get_height()): for x in xrange_(surf_b.get_width()): if surf_a.get_at((x,y)) != surf_b.get_at((x,y)): return False return True
def convertRGBAtoPremultiplied(surface_to_modify): for x in xrange_(surface_to_modify.get_width()): for y in xrange_(surface_to_modify.get_height()): color = surface_to_modify.get_at((x, y)) premult_color = (color[0] * color[3] // 255, color[1] * color[3] // 255, color[2] * color[3] // 255, color[3]) surface_to_modify.set_at((x, y), premult_color)
def equal_images(s1, s2): size = s1.get_size() if s2.get_size() != size: return False w, h = size for x in xrange_(w): for y in xrange_(h): if s1.get_at((x, y)) != s2.get_at((x, y)): return False return True
def vPlayer( fName ): global ovl f= open( fName, 'rb' ) fmt= f.readline().strip() res= f.readline().strip() col= f.readline().strip() if fmt!= "P5": print ('Unknown format( len %d ). Exiting...' % len( fmt )) return w,h= [ int(x) for x in res.split( ' ' ) ] h= ( h* 2 )/ 3 # Read into strings y= f.read( w*h ) u= [] v= [] for i in xrange_( 0, h/2 ): u.append( f.read( w/2 )) v.append( f.read( w/2 )) u= ''.join(u) v= ''.join(v) # Open overlay with the resolution specified ovl= pygame.Overlay(pygame.YV12_OVERLAY, (w,h)) ovl.set_location(0, 0, w, h) ovl.display((y,u,v)) while 1: pygame.time.wait(10) for ev in pygame.event.get(): if ev.type in (pygame.KEYDOWN, pygame.QUIT): return
def test_set_num_channels(self): mixer.init() for i in xrange_(1, mixer.get_num_channels() + 1): mixer.set_num_channels(i) self.assert_(mixer.get_num_channels() == i) mixer.quit()
def RotateARGBtoRGBA(str_buf): byte_buf = array.array("B", str_buf) num_quads = len(byte_buf)//4 for i in xrange_(num_quads): alpha = byte_buf[i*4 + 0] byte_buf[i*4 + 0] = byte_buf[i*4 + 1] byte_buf[i*4 + 1] = byte_buf[i*4 + 2] byte_buf[i*4 + 2] = byte_buf[i*4 + 3] byte_buf[i*4 + 3] = alpha return byte_buf.tostring()
def assertPremultipliedAreEqual(self, string1, string2, source_string): self.assertEqual(len(string1), len(string2)) block_size = 20 if string1 != string2: for block_start in xrange_(0, len(string1), block_size): block_end = min(block_start + block_size, len(string1)) block1 = string1[block_start:block_end] block2 = string2[block_start:block_end] if block1 != block2: source_block = source_string[block_start:block_end] msg = "string difference in %d to %d of %d:\n%s\n%s\nsource:\n%s" % (block_start, block_end, len(string1), block1.encode("hex"), block2.encode("hex"), source_block.encode("hex")) self.fail(msg)
def test_get_pixel (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): sf.set_at ((1, x), (0, 0, 11)) for x in xrange_ (10): sf.set_at ((x, 1), (0, 0, 11)) ar = pygame.PixelArray (sf) ar2 = ar.__getitem__ (0).__getitem__ (0) self.assertEqual (ar2, sf.map_rgb ((0, 0, 255))) ar2 = ar.__getitem__ (1).__getitem__ (0) self.assertEqual (ar2, sf.map_rgb ((0, 0, 11))) ar2 = ar.__getitem__ (-4).__getitem__ (1) self.assertEqual (ar2, sf.map_rgb ((0, 0, 11))) ar2 = ar.__getitem__ (-4).__getitem__ (5) self.assertEqual (ar2, sf.map_rgb ((0, 0, 255)))
def test_wait(self): # __doc__ (as of 2008-06-28) for pygame.threads.WorkerQueue.wait: # waits until all tasks are complete. wq = WorkerQueue() for i in xrange_(2000): wq.do(lambda x: x+1, i) wq.wait() self.assertRaises(Empty, wq.queue.get_nowait) wq.stop()
def setUp(self): pygame.display.init() self.screen = pygame.display.set_mode(screen_dims, flags) self.screen.fill([0,0,0]) pygame.display.flip() sprite_surface = pygame.image.load(os.path.join(data_dir, "asprite.bmp")) sprite_surface2 = pygame.image.load(os.path.join(data_dir, "static.png")) if use_rle: sprite_surface.set_colorkey([0xFF, 0xFF, 0xFF], SRCCOLORKEY|RLEACCEL) sprite_surface2.set_colorkey([0xFF, 0xFF, 0xFF], SRCCOLORKEY|RLEACCEL) else: sprite_surface.set_colorkey([0xFF, 0xFF, 0xFF], SRCCOLORKEY) sprite_surface2.set_colorkey([0xFF, 0xFF, 0xFF], SRCCOLORKEY) if use_alpha: sprite_surface = sprite_surface.convert_alpha() sprite_surface2 = sprite_surface2.convert_alpha() else: sprite_surface = sprite_surface.convert() sprite_surface2 = sprite_surface2.convert() Thingy.images = [sprite_surface] if use_static: Static.images = [sprite_surface2] self.sprites = None if use_FastRenderGroup: ## sprites = FRG.FastRenderGroup() self.sprites = FRG.LayeredDirty() else: if update_rects: self.sprites = pygame.sprite.RenderUpdates() else: self.sprites = pygame.sprite.Group() for i in xrange_(0, self.numsprites): if use_static and i%2==0: self.sprites.add(Static()) self.sprites.add(Thingy()) self.background = pygame.Surface(self.screen.get_size()) self.background = self.background.convert() self.background.fill([0,0,0])
def test_stop(self): # __doc__ (as of 2008-06-28) for pygame.threads.WorkerQueue.stop: # Stops the WorkerQueue, waits for all of the threads to finish up. # wq = WorkerQueue() self.assert_(len(wq.pool) > 0) for t in wq.pool: self.assert_(t.isAlive()) for i in xrange_(200): wq.do(lambda x: x+1, i) wq.stop() for t in wq.pool: self.assert_(not t.isAlive()) self.assert_(wq.queue.get() is STOP)
def test_tmap(self): # __doc__ (as of 2008-06-28) for pygame.threads.tmap: # like map, but uses a thread pool to execute. # num_workers - the number of worker threads that will be used. If pool # is passed in, then the num_workers arg is ignored. # worker_queue - you can optionally pass in an existing WorkerQueue. # wait - True means that the results are returned when everything is finished. # False means that we return the [worker_queue, results] right away instead. # results, is returned as a list of FuncResult instances. # stop_on_error - func, data = lambda x:x+1, xrange_(100) tmapped = list(tmap(func, data)) mapped = list(map(func, data)) self.assertEqual(tmapped, mapped)
def _clip_and_draw_line_width(surface, c_color, width, start, end): x0, y0 = start x1, y1 = end xinc = yinc = 0 if abs(x1 - x0) > abs(y1 - y0): yinc = 1 else: xinc = 1 # XXX: Instead of getting the minimum and maximum for each direction (which # we do here), pygame gets the minimum of the start coords and the # maximum of the end coords. I think we're right, but we should maybe # match what pygame does instead even though it's more of a pain to # implement. points = set() p0 = (x0, y0) p1 = (x1, y1) if _clip_and_draw_line(surface, c_color, p0, p1): points.update((p0, p1)) for i in xrange_(width // 2): p0 = (x0 + xinc * (i + 1), y0 + yinc * (i + 1)) p1 = (x1 + xinc * (i + 1), y1 + yinc * (i + 1)) if _clip_and_draw_line(surface, c_color, p0, p1): points.update((p0, p1)) # When the width is odd, we only draw the +xinc case # on the last pass through the loop if (2 * i + 2 < width): p0 = (x0 - xinc * (i + 1), y0 - yinc * (i + 1)) p1 = (x1 - xinc * (i + 1), y1 - yinc * (i + 1)) if _clip_and_draw_line(surface, c_color, p0, p1): points.update((p0, p1)) if points: # points would be empty if nothing was drawn return _make_drawn_rect(points, surface) return None
def test_get_pixel(self): w = 10 h = 20 size = w, h bg_color = (0, 0, 255) fg_color_y = (0, 0, 128) fg_color_x = (0, 0, 11) for bpp in (8, 16, 24, 32): sf = pygame.Surface(size, 0, bpp) mapped_bg_color = sf.map_rgb(bg_color) mapped_fg_color_y = sf.map_rgb(fg_color_y) mapped_fg_color_x = sf.map_rgb(fg_color_x) self.assertNotEqual(mapped_fg_color_y, mapped_bg_color, "Unusable test colors for bpp %i" % (bpp,)) self.assertNotEqual(mapped_fg_color_x, mapped_bg_color, "Unusable test colors for bpp %i" % (bpp,)) self.assertNotEqual(mapped_fg_color_y, mapped_fg_color_x, "Unusable test colors for bpp %i" % (bpp,)) sf.fill(bg_color) ar = pygame.PixelArray(sf) ar_y = ar.__getitem__(1) for y in xrange_(h): ar2 = ar_y.__getitem__(y) self.assertEqual( ar2, mapped_bg_color, "ar[1][%i] == %i, mapped_bg_color == %i" % (y, ar2, mapped_bg_color) ) sf.set_at((1, y), fg_color_y) ar2 = ar_y.__getitem__(y) self.assertEqual( ar2, mapped_fg_color_y, "ar[1][%i] == %i, mapped_fg_color_y == %i" % (y, ar2, mapped_fg_color_y) ) sf.set_at((1, 1), bg_color) for x in xrange_(w): ar2 = ar.__getitem__(x).__getitem__(1) self.assertEqual( ar2, mapped_bg_color, "ar[%i][1] = %i, mapped_bg_color = %i" % (x, ar2, mapped_bg_color) ) sf.set_at((x, 1), fg_color_x) ar2 = ar.__getitem__(x).__getitem__(1) self.assertEqual( ar2, mapped_fg_color_x, "ar[%i][1] = %i, mapped_fg_color_x = %i" % (x, ar2, mapped_fg_color_x) ) ar2 = ar.__getitem__(0).__getitem__(0) self.assertEqual(ar2, mapped_bg_color, "bpp = %i" % (bpp,)) ar2 = ar.__getitem__(1).__getitem__(0) self.assertEqual(ar2, mapped_fg_color_y, "bpp = %i" % (bpp,)) ar2 = ar.__getitem__(-4).__getitem__(1) self.assertEqual(ar2, mapped_fg_color_x, "bpp = %i" % (bpp,)) ar2 = ar.__getitem__(-4).__getitem__(5) self.assertEqual(ar2, mapped_bg_color, "bpp = %i" % (bpp,)) ar2 = ar.__getitem__(-4).__getitem__(0) self.assertEqual(ar2, mapped_bg_color, "bpp = %i" % (bpp,)) ar2 = ar.__getitem__(-w + 1).__getitem__(0) self.assertEqual(ar2, mapped_fg_color_y, "bpp = %i" % (bpp,)) ar2 = ar.__getitem__(-w).__getitem__(0) self.assertEqual(ar2, mapped_bg_color, "bpp = %i" % (bpp,)) ar2 = ar.__getitem__(5).__getitem__(-4) self.assertEqual(ar2, mapped_bg_color, "bpp = %i" % (bpp,)) ar2 = ar.__getitem__(5).__getitem__(-h + 1) self.assertEqual(ar2, mapped_fg_color_x, "bpp = %i" % (bpp,)) ar2 = ar.__getitem__(5).__getitem__(-h) self.assertEqual(ar2, mapped_bg_color, "bpp = %i" % (bpp,)) ar2 = ar.__getitem__(0).__getitem__(-h + 1) self.assertEqual(ar2, mapped_fg_color_x, "bpp = %i" % (bpp,)) ar2 = ar.__getitem__(0).__getitem__(-h) self.assertEqual(ar2, mapped_bg_color, "bpp = %i" % (bpp,))
def main(): pygame.init() pygame.display.set_mode((255, 255)) surface = pygame.Surface((255, 255)) pygame.display.flip() # Create the PixelArray. ar = pygame.PixelArray(surface) r, g, b = 0, 0, 0 # Do some easy gradient effect. for y in xrange_(255): r, g, b = y, y, y ar[:, y] = (r, g, b) del ar show(surface) # We have made some gradient effect, now flip it. ar = pygame.PixelArray(surface) ar[:] = ar[:, ::-1] del ar show(surface) # Every second column will be made blue ar = pygame.PixelArray(surface) ar[::2] = (0, 0, 255) del ar show(surface) # Every second row will be made green ar = pygame.PixelArray(surface) ar[:, ::2] = (0, 255, 0) del ar show(surface) # Manipulate the image. Flip it around the y axis. surface = pygame.image.load(os.path.join(data_dir, 'arraydemo.bmp')) ar = pygame.PixelArray(surface) ar[:] = ar[:, ::-1] del ar show(surface) # Flip the image around the x axis. ar = pygame.PixelArray(surface) ar[:] = ar[::-1, :] del ar show(surface) # Every second column will be made white. ar = pygame.PixelArray(surface) ar[::2] = (255, 255, 255) del ar show(surface) # Flip the image around both axes, restoring it's original layout. ar = pygame.PixelArray(surface) ar[:] = ar[::-1, ::-1] del ar show(surface) # Rotate 90 degrees clockwise. w, h = surface.get_size() surface2 = pygame.Surface((h, w), surface.get_flags(), surface) ar = pygame.PixelArray(surface) ar2 = pygame.PixelArray(surface2) ar2[...] = ar.transpose()[::-1, :] del ar, ar2 show(surface2) # Scale it by throwing each second pixel away. surface = pygame.image.load(os.path.join(data_dir, 'arraydemo.bmp')) ar = pygame.PixelArray(surface) sf2 = ar[::2, ::2].make_surface() del ar show(sf2) # Replace anything looking like the blue color from the text. ar = pygame.PixelArray(surface) ar.replace((60, 60, 255), (0, 255, 0), 0.06) del ar show(surface) # Extract anything which might be somewhat black. surface = pygame.image.load(os.path.join(data_dir, 'arraydemo.bmp')) ar = pygame.PixelArray(surface) ar2 = ar.extract((0, 0, 0), 0.07) sf2 = ar2.surface del ar, ar2 show(sf2) # Compare two images. surface = pygame.image.load(os.path.join(data_dir, 'alien1.gif')) surface2 = pygame.image.load(os.path.join(data_dir, 'alien2.gif')) ar1 = pygame.PixelArray(surface) ar2 = pygame.PixelArray(surface2) ar3 = ar1.compare(ar2, 0.07) sf3 = ar3.surface del ar1, ar2, ar3 show(sf3)
def initsysfonts_win32(): """initialize fonts dictionary on Windows""" fontdir = join(os.environ.get('WINDIR', 'C:\\Windows'), 'Fonts') TrueType_suffix = '(TrueType)' mods = ('demibold', 'narrow', 'light', 'unicode', 'bt', 'mt') fonts = {} # add fonts entered in the registry # find valid registry keys containing font information. # 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 sys.getwindowsversion()[0] == 1: key_name = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Fonts" else: key_name = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts" key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, key_name) for i in xrange_(_winreg.QueryInfoKey(key)[1]): try: # name is the font's name e.g. Times New Roman (TrueType) # font is the font's filename e.g. times.ttf name, font = _winreg.EnumValue(key, i)[0:2] except EnvironmentError: break # try to handle windows unicode strings for file names with # international characters if PY_MAJOR_VERSION < 3: # here are two documents with some information about it: # http://www.python.org/peps/pep-0277.html # https://www.microsoft.com/technet/archive/interopmigration/linux/mvc/lintowin.mspx#ECAA try: font = str(font) except UnicodeEncodeError: # MBCS is the windows encoding for unicode file names. try: font = font.encode('MBCS') except: # no success with str or MBCS encoding... skip this font. continue if splitext(font)[1].lower() not in OpenType_extensions: continue if not dirname(font): font = join(fontdir, font) if name.endswith(TrueType_suffix): name = name.rstrip(TrueType_suffix).rstrip() name = name.lower().split() bold = italic = 0 for m in mods: if m in name: name.remove(m) if 'bold' in name: name.remove('bold') bold = 1 if 'italic' in name: name.remove('italic') italic = 1 name = ''.join(name) name = _simplename(name) _addfont(name, bold, italic, font, fonts) return fonts
def main( update_rects=True, use_static=False, use_layered_dirty=False, screen_dims=[640, 480], use_alpha=False, flags=0, ): """Show lots of sprites moving around Optional keyword arguments: update_rects - use the RenderUpdate sprite group class (default True) use_static - include non-moving images (default False) use_layered_dirty - Use the FastRenderGroup sprite group (default False) screen_dims - Pygame window dimensions (default [640, 480]) use_alpha - use alpha blending (default False) flags - additional display mode flags (default no additional flags) """ if use_layered_dirty: update_rects = True # pg.init() pg.display.init() # if "-fast" in sys.argv: screen = pg.display.set_mode(screen_dims, flags) # this is mainly for GP2X, so it can quit. pg.joystick.init() num_joysticks = pg.joystick.get_count() if num_joysticks > 0: stick = pg.joystick.Joystick(0) stick.init() # now we will receive events for the joystick screen.fill([0, 0, 0]) pg.display.flip() sprite_surface = pg.image.load(os.path.join(data_dir, "asprite.bmp")) sprite_surface2 = pg.image.load(os.path.join(data_dir, "static.png")) if use_rle: sprite_surface.set_colorkey([0xFF, 0xFF, 0xFF], pg.SRCCOLORKEY | pg.RLEACCEL) sprite_surface2.set_colorkey([0xFF, 0xFF, 0xFF], pg.SRCCOLORKEY | pg.RLEACCEL) else: sprite_surface.set_colorkey([0xFF, 0xFF, 0xFF], pg.SRCCOLORKEY) sprite_surface2.set_colorkey([0xFF, 0xFF, 0xFF], pg.SRCCOLORKEY) if use_alpha: sprite_surface = sprite_surface.convert_alpha() sprite_surface2 = sprite_surface2.convert_alpha() else: sprite_surface = sprite_surface.convert() sprite_surface2 = sprite_surface2.convert() Thingy.images = [sprite_surface] if use_static: Static.images = [sprite_surface2] if len(sys.argv) > 1: try: numsprites = int(sys.argv[-1]) except Exception: numsprites = 100 else: numsprites = 100 sprites = None if use_layered_dirty: ## sprites = pg.sprite.FastRenderGroup() sprites = pg.sprite.LayeredDirty() else: if update_rects: sprites = pg.sprite.RenderUpdates() else: sprites = pg.sprite.Group() for i in xrange_(0, numsprites): if use_static and i % 2 == 0: sprites.add(Static()) sprites.add(Thingy()) frames = 0 start = time() background = pg.Surface(screen.get_size()) background = background.convert() background.fill([0, 0, 0]) going = True while going: if not update_rects: screen.fill([0, 0, 0]) ## for sprite in sprites: ## sprite.move() if update_rects: sprites.clear(screen, background) sprites.update() rects = sprites.draw(screen) if update_rects: pg.display.update(rects) else: pg.display.flip() for event in pg.event.get(): if event.type in [pg.QUIT, pg.KEYDOWN, pg.QUIT, pg.JOYBUTTONDOWN]: going = False frames += 1 end = time() print("FPS: %f" % (frames / ((end - start)))) pg.quit()
def test_fromstring__and_tostring(self): """Ensure methods tostring() and fromstring() are symmetric.""" #################################################################### def RotateRGBAtoARGB(str_buf): byte_buf = array.array("B", str_buf) num_quads = len(byte_buf) // 4 for i in xrange_(num_quads): alpha = byte_buf[i * 4 + 3] byte_buf[i * 4 + 3] = byte_buf[i * 4 + 2] byte_buf[i * 4 + 2] = byte_buf[i * 4 + 1] byte_buf[i * 4 + 1] = byte_buf[i * 4 + 0] byte_buf[i * 4 + 0] = alpha return tostring(byte_buf) #################################################################### def RotateARGBtoRGBA(str_buf): byte_buf = array.array("B", str_buf) num_quads = len(byte_buf) // 4 for i in xrange_(num_quads): alpha = byte_buf[i * 4 + 0] byte_buf[i * 4 + 0] = byte_buf[i * 4 + 1] byte_buf[i * 4 + 1] = byte_buf[i * 4 + 2] byte_buf[i * 4 + 2] = byte_buf[i * 4 + 3] byte_buf[i * 4 + 3] = alpha return tostring(byte_buf) #################################################################### test_surface = pygame.Surface((64, 256), flags=pygame.SRCALPHA, depth=32) for i in xrange_(256): for j in xrange_(16): intensity = j * 16 + 15 test_surface.set_at((j + 0, i), (intensity, i, i, i)) test_surface.set_at((j + 16, i), (i, intensity, i, i)) test_surface.set_at((j + 32, i), (i, i, intensity, i)) test_surface.set_at((j + 32, i), (i, i, i, intensity)) self._assertSurfaceEqual( test_surface, test_surface, "failing with identical surfaces" ) rgba_buf = pygame.image.tostring(test_surface, "RGBA") rgba_buf = RotateARGBtoRGBA(RotateRGBAtoARGB(rgba_buf)) test_rotate_functions = pygame.image.fromstring( rgba_buf, test_surface.get_size(), "RGBA" ) self._assertSurfaceEqual( test_surface, test_rotate_functions, "rotate functions are not symmetric" ) rgba_buf = pygame.image.tostring(test_surface, "RGBA") argb_buf = RotateRGBAtoARGB(rgba_buf) test_from_argb_string = pygame.image.fromstring( argb_buf, test_surface.get_size(), "ARGB" ) self._assertSurfaceEqual( test_surface, test_from_argb_string, '"RGBA" rotated to "ARGB" failed' ) argb_buf = pygame.image.tostring(test_surface, "ARGB") rgba_buf = RotateARGBtoRGBA(argb_buf) test_to_argb_string = pygame.image.fromstring( rgba_buf, test_surface.get_size(), "RGBA" ) self._assertSurfaceEqual( test_surface, test_to_argb_string, '"ARGB" rotated to "RGBA" failed' ) for fmt in ("ARGB", "RGBA"): fmt_buf = pygame.image.tostring(test_surface, fmt) test_to_from_fmt_string = pygame.image.fromstring( fmt_buf, test_surface.get_size(), fmt ) self._assertSurfaceEqual( test_surface, test_to_from_fmt_string, "tostring/fromstring functions are not " 'symmetric with "{}" format'.format(fmt), )
def test_xrange_(self): self.failIf(isinstance(compat.xrange_(2), list))
def test_xrange_(self): self.assertFalse(isinstance(compat.xrange_(2), list))
def main(): pygame.init () pygame.display.set_mode ((255, 255)) surface = pygame.Surface ((255, 255)) pygame.display.flip () # Create the PixelArray. ar = pygame.PixelArray (surface) r, g, b = 0, 0, 0 # Do some easy gradient effect. for y in xrange_ (255): r, g, b = y, y, y ar[:,y] = (r, g, b) del ar show (surface) # We have made some gradient effect, now flip it. ar = pygame.PixelArray (surface) ar[:] = ar[:,::-1] del ar show (surface) # Every second column will be made blue ar = pygame.PixelArray (surface) ar[::2] = (0, 0, 255) del ar show (surface) # Every second row will be made green ar = pygame.PixelArray (surface) ar[:,::2] = (0, 255, 0) del ar show (surface) # Manipulate the image. Flip it around the y axis. surface = pygame.image.load (os.path.join (data_dir, 'arraydemo.bmp')) ar = pygame.PixelArray (surface) ar[:] = ar[:,::-1] del ar show (surface) # Flip the image around the x axis. ar = pygame.PixelArray (surface) ar[:] = ar[::-1,:] del ar show (surface) # Every second column will be made white. ar = pygame.PixelArray (surface) ar[::2] = (255, 255, 255) del ar show (surface) # Flip the image around both axes, restoring it's original layout. ar = pygame.PixelArray (surface) ar[:] = ar[::-1,::-1] del ar show (surface) # Scale it by throwing each second pixel away. surface = pygame.image.load (os.path.join (data_dir, 'arraydemo.bmp')) ar = pygame.PixelArray (surface) sf2 = ar[::2,::2].make_surface () del ar show (sf2) # Replace anything looking like the blue color from the text. ar = pygame.PixelArray (surface) ar.replace ((60, 60, 255), (0, 255, 0), 0.06) del ar show (surface) # Extract anything which might be somewhat black. surface = pygame.image.load (os.path.join (data_dir, 'arraydemo.bmp')) ar = pygame.PixelArray (surface) ar2 = ar.extract ((0, 0, 0), 0.07) sf2 = ar2.surface del ar, ar2 show (sf2) # Compare two images. surface = pygame.image.load (os.path.join (data_dir, 'alien1.gif')) surface2 = pygame.image.load (os.path.join (data_dir, 'alien2.gif')) ar1 = pygame.PixelArray (surface) ar2 = pygame.PixelArray (surface2) ar3 = ar1.compare (ar2, 0.07) sf3 = ar3.surface del ar1, ar2, ar3 show (sf3)
def test_get_pixel(self): w = 10 h = 20 size = w, h bg_color = (0, 0, 255) fg_color_y = (0, 0, 128) fg_color_x = (0, 0, 11) for bpp in (8, 16, 24, 32): sf = pygame.Surface(size, 0, bpp) mapped_bg_color = sf.map_rgb(bg_color) mapped_fg_color_y = sf.map_rgb(fg_color_y) mapped_fg_color_x = sf.map_rgb(fg_color_x) self.assertNotEqual(mapped_fg_color_y, mapped_bg_color, "Unusable test colors for bpp %i" % (bpp, )) self.assertNotEqual(mapped_fg_color_x, mapped_bg_color, "Unusable test colors for bpp %i" % (bpp, )) self.assertNotEqual(mapped_fg_color_y, mapped_fg_color_x, "Unusable test colors for bpp %i" % (bpp, )) sf.fill(bg_color) ar = pygame.PixelArray(sf) ar_y = ar.__getitem__(1) for y in xrange_(h): ar2 = ar_y.__getitem__(y) self.assertEqual( ar2, mapped_bg_color, "ar[1][%i] == %i, mapped_bg_color == %i" % (y, ar2, mapped_bg_color)) sf.set_at((1, y), fg_color_y) ar2 = ar_y.__getitem__(y) self.assertEqual( ar2, mapped_fg_color_y, "ar[1][%i] == %i, mapped_fg_color_y == %i" % (y, ar2, mapped_fg_color_y)) sf.set_at((1, 1), bg_color) for x in xrange_(w): ar2 = ar.__getitem__(x).__getitem__(1) self.assertEqual( ar2, mapped_bg_color, "ar[%i][1] = %i, mapped_bg_color = %i" % (x, ar2, mapped_bg_color)) sf.set_at((x, 1), fg_color_x) ar2 = ar.__getitem__(x).__getitem__(1) self.assertEqual( ar2, mapped_fg_color_x, "ar[%i][1] = %i, mapped_fg_color_x = %i" % (x, ar2, mapped_fg_color_x)) ar2 = ar.__getitem__(0).__getitem__(0) self.assertEqual(ar2, mapped_bg_color, "bpp = %i" % (bpp, )) ar2 = ar.__getitem__(1).__getitem__(0) self.assertEqual(ar2, mapped_fg_color_y, "bpp = %i" % (bpp, )) ar2 = ar.__getitem__(-4).__getitem__(1) self.assertEqual(ar2, mapped_fg_color_x, "bpp = %i" % (bpp, )) ar2 = ar.__getitem__(-4).__getitem__(5) self.assertEqual(ar2, mapped_bg_color, "bpp = %i" % (bpp, )) ar2 = ar.__getitem__(-4).__getitem__(0) self.assertEqual(ar2, mapped_bg_color, "bpp = %i" % (bpp, )) ar2 = ar.__getitem__(-w + 1).__getitem__(0) self.assertEqual(ar2, mapped_fg_color_y, "bpp = %i" % (bpp, )) ar2 = ar.__getitem__(-w).__getitem__(0) self.assertEqual(ar2, mapped_bg_color, "bpp = %i" % (bpp, )) ar2 = ar.__getitem__(5).__getitem__(-4) self.assertEqual(ar2, mapped_bg_color, "bpp = %i" % (bpp, )) ar2 = ar.__getitem__(5).__getitem__(-h + 1) self.assertEqual(ar2, mapped_fg_color_x, "bpp = %i" % (bpp, )) ar2 = ar.__getitem__(5).__getitem__(-h) self.assertEqual(ar2, mapped_bg_color, "bpp = %i" % (bpp, )) ar2 = ar.__getitem__(0).__getitem__(-h + 1) self.assertEqual(ar2, mapped_fg_color_x, "bpp = %i" % (bpp, )) ar2 = ar.__getitem__(0).__getitem__(-h) self.assertEqual(ar2, mapped_bg_color, "bpp = %i" % (bpp, ))
def main( update_rects=True, use_static=False, use_FastRenderGroup=False, screen_dims=[640, 480], use_alpha=False, flags=0, plot=False, ): """Show lots of sprites moving around Optional keyword arguments: update_rects - use the RenderUpdate sprite group class (default True) use_static - include non-moving images (default False) use_FastRenderGroup - Use the FastRenderGroup sprite group (default False) screen_dims - Pygame window dimensions (default [640, 480]) use_alpha - use alpha blending (default False) flags - additional display mode flags (default no addiontal flags) """ global jit_on if use_FastRenderGroup: update_rects = True # pygame.init() pygame.display.init() # if "-fast" in sys.argv: screen = pygame.display.set_mode(screen_dims, flags) # this is mainly for GP2X, so it can quit. pygame.joystick.init() num_joysticks = pygame.joystick.get_count() if num_joysticks > 0: stick = pygame.joystick.Joystick(0) stick.init() # now we will receive events for the joystick screen.fill([0, 0, 0]) pygame.display.flip() sprite_surface = pygame.image.load(os.path.join(data_dir, "asprite.bmp")) sprite_surface2 = pygame.image.load(os.path.join(data_dir, "static.png")) if use_rle: sprite_surface.set_colorkey([0xFF, 0xFF, 0xFF], SRCCOLORKEY | RLEACCEL) sprite_surface2.set_colorkey([0xFF, 0xFF, 0xFF], SRCCOLORKEY | RLEACCEL) else: sprite_surface.set_colorkey([0xFF, 0xFF, 0xFF], SRCCOLORKEY) sprite_surface2.set_colorkey([0xFF, 0xFF, 0xFF], SRCCOLORKEY) if use_alpha: sprite_surface = sprite_surface.convert_alpha() sprite_surface2 = sprite_surface2.convert_alpha() else: sprite_surface = sprite_surface.convert() sprite_surface2 = sprite_surface2.convert() Thingy.images = [sprite_surface] if use_static: Static.images = [sprite_surface2] if len(sys.argv) > 1: try: numsprites = int(sys.argv[-1]) except Exception: numsprites = 100 else: numsprites = 100 sprites = None if use_FastRenderGroup: ## sprites = FRG.FastRenderGroup() sprites = FRG.LayeredDirty() else: if update_rects: sprites = pygame.sprite.RenderUpdates() else: sprites = pygame.sprite.Group() for i in xrange_(0, numsprites): if use_static and i % 2 == 0: sprites.add(Static()) sprites.add(Thingy()) done = False frames = 0 start = time() background = pygame.Surface(screen.get_size()) background = background.convert() background.fill([0, 0, 0]) frame_times = [] gc.disable() frames_since_last_gc = 0 while not done: # print('1) at top of loop') t0 = time() for event in pygame.event.get(): if event.type in [KEYDOWN, QUIT, JOYBUTTONDOWN]: done = True if not update_rects: screen.fill([0, 0, 0]) ## for sprite in sprites: ## sprite.move() if update_rects: sprites.clear(screen, background) sprites.update() rects = sprites.draw(screen) t1 = time() # print (t1-t0) # gc.collect(0) if t1 - t0 > 0.011: print("slow") # print('frame') # if (t1-t0 < 0.0011 and frames_since_last_gc > 30): # print('2) tell GC thread to collect') # gc_queue.put(True) gc_event.set() # gc.collect_step() # if frames_since_last_gc > 0: # # print('collecting') # frames_since_last_gc = 0 # # gc.collect(0) # # gc.collect_step() # print('put on queue') # gc_queue.put(True) # else: # frames_since_last_gc += 1 # print ('3) flipping display. GIL released') if update_rects: pygame.display.update(rects) else: pygame.display.flip() # print ('6) finished flipping. GIL grabbed') # frame_times.append(time() - t0) frame_times.append(t1 - t0) if jit_on and time() - start > 10: # print('turning off pypyjit') # pypyjit.set_param("off") jit_on = 0 frames += 1 end = time() print("FPS: %f" % (frames / ((end - start)))) pygame.quit() if plot: msg = "\n".join(( "update_rects:%s,", "use_static:%s,", "use_FastRenderGroup:%s", "screen_dims:%s,", "use_alpha:%s,", "flags: %s", )) % ( update_rects, use_static, use_FastRenderGroup, screen_dims, use_alpha, flags, ) print(msg) import pickle with open("spriteplot.pickle", "wb") as picklef: pickle.dump({"msg": msg, "frame_times": frame_times}, picklef)
def main(update_rects = True, use_static = False, use_FastRenderGroup = False, screen_dims = [640, 480], use_alpha = False, flags = 0, ): """Show lots of sprites moving around Optional keyword arguments: update_rects - use the RenderUpdate sprite group class (default True) use_static - include non-moving images (default False) use_FastRenderGroup - Use the FastRenderGroup sprite group (default False) screen_dims - Pygame window dimensions (default [640, 480]) use_alpha - use alpha blending (default False) flags - additional display mode flags (default no addiontal flags) """ if use_FastRenderGroup: update_rects = True #pygame.init() pygame.display.init() #if "-fast" in sys.argv: screen = pygame.display.set_mode(screen_dims, flags) # this is mainly for GP2X, so it can quit. pygame.joystick.init() num_joysticks = pygame.joystick.get_count() if num_joysticks > 0: stick = pygame.joystick.Joystick(0) stick.init() # now we will receive events for the joystick screen.fill([0,0,0]) pygame.display.flip() sprite_surface = pygame.image.load(os.path.join(data_dir, "asprite.bmp")) sprite_surface2 = pygame.image.load(os.path.join(data_dir, "static.png")) if use_rle: sprite_surface.set_colorkey([0xFF, 0xFF, 0xFF], SRCCOLORKEY|RLEACCEL) sprite_surface2.set_colorkey([0xFF, 0xFF, 0xFF], SRCCOLORKEY|RLEACCEL) else: sprite_surface.set_colorkey([0xFF, 0xFF, 0xFF], SRCCOLORKEY) sprite_surface2.set_colorkey([0xFF, 0xFF, 0xFF], SRCCOLORKEY) if use_alpha: sprite_surface = sprite_surface.convert_alpha() sprite_surface2 = sprite_surface2.convert_alpha() else: sprite_surface = sprite_surface.convert() sprite_surface2 = sprite_surface2.convert() Thingy.images = [sprite_surface] if use_static: Static.images = [sprite_surface2] if len(sys.argv) > 1: try: numsprites = int(sys.argv[-1]) except Exception: numsprites = 100 else: numsprites = 100 sprites = None if use_FastRenderGroup: ## sprites = FRG.FastRenderGroup() sprites = FRG.LayeredDirty() else: if update_rects: sprites = pygame.sprite.RenderUpdates() else: sprites = pygame.sprite.Group() for i in xrange_(0, numsprites): if use_static and i%2==0: sprites.add(Static()) sprites.add(Thingy()) done = False frames = 0 start = time() background = pygame.Surface(screen.get_size()) background = background.convert() background.fill([0,0,0]) while not done: if not update_rects: screen.fill([0,0,0]) ## for sprite in sprites: ## sprite.move() if update_rects: sprites.clear(screen, background) sprites.update() rects = sprites.draw(screen) if update_rects: pygame.display.update(rects) else: pygame.display.flip() for event in pygame.event.get(): if event.type in [KEYDOWN, QUIT, JOYBUTTONDOWN]: done = True frames += 1 end = time() print ("FPS: %f" % (frames / ((end - start)))) pygame.quit()
def test_fromstring__and_tostring(self): """ see if fromstring, and tostring methods are symmetric. """ def AreSurfacesIdentical(surf_a, surf_b): if surf_a.get_width() != surf_b.get_width() or surf_a.get_height() != surf_b.get_height(): return False for y in xrange_(surf_a.get_height()): for x in xrange_(surf_b.get_width()): if surf_a.get_at((x,y)) != surf_b.get_at((x,y)): return False return True #################################################################### def RotateRGBAtoARGB(str_buf): byte_buf = array.array("B", str_buf) num_quads = len(byte_buf)//4 for i in xrange_(num_quads): alpha = byte_buf[i*4 + 3] byte_buf[i*4 + 3] = byte_buf[i*4 + 2] byte_buf[i*4 + 2] = byte_buf[i*4 + 1] byte_buf[i*4 + 1] = byte_buf[i*4 + 0] byte_buf[i*4 + 0] = alpha return byte_buf.tostring() #################################################################### def RotateARGBtoRGBA(str_buf): byte_buf = array.array("B", str_buf) num_quads = len(byte_buf)//4 for i in xrange_(num_quads): alpha = byte_buf[i*4 + 0] byte_buf[i*4 + 0] = byte_buf[i*4 + 1] byte_buf[i*4 + 1] = byte_buf[i*4 + 2] byte_buf[i*4 + 2] = byte_buf[i*4 + 3] byte_buf[i*4 + 3] = alpha return byte_buf.tostring() #################################################################### test_surface = pygame.Surface((64, 256), flags=pygame.SRCALPHA, depth=32) for i in xrange_(256): for j in xrange_(16): intensity = j*16 + 15 test_surface.set_at((j + 0, i), (intensity, i, i, i)) test_surface.set_at((j + 16, i), (i, intensity, i, i)) test_surface.set_at((j + 32, i), (i, i, intensity, i)) test_surface.set_at((j + 32, i), (i, i, i, intensity)) self.assert_(AreSurfacesIdentical(test_surface, test_surface)) rgba_buf = pygame.image.tostring(test_surface, "RGBA") rgba_buf = RotateARGBtoRGBA(RotateRGBAtoARGB(rgba_buf)) test_rotate_functions = pygame.image.fromstring(rgba_buf, test_surface.get_size(), "RGBA") self.assert_(AreSurfacesIdentical(test_surface, test_rotate_functions)) rgba_buf = pygame.image.tostring(test_surface, "RGBA") argb_buf = RotateRGBAtoARGB(rgba_buf) test_from_argb_string = pygame.image.fromstring(argb_buf, test_surface.get_size(), "ARGB") self.assert_(AreSurfacesIdentical(test_surface, test_from_argb_string)) #"ERROR: image.fromstring with ARGB failed" argb_buf = pygame.image.tostring(test_surface, "ARGB") rgba_buf = RotateARGBtoRGBA(argb_buf) test_to_argb_string = pygame.image.fromstring(rgba_buf, test_surface.get_size(), "RGBA") self.assert_(AreSurfacesIdentical(test_surface, test_to_argb_string)) #"ERROR: image.tostring with ARGB failed" argb_buf = pygame.image.tostring(test_surface, "ARGB") test_to_from_argb_string = pygame.image.fromstring(argb_buf, test_surface.get_size(), "ARGB") self.assert_(AreSurfacesIdentical(test_surface, test_to_from_argb_string))