Python pygame 模块,Surface() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pygame.Surface()

项目:sc8pr    作者:dmaccarthy    | 项目源码 | 文件源码
def style(srf, bg=None, border=(0,0,0), weight=0, padding=0):
    "Create a new surface with padding, background color, and/or border"
    w, h = srf.get_size()

    # Add padding
    padding += weight
    w += 2 * padding
    h += 2 * padding
    img = pygame.Surface((w, h), pygame.SRCALPHA)

    # Add background color and border
    if bg: img.fill(rgba(bg))
    img.blit(srf, (padding, padding))
    if weight: drawBorder(img, border, weight)

    return img
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def render(self, text, antialias, forecolor, backcolor=(0,0,0,255)):
        size = self.size(text)
        img = NSImage.alloc().initWithSize_(size)
        img.lockFocus()

        NSString.drawAtPoint_withAttributes_(text, (0.0, 0.0), {
            NSFontAttributeName: self._font,
            NSUnderlineStyleAttributeName: self._isUnderline and 1.0 or None,
            NSBackgroundColorAttributeName: backcolor and _getColor(backcolor) or None,
            NSForegroundColorAttributeName: _getColor(forecolor),
        })

        rep = NSBitmapImageRep.alloc().initWithFocusedViewRect_(((0.0, 0.0), size))
        img.unlockFocus()
        if rep.samplesPerPixel() == 4:
            s = Surface(size, SRCALPHA|SWSURFACE, 32, [-1<<24,0xff<<16,0xff<<8,0xff])

            a = Numeric.reshape(Numeric.fromstring(rep.bitmapData(), typecode=Numeric.Int32), (size[1], size[0]))
            blit_array(s, Numeric.swapaxes(a,0,1))
            return s.convert_alpha()
项目:sappho    作者:lily-mayfield    | 项目源码 | 文件源码
def create_surface_layers(target_surface, number_of_layers):
        """Create a list of pygame surfaces
        the size of the target surface.

        Arguments:
            target_surface (pygame.Surface): The surface
                whose dimensions will be used for each layer.
            number_of_layers (int): The number of surfaces to
                create/return.

        Returns:
            list[pygame.Surface]: List of surfaces

        """

        surface_layers = []

        for i in range(number_of_layers):
            surface = pygame.surface.Surface(target_surface.get_size(),
                                             pygame.SRCALPHA, 32)
            surface_layers.append(surface)

        return surface_layers
项目:sappho    作者:lily-mayfield    | 项目源码 | 文件源码
def __getitem__(self, key):
        """Access a surface by z-index.

        Arguments:
            key (int): The z-index of the surface.

        Raises:
            IndexError: When the z-index is invalid.

        Returns:
            pygame.Surface: The surface belonging
                to the z-index specified.

        """

        return self._surface_layers[key]
项目:simple_rl    作者:david-abel    | 项目源码 | 文件源码
def _draw_title_text(mdp, screen):
    '''
    Args:
        mdp (simple_rl.MDP)
        screen (pygame.Surface)

    Summary:
        Draws the name of the MDP to the top of the screen.
    '''
    scr_width, scr_height = screen.get_width(), screen.get_height()
    title_split = str(mdp).split("_")
    title = title_split[0]
    param_text = " ("
    for param in title_split[1:-1]:
        param_text += param + ", "
    param_text += title_split[-1] + ")"
    formatted_title_text = title[0].upper() + title[1:] + param_text
    title_text = title_font.render(formatted_title_text, True, (46, 49, 49))
    screen.blit(title_text, (scr_width / 2.0 - len(formatted_title_text)*6, scr_width / 20.0))
项目:simple_rl    作者:david-abel    | 项目源码 | 文件源码
def _draw_state_text(state, screen):
    '''
    Args:
        state (simple_rl.State)
        screen (pygame.Surface)

    Summary:
        Draws the name of the current state to the bottom left of the screen.
    '''
    scr_width, scr_height = screen.get_width(), screen.get_height()
    # Clear.
    formatted_state_text = str(state)
    if len(formatted_state_text) > 20:
        # State text is too long, ignore.
        return
    state_text_point = (scr_width / 4.0 - len(formatted_state_text)*6, 18*scr_height / 20.0)
    pygame.draw.rect(screen, (255,255,255), (state_text_point[0] - 20, state_text_point[1]) + (200,40))
    state_text = title_font.render(formatted_state_text, True, (46, 49, 49))
    screen.blit(state_text, state_text_point)
项目:simple_rl    作者:david-abel    | 项目源码 | 文件源码
def _draw_agent(center_point, screen, base_size=30):
    '''
    Args:
        center_point (tuple): (x,y)
        screen (pygame.Surface)

    Returns:
        (pygame.rect)
    '''
    # taxi_image = pygame.image.load("taxi.png")
    # image_rect = taxi_image.get_rect()

    tri_bot_left = center_point[0] - base_size, center_point[1] + base_size
    tri_bot_right = center_point[0] + base_size, center_point[1] + base_size
    tri_top = center_point[0], center_point[1] - base_size
    tri = [tri_bot_left, tri_top, tri_bot_right]
    tri_color = (98, 140, 190)
    # screen.blit(taxi_image, image_rect)
    # return image_rect
    return pygame.draw.polygon(screen, tri_color, tri)
项目:sc8pr    作者:dmaccarthy    | 项目源码 | 文件源码
def __init__(self, srf, bg=None, decompress=zlib.decompress):
        if hasattr(srf, "image"): srf = srf.image
        t = type(srf)
        if t is str:
            srf = pygame.image.load(srf)
            if bg: srf = style(srf, bg)
            elif not hasAlpha(srf): srf = srf.convert_alpha()
        elif t is bytes:
            mode, w, h = struct.unpack("!3I", bg)
            if mode & 2: srf = decompress(srf)
            mode = "RGBA" if mode & 1 else "RGB"
            srf = pygame.image.fromstring(srf, (w,h), mode)
        elif t in (list, tuple):
            srf = pygame.Surface(srf, pygame.SRCALPHA)
            if bg: srf.fill(bg if type(bg) is pygame.Color else rgba(bg))
        self.original = srf
        self.dumpCache()
项目:sc8pr    作者:dmaccarthy    | 项目源码 | 文件源码
def snapshot(self):
        "Capture the canvas as an Image instance"
        srf = pygame.Surface(self.size, pygame.SRCALPHA)

        # Draw background
        if isinstance(self._bg, Image):
            self._bg.config(size=self._size)
            srf.blit(self._bg.image, (0,0))
        elif self._bg: srf.fill(self._bg)

        # Draw objects
        for g in self:
            if g.snapshot is not None:
                xy = g.blitPosition((0,0), g.size)
                srf.blit(g.snapshot().image, xy)
            else: g.draw(srf, snapshot=True)

        # Draw border
        if self.weight: drawBorder(srf, self.border, self.weight)
        return Image(srf)
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def main():
    pygame.init()
    screen = pygame.display.set_mode((500,500))
    screen.fill((255, 0, 0))
    s = pygame.Surface(screen.get_size(), pygame.SRCALPHA, 32)
    pygame.draw.line(s, (0,0,0), (250, 250), (250+200,250))

    width = 1
    for a_radius in range(width):
        radius = 200
        pygame.gfxdraw.aacircle(s, 250, 250, radius-a_radius, (0, 0, 0))

    screen.blit(s, (0, 0))
    pygame.display.flip()
    try:
        while 1:
            event = pygame.event.wait()
            if event.type == pygame.QUIT:
                break
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE or event.unicode == 'q':
                    break
            pygame.display.flip()
    finally:
        pygame.quit()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def surfdemo_show(array_img, name):
    "displays a surface, waits for user to continue"
    screen = pygame.display.set_mode(array_img.shape[:2], 0, 32)
    surfarray.blit_array(screen, array_img)
    pygame.display.flip()
    pygame.display.set_caption(name)
    while 1:
        e = pygame.event.wait()
        if e.type == MOUSEBUTTONDOWN: break
        elif e.type == KEYDOWN and e.key == K_s:
            #pygame.image.save(screen, name+'.bmp')
            #s = pygame.Surface(screen.get_size(), 0, 32)
            #s = s.convert_alpha()
            #s.fill((0,0,0,255))
            #s.blit(screen, (0,0))
            #s.fill((222,0,0,50), (0,0,40,40))
            #pygame.image.save_extended(s, name+'.png')
            #pygame.image.save(s, name+'.png')
            #pygame.image.save(screen, name+'_screen.png')
            #pygame.image.save(s, name+'.tga')
            pygame.image.save(screen, name+'.png')
        elif e.type == QUIT:
            raise SystemExit()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_rect__one_pixel_lines(self):
        # __doc__ (as of 2008-06-25) for pygame.draw.rect:

          # pygame.draw.rect(Surface, color, Rect, width=0): return Rect
          # draw a rectangle shape
        rect = pygame.Rect(10, 10, 56, 20)

        drawn = draw.rect(self.surf, self.color, rect, 1)
        self.assert_(drawn == rect)

        #Should be colored where it's supposed to be
        for pt in test_utils.rect_perimeter_pts(drawn):
            color_at_pt = self.surf.get_at(pt)
            self.assert_(color_at_pt == self.color)

        #And not where it shouldn't
        for pt in test_utils.rect_outer_bounds(drawn):
            color_at_pt = self.surf.get_at(pt)
            self.assert_(color_at_pt != self.color)
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def todo_test_arc(self):

        # __doc__ (as of 2008-08-02) for pygame.draw.arc:

          # pygame.draw.arc(Surface, color, Rect, start_angle, stop_angle,
          # width=1): return Rect
          # 
          # draw a partial section of an ellipse
          # 
          # Draws an elliptical arc on the Surface. The rect argument is the
          # area that the ellipse will fill. The two angle arguments are the
          # initial and final angle in radians, with the zero on the right. The
          # width argument is the thickness to draw the outer edge.
          # 

        self.fail()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def todo_test_lines(self):

        # __doc__ (as of 2008-08-02) for pygame.draw.lines:

          # pygame.draw.lines(Surface, color, closed, pointlist, width=1): return Rect
          # draw multiple contiguous line segments
          # 
          # Draw a sequence of lines on a Surface. The pointlist argument is a
          # series of points that are connected by a line. If the closed
          # argument is true an additional line segment is drawn between the
          # first and last points.
          # 
          # This does not draw any endcaps or miter joints. Lines with sharp
          # corners and wide line widths can have improper looking corners.
          # 

        self.fail()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def todo_test_polygon(self):

        # __doc__ (as of 2008-08-02) for pygame.draw.polygon:

          # pygame.draw.polygon(Surface, color, pointlist, width=0): return Rect
          # draw a shape with any number of sides
          # 
          # Draws a polygonal shape on the Surface. The pointlist argument is
          # the vertices of the polygon. The width argument is the thickness to
          # draw the outer edge. If width is zero then the polygon will be
          # filled.
          # 
          # For aapolygon, use aalines with the 'closed' parameter. 

        self.fail() 

################################################################################
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_scale__destination( self ):
        """ see if the destination surface can be passed in to use.
        """

        s = pygame.Surface((32,32))
        s2 = pygame.transform.scale(s, (64,64))
        s3 = s2.copy()

        s3 = pygame.transform.scale(s, (64,64), s3)
        pygame.transform.scale(s, (64,64), s2)

        # the wrong size surface is past in.  Should raise an error.
        self.assertRaises(ValueError, pygame.transform.scale, s, (33,64), s3)

        if 1:
            s = pygame.Surface((32,32))
            s2 = pygame.transform.smoothscale(s, (64,64))
            s3 = s2.copy()

            s3 = pygame.transform.smoothscale(s, (64,64), s3)
            pygame.transform.smoothscale(s, (64,64), s2)

            # the wrong size surface is past in.  Should raise an error.
            self.assertRaises(ValueError, pygame.transform.smoothscale, s, (33,64), s3)
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_average_surfaces__24(self):

        SIZE = 32
        depth = 24
        s1 = pygame.Surface((SIZE, SIZE), 0, depth)
        s2 = pygame.Surface((SIZE, SIZE), 0, depth)
        s3 = pygame.Surface((SIZE, SIZE), 0, depth)
        s1.fill((10,10,70, 255))
        s2.fill((10,20,70, 255))
        s3.fill((10,130,10, 255))

        surfaces = [s1, s2, s3]
        sr = pygame.transform.average_surfaces(surfaces)
        self.assertEqual( sr.get_masks(), s1.get_masks() )
        self.assertEqual( sr.get_flags(), s1.get_flags() )
        self.assertEqual( sr.get_losses(), s1.get_losses() )

        if 0:
            print ( sr, s1 )
            print ( sr.get_masks(), s1.get_masks() )
            print ( sr.get_flags(), s1.get_flags() )
            print ( sr.get_losses(), s1.get_losses() )
            print ( sr.get_shifts(), s1.get_shifts() )

        self.assertEqual(sr.get_at((0,0)), (10,53,50,255))
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def todo_test_chop(self):

        # __doc__ (as of 2008-08-02) for pygame.transform.chop:

          # pygame.transform.chop(Surface, rect): return Surface
          # gets a copy of an image with an interior area removed
          #
          # Extracts a portion of an image. All vertical and horizontal pixels
          # surrounding the given rectangle area are removed. The corner areas
          # (diagonal to the rect) are then brought together. (The original
          # image is not altered by this operation.)
          #
          # NOTE: If you want a "crop" that returns the part of an image within
          # a rect, you can blit with a rect to a new surface or copy a
          # subsurface.

        self.fail()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def setUp(self):
        self.ag = sprite.AbstractGroup()
        self.ag2 = sprite.AbstractGroup()
        self.s1 = sprite.Sprite(self.ag)
        self.s2 = sprite.Sprite(self.ag2)
        self.s3 = sprite.Sprite(self.ag2)

        self.s1.image = pygame.Surface((50,10), pygame.SRCALPHA, 32)
        self.s2.image = pygame.Surface((10,10), pygame.SRCALPHA, 32)
        self.s3.image = pygame.Surface((10,10), pygame.SRCALPHA, 32)

        self.s1.rect = self.s1.image.get_rect()
        self.s2.rect = self.s2.image.get_rect()
        self.s3.rect = self.s3.image.get_rect()
        self.s2.rect.move_ip(40, 0)
        self.s3.rect.move_ip(100, 100)
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def iter_surface_to_array_3d(self, rgba_masks):
        dst = pygame.Surface(self.surf_size, 0, 24, masks=rgba_masks)

        for surf in self.sources:
            dst.fill((0, 0, 0, 0))
            src_bitsize = surf.get_bitsize()
            view = dst.get_view('3')
            self.assertFalse(surf.get_locked())
            surface_to_array(view, surf)
            self.assertFalse(surf.get_locked())
            for posn, i in self.test_points:
                sc = surf.get_at(posn)[0:3]
                dc = dst.get_at(posn)[0:3]
                self.assertEqual(dc, sc,
                                 "%s != %s: flags: %i"
                                 ", bpp: %i, posn: %s" %
                                 (dc, sc,
                                  surf.get_flags(), surf.get_bitsize(),
                                  posn))
            view = None
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_save_colorkey(self):
        """ make sure the color key is not changed when saving.
        """
        s = pygame.Surface((10,10), pygame.SRCALPHA, 32)
        s.fill((23,23,23))
        s.set_colorkey((0,0,0))
        colorkey1 = s.get_colorkey()
        p1 = s.get_at((0,0))

        temp_filename = "tmpimg.png"
        try:
            pygame.image.save(s, temp_filename)
            s2 = pygame.image.load(temp_filename)
        finally:
            os.remove(temp_filename)


        colorkey2 = s.get_colorkey()
        # check that the pixel and the colorkey is correct.
        self.assertEqual(colorkey1, colorkey2)
        self.assertEqual(p1, s2.get_at((0,0)))
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def todo_test_frombuffer(self):

        # __doc__ (as of 2008-08-02) for pygame.image.frombuffer:

          # pygame.image.frombuffer(string, size, format): return Surface
          # create a new Surface that shares data inside a string buffer
          # 
          # Create a new Surface that shares pixel data directly from the string
          # buffer. This method takes the same arguments as
          # pygame.image.fromstring(), but is unable to vertically flip the
          # source data.
          # 
          # This will run much faster than pygame.image.fromstring, since no
          # pixel data must be allocated and copied.

        self.fail()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_from_threshold(self):
        """ Does mask.from_threshold() work correctly?
        """

        a = [16, 24, 32]

        for i in a:
            surf = pygame.surface.Surface((70,70), 0, i)
            surf.fill((100,50,200),(20,20,20,20))
            mask = pygame.mask.from_threshold(surf,(100,50,200,255),(10,10,10,255))

            self.assertEqual(mask.count(), 400)
            self.assertEqual(mask.get_bounding_rects(), [pygame.Rect((20,20,20,20))])

        for i in a:
            surf = pygame.surface.Surface((70,70), 0, i)
            surf2 = pygame.surface.Surface((70,70), 0, i)
            surf.fill((100,100,100))
            surf2.fill((150,150,150))
            surf2.fill((100,100,100), (40,40,10,10))
            mask = pygame.mask.from_threshold(surf, (0,0,0,0), (10,10,10,255), surf2)

            self.assertEqual(mask.count(), 100)
            self.assertEqual(mask.get_bounding_rects(), [pygame.Rect((40,40,10,10))])
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_pixel_array (self):
        for bpp in (8, 16, 24, 32):
            sf = pygame.Surface ((10, 20), 0, bpp)
            sf.fill ((0, 0, 0))
            ar = pygame.PixelArray (sf)

            self.assertEqual (ar._pixels_address, sf._pixels_address)

            if sf.mustlock ():
                self.assertTrue (sf.get_locked ())

            self.assertEqual (len (ar), 10)

            del ar
            if sf.mustlock ():
                self.assertFalse (sf.get_locked ())
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_get_column (self):
        for bpp in (8, 16, 24, 32):
            sf = pygame.Surface ((6, 8), 0, bpp)
            sf.fill ((0, 0, 255))
            val = sf.map_rgb ((0, 0, 255))
            ar = pygame.PixelArray (sf)

            ar2 = ar.__getitem__ (1)
            self.assertEqual (len(ar2), 8)
            self.assertEqual (ar2.__getitem__ (0), val)
            self.assertEqual (ar2.__getitem__ (1), val)
            self.assertEqual (ar2.__getitem__ (2), val)

            ar2 = ar.__getitem__ (-1)
            self.assertEqual (len(ar2), 8)
            self.assertEqual (ar2.__getitem__ (0), val)
            self.assertEqual (ar2.__getitem__ (1), val)
            self.assertEqual (ar2.__getitem__ (2), val)
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_set_pixel (self):
        for bpp in (8, 16, 24, 32):
            sf = pygame.Surface ((10, 20), 0, bpp)
            sf.fill ((0, 0, 0))
            ar = pygame.PixelArray (sf)

            ar.__getitem__ (0).__setitem__ (0, (0, 255, 0))
            self.assertEqual (ar[0][0], sf.map_rgb ((0, 255, 0)))

            ar.__getitem__ (1).__setitem__ (1, (128, 128, 128))
            self.assertEqual (ar[1][1], sf.map_rgb ((128, 128, 128)))

            ar.__getitem__(-1).__setitem__ (-1, (128, 128, 128))
            self.assertEqual (ar[9][19], sf.map_rgb ((128, 128, 128)))

            ar.__getitem__ (-2).__setitem__ (-2, (128, 128, 128))
            self.assertEqual (ar[8][-2], sf.map_rgb ((128, 128, 128)))
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_contains (self):
        for bpp in (8, 16, 24, 32):
            sf = pygame.Surface ((10, 20), 0, bpp)
            sf.fill ((0, 0, 0))
            sf.set_at ((8, 8), (255, 255, 255))

            ar = pygame.PixelArray (sf)
            self.assertTrue ((0, 0, 0) in ar)
            self.assertTrue ((255, 255, 255) in ar)
            self.assertFalse ((255, 255, 0) in ar)
            self.assertFalse (0x0000ff in ar)

            # Test sliced array
            self.assertTrue ((0, 0, 0) in ar[8])
            self.assertTrue ((255, 255, 255) in ar[8])
            self.assertFalse ((255, 255, 0) in ar[8])
            self.assertFalse (0x0000ff in ar[8])
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_replace (self):
        #print "replace start"
        for bpp in (8, 16, 24, 32):
            sf = pygame.Surface ((10, 10), 0, bpp)
            sf.fill ((255, 0, 0))
            rval = sf.map_rgb ((0, 0, 255))
            oval = sf.map_rgb ((255, 0, 0))
            ar = pygame.PixelArray (sf)
            ar[::2].replace ((255, 0, 0), (0, 0, 255))
            self.assertEqual (ar[0][0], rval)
            self.assertEqual (ar[1][0], oval)
            self.assertEqual (ar[2][3], rval)
            self.assertEqual (ar[3][6], oval)
            self.assertEqual (ar[8][9], rval)
            self.assertEqual (ar[9][9], oval)

            ar[::2].replace ((0, 0, 255), (255, 0, 0), weights=(10, 20, 50))
            self.assertEqual (ar[0][0], oval)
            self.assertEqual (ar[2][3], oval)
            self.assertEqual (ar[3][6], oval)
            self.assertEqual (ar[8][9], oval)
            self.assertEqual (ar[9][9], oval)
        #print "replace end"
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_2dslice_assignment (self):
        w = 2 * 5 * 8
        h = 3 * 5 * 9
        sf = pygame.Surface ((w, h), 0, 32)
        ar = pygame.PixelArray (sf)
        size = (w, h)
        strides = (1, w)
        offset = 0
        self._test_assignment (sf, ar, size, strides, offset)
        xslice = slice (None, None, 2)
        yslice = slice (None, None, 3)
        ar, size, strides, offset = self._array_slice (
            ar, size, (xslice, yslice), strides, offset)
        self._test_assignment (sf, ar, size, strides, offset)
        xslice = slice (5, None, 5)
        yslice = slice (5, None, 5)
        ar, size, strides, offset = self._array_slice (
            ar, size, (xslice, yslice), strides, offset)
        self._test_assignment (sf, ar, size, strides, offset)
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_shape (self):
        for shape in [[4, 16], [5, 13]]:
            w, h = shape
            sf = pygame.Surface (shape, 0, 32)
            ar = pygame.PixelArray (sf)
            ai = arrinter.ArrayInterface (ar)
            ai_shape = [ai.shape[i] for i in range(ai.nd)]
            self.assertEqual (ai_shape, shape)
            ar2 = ar[::2,:]
            ai2 = arrinter.ArrayInterface (ar2)
            w2 = len(([0] * w)[::2])
            ai_shape = [ai2.shape[i] for i in range(ai2.nd)]
            self.assertEqual (ai_shape, [w2, h])
            ar2 = ar[:,::2]
            ai2 = arrinter.ArrayInterface (ar2)
            h2 = len(([0] * h)[::2])
            ai_shape = [ai2.shape[i] for i in range(ai2.nd)]
            self.assertEqual (ai_shape, [w, h2])
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_flags (self):
        aim = arrinter
        common_flags = (aim.PAI_NOTSWAPPED | aim.PAI_WRITEABLE |
                        aim.PAI_ALIGNED)
        s = pygame.Surface ((10, 2), 0, 32)
        ar = pygame.PixelArray (s)
        ai = aim.ArrayInterface (ar)
        self.assertEqual (ai.flags, common_flags | aim.PAI_FORTRAN)

        ar2 = ar[::2,:]
        ai = aim.ArrayInterface (ar2)
        self.assertEqual (ai.flags, common_flags)

        s = pygame.Surface ((8, 2), 0, 24)
        ar = pygame.PixelArray (s)
        ai = aim.ArrayInterface (ar)
        self.assertEqual (ai.flags, common_flags | aim.PAI_FORTRAN)

        s = pygame.Surface ((7, 2), 0, 24)
        ar = pygame.PixelArray (s)
        ai = aim.ArrayInterface (ar)
        self.assertEqual (ai.flags, common_flags)
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_lock (self):
        sf = pygame.Surface ((5, 5))

        sf.lock ()
        self.assertEquals (sf.get_locked (), True)
        self.assertEquals (sf.get_locks (), (sf,))

        sf.lock ()
        self.assertEquals (sf.get_locked (), True)
        self.assertEquals (sf.get_locks (), (sf, sf))

        sf.unlock ()
        self.assertEquals (sf.get_locked (), True)
        self.assertEquals (sf.get_locks (), (sf,))

        sf.unlock ()
        self.assertEquals (sf.get_locked (), False)
        self.assertEquals (sf.get_locks (), ())
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_pxarray_ref (self):
        sf = pygame.Surface ((5, 5))
        ar = pygame.PixelArray (sf)
        ar2 = pygame.PixelArray (sf)

        self.assertEquals (sf.get_locked (), True)
        self.assertEquals (sf.get_locks (), (ar, ar2))

        del ar
        self.assertEquals (sf.get_locked (), True)
        self.assertEquals (sf.get_locks (), (ar2,))

        ar = ar2[:]
        self.assertEquals (sf.get_locked (), True)
        self.assertEquals (sf.get_locks (), (ar2,))

        del ar
        self.assertEquals (sf.get_locked (), True)
        self.assertEquals (len (sf.get_locks ()), 1)
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_surf_lock (self):
        if not arraytype:
            self.fail("no array package installed")

        sf = pygame.Surface ((5, 5), 0, 32)
        for atype in pygame.surfarray.get_arraytypes ():
            pygame.surfarray.use_arraytype (atype)

            ar = pygame.surfarray.pixels2d (sf)
            self.assertEquals (sf.get_locked (), True)

            sf.unlock ()
            self.assertEquals (sf.get_locked (), True)

            del ar
            self.assertEquals (sf.get_locked (), False)
            self.assertEquals (sf.get_locks (), ())

        #print ("test_surf_lock - end")
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_copy(self):

        # __doc__ (as of 2008-06-25) for pygame.surface.Surface.copy:

          # Surface.copy(): return Surface
          # create a new copy of a Surface

        color = (25, 25, 25, 25)
        s1 = pygame.Surface((32,32), pygame.SRCALPHA, 32)
        s1.fill(color)

        s2 = s1.copy()

        s1rect = s1.get_rect()
        s2rect = s2.get_rect()

        self.assert_(s1rect.size == s2rect.size)
        self.assert_(s2.get_at((10,10)) == color)
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_fill(self):

        # __doc__ (as of 2008-06-25) for pygame.surface.Surface.fill:

          # Surface.fill(color, rect=None, special_flags=0): return Rect
          # fill Surface with a solid color

        color = (25, 25, 25, 25)
        fill_rect = pygame.Rect(0, 0, 16, 16)

        s1 = pygame.Surface((32,32), pygame.SRCALPHA, 32)
        s1.fill(color, fill_rect)

        for pt in test_utils.rect_area_pts(fill_rect):
            self.assert_(s1.get_at(pt) == color )

        for pt in test_utils.rect_outer_bounds(fill_rect):
            self.assert_(s1.get_at(pt) != color )
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_get_alpha(self):

        # __doc__ (as of 2008-06-25) for pygame.surface.Surface.get_alpha:

          # Surface.get_alpha(): return int_value or None
          # get the current Surface transparency value

        s1 = pygame.Surface((32,32), pygame.SRCALPHA, 32)
        self.assert_(s1.get_alpha() == 255)

        for alpha in (0, 32, 127, 255):
            s1.set_alpha(alpha)
            for t in range(4): s1.set_alpha(s1.get_alpha())
            self.assert_(s1.get_alpha() == alpha)

    ########################################################################
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_set_colorkey(self):

        # __doc__ (as of 2008-06-25) for pygame.surface.Surface.set_colorkey:

          # Surface.set_colorkey(Color, flags=0): return None
          # Surface.set_colorkey(None): return None
          # Set the transparent colorkey

        s = pygame.Surface((16,16), pygame.SRCALPHA, 32)

        colorkeys = ((20,189,20, 255),(128,50,50,255), (23, 21, 255,255))

        for colorkey in colorkeys:
            s.set_colorkey(colorkey)
            for t in range(4): s.set_colorkey(s.get_colorkey())
            self.assertEquals(s.get_colorkey(), colorkey)
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def todo_test_convert_alpha(self):

        # __doc__ (as of 2008-08-02) for pygame.surface.Surface.convert_alpha:

          # Surface.convert_alpha(Surface): return Surface
          # Surface.convert_alpha(): return Surface
          # change the pixel format of an image including per pixel alphas
          #
          # Creates a new copy of the surface with the desired pixel format. The
          # new surface will be in a format suited for quick blitting to the
          # given format with per pixel alpha. If no surface is given, the new
          # surface will be optimized for blitting to the current display.
          #
          # Unlike the Surface.convert() method, the pixel format for the new
          # image will not be exactly the same as the requested source, but it
          # will be optimized for fast alpha blitting to the destination.
          #

        self.fail()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_get_at(self):
        surf = pygame.Surface((2, 2), 0, 24)
        c00 = pygame.Color(1, 2, 3)
        c01 = pygame.Color(5, 10, 15)
        c10 = pygame.Color(100, 50, 0)
        c11 = pygame.Color(4, 5, 6)
        surf.set_at((0, 0), c00)
        surf.set_at((0, 1), c01)
        surf.set_at((1, 0), c10)
        surf.set_at((1, 1), c11)
        c = surf.get_at((0, 0))
        self.failUnless(isinstance(c, pygame.Color))
        self.failUnlessEqual(c, c00)
        self.failUnlessEqual(surf.get_at((0, 1)), c01)
        self.failUnlessEqual(surf.get_at((1, 0)), c10)
        self.failUnlessEqual(surf.get_at((1, 1)), c11)
        for p in [(-1, 0), (0, -1), (2, 0), (0, 2)]:
            self.failUnlessRaises(IndexError, surf.get_at, p)
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_get_palette(self):
        pygame.init()
        try:
            palette = [Color(i, i, i) for i in range(256)]
            pygame.display.set_mode((100, 50))
            surf = pygame.Surface((2, 2), 0, 8)
            surf.set_palette(palette)
            palette2 = surf.get_palette()
            r,g,b = palette2[0]

            self.failUnlessEqual(len(palette2), len(palette))
            for c2, c in zip(palette2, palette):
                self.failUnlessEqual(c2, c)
            for c in palette2:
                self.failUnless(isinstance(c, pygame.Color))
        finally:
            pygame.quit()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_set_palette_at(self):
        pygame.init()
        try:
            pygame.display.set_mode((100, 50))
            surf = pygame.Surface((2, 2), 0, 8)
            original = surf.get_palette_at(10)
            replacement = Color(1, 1, 1, 255)
            if replacement == original:
                replacement = Color(2, 2, 2, 255)
            surf.set_palette_at(10, replacement)
            self.failUnlessEqual(surf.get_palette_at(10), replacement)
            next = tuple(original)
            surf.set_palette_at(10, next)
            self.failUnlessEqual(surf.get_palette_at(10), next)
            next = tuple(original)[0:3]
            surf.set_palette_at(10, next)
            self.failUnlessEqual(surf.get_palette_at(10), next)
            self.failUnlessRaises(IndexError,
                                  surf.set_palette_at,
                                  256, replacement)
            self.failUnlessRaises(IndexError,
                                  surf.set_palette_at,
                                  -1, replacement)
        finally:
            pygame.quit()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def todo_test_unlock(self):

        # __doc__ (as of 2008-08-02) for pygame.surface.Surface.unlock:

          # Surface.unlock(): return None
          # unlock the Surface memory from pixel access
          #
          # Unlock the Surface pixel data after it has been locked. The unlocked
          # Surface can once again be drawn and managed by Pygame. See the
          # Surface.lock() documentation for more details.
          #
          # All pygame functions will automatically lock and unlock the Surface
          # data as needed. If a section of code is going to make calls that
          # will repeatedly lock and unlock the Surface many times, it can be
          # helpful to wrap the block inside a lock and unlock pair.
          #
          # It is safe to nest locking and unlocking calls. The surface will
          # only be unlocked after the final lock is released.
          #

        self.fail()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_convert(self):
        """Ensure method convert() preserves the surface's class

        When Surface is subclassed, the inherited convert() method will return
        instances of the subclass. Non Surface fields are omitted, however.
        This includes instance attributes.
        """
        pygame.display.init()
        try:
            ms1 = self.MySurface((32, 32), 0, 24)
            ms2 = ms1.convert(24)
            self.assertTrue(ms2 is not ms1)
            self.assertTrue(isinstance(ms2, self.MySurface))
            self.assertTrue(ms1.an_attribute)
            self.assertRaises(AttributeError, getattr, ms2, "an_attribute")
        finally:
            pygame.display.quit()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_convert_alpha(self):
        """Ensure method convert_alpha() preserves the surface's class

        When Surface is subclassed, the inherited convert_alpha() method will
        return instances of the subclass. Non Surface fields are omitted,
        however. This includes instance attributes.
        """
        pygame.display.init()
        try:
            pygame.display.set_mode((40, 40))
            s = pygame.Surface((32, 32), pygame.SRCALPHA, 16)
            ms1 = self.MySurface((32, 32), pygame.SRCALPHA, 32)
            ms2 = ms1.convert_alpha(s)
            self.assertTrue(ms2 is not ms1)
            self.assertTrue(isinstance(ms2, self.MySurface))
            self.assertTrue(ms1.an_attribute)
            self.assertRaises(AttributeError, getattr, ms2, "an_attribute")
        finally:
            pygame.display.quit()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_array_interface_masks(self):
        """Test non-default color byte orders on 3D views"""

        sz = (5, 7)
        # Reversed RGB byte order
        s = pygame.Surface(sz, 0, 32)
        s_masks = list(s.get_masks())
        masks = [0xff, 0xff00, 0xff0000]
        if s_masks[0:3] == masks or s_masks[0:3] == masks[::-1]:
            masks = s_masks[2::-1] + s_masks[3:4]
            self._check_interface_3D(pygame.Surface(sz, 0, 32, masks))
        s = pygame.Surface(sz, 0, 24)
        s_masks = list(s.get_masks())
        masks = [0xff, 0xff00, 0xff0000]
        if s_masks[0:3] == masks or s_masks[0:3] == masks[::-1]:
            masks = s_masks[2::-1] + s_masks[3:4]
            self._check_interface_3D(pygame.Surface(sz, 0, 24, masks))

        masks = [0xff00, 0xff0000, 0xff000000, 0]
        self._check_interface_3D(pygame.Surface(sz, 0, 32, masks))

        # Unsupported RGB byte orders
        masks = [0xff00, 0xff, 0xff0000, 0]
        self.assertRaises(ValueError,
                          pygame.Surface(sz, 0, 24, masks).get_view, '3')
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def NEWBUF_test_newbuf_PyBUF_flags_0D(self):
        # This is the same handler as used by get_buffer(), so just
        # confirm that it succeeds for one case.
        buftools = self.buftools
        Importer = buftools.Importer
        s = pygame.Surface((10, 6), 0, 32)
        a = s.get_view('0')
        b = Importer(a, buftools.PyBUF_SIMPLE)
        self.assertEqual(b.ndim, 0)
        self.assertTrue(b.format is None)
        self.assertEqual(b.len, a.length)
        self.assertEqual(b.itemsize, 1)
        self.assertTrue(b.shape is None)
        self.assertTrue(b.strides is None)
        self.assertTrue(b.suboffsets is None)
        self.assertFalse(b.readonly)
        self.assertEqual(b.buf, s._pixels_address)
项目:pyclimber    作者:manixaist    | 项目源码 | 文件源码
def load_image_to_tiles(self, file_name, tile_width, tile_height, images):
        """Load the specified image and attempt to split it into tiles
        of the specified width and height."""
        image = pygame.image.load(file_name)
        image_rect = image.get_rect()

        image_width = image_rect.width
        image_height = image_rect.height

        # Calculate the number of tiles in one row of the image (ignoring any remaining space)
        tiles_per_row = image_width // tile_width
        # Calculate the number of tiles in one col of the image (ignoring any remaining space)
        tiles_per_col = image_height // tile_height

        # The index for the row is over the number of cols in a row and vice versa
        for row_index in range(0, tiles_per_col):
            for col_index in range(0, tiles_per_row):
                # Create a new surface the size of the tile
                new_surface = pygame.Surface((tile_width, tile_height))
                # Set transparency color key (colors matching this won't get copied in blits)
                new_surface.set_colorkey(self.settings.color_key)
                # Copy just the sub-section of the image onto the surface
                new_surface.blit(image, (0, 0), (col_index * tile_width, row_index * tile_height, tile_width, tile_height))
                # Now add it to our list of surfaces, these will be index-addressed for now
                images.append(new_surface)
项目:pipresenter    作者:Turakar    | 项目源码 | 文件源码
def __init__(self, caption, x, y, w, h, font):
        self.x = x
        self.y = y
        self.caption = caption
        self.w = w+1 # overlap borders
        self.h = h+1 # overlap borders
        self.special = False
        self.enter = False
        self.bskey = False
        self.fskey = False
        self.spacekey = False
        self.escape = False
        self.shiftkey = False
        self.font = font
        self.selected = False
        self.dirty = True
        self.keylayer = pygame.Surface((self.w,self.h)).convert()
        self.keylayer.fill((128, 128, 128)) # 0,0,0
##        self.keylayer.set_alpha(160)
        # Pre draw the border and store in the key layer
        pygame.draw.rect(self.keylayer, (255,255,255), (0,0,self.w,self.h), 1)
项目:project_xcape    作者:OthmanEmpire    | 项目源码 | 文件源码
def add(self, state, images, duration=1000):
        """
        Links a given state to a sequence of images that can be rendered as
        an animation.

        The timing of each frame in the animation is automatically partitioned
        such that each frame has uniform of length (and if a single image is
        given, its duration will span forever). This can be technically
        modified after adding the animation for fine tuning.

        :param state: String, the name of the state tied to the animation.
        :param images: List, containing pygame.Surface objects.
        :param duration: Integer, the length of the animation in milliseconds.
        """
        try:
            dt = duration / len(images)
            timings = [i*dt for i, _ in enumerate(images, start=1)]
            self.stateToTiming[state] = timings
            self.stateToAnimation[state] = images

        except TypeError:
            timings = [float('inf')]
            self.stateToTiming[state] = timings
            self.stateToAnimation[state] = [images]