python类error()的实例源码

imageext_test.py 文件源码 项目:Projects 作者: it2school 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def test_load_non_string_file(self):
        self.assertRaises(pygame.error, imageext.load_extended, [])
imageext_test.py 文件源码 项目:Projects 作者: it2school 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_save_bad_filename(self):
        im = pygame.Surface((10, 10), 0, 32)
        u = as_unicode(r"a\x00b\x00c.png")
        self.assertRaises(pygame.error, imageext.save_extended, im, u)
imageext_test.py 文件源码 项目:Projects 作者: it2school 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def test_load_bad_filename(self):
        u = as_unicode(r"a\x00b\x00c.png")
        self.assertRaises(pygame.error, imageext.load_extended, u)
imageext_test.py 文件源码 项目:Projects 作者: it2school 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def test_save_unknown_extension(self):
        im = pygame.Surface((10, 10), 0, 32)
        s = "foo.bar"
        self.assertRaises(pygame.error, imageext.save_extended, im, s)
imageext_test.py 文件源码 项目:Projects 作者: it2school 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def test_load_unknown_extension(self):
        s = "foo.bar"
        self.assertRaises(pygame.error, imageext.load_extended, s)
freetype_test.py 文件源码 项目:Projects 作者: it2school 项目源码 文件源码 阅读 42 收藏 0 点赞 0 评论 0
def test_issue_144(self):
        """Issue #144: unable to render text"""

        # The bug came in two parts. The first was a convertion bug from
        # FT_Fixed to integer in for an Intel x86_64 Pygame build. The second
        # was to have the raised exception disappear before Font.render
        # returned to Python level.
        #
        font = ft.Font(None, size=64)
        s = 'M' * 100000  # Way too long for an SDL surface
        self.assertRaises(pygame.error, font.render, s, (0, 0, 0))
base_test.py 文件源码 项目:Projects 作者: it2school 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def test_set_error(self):

        e = pygame.get_error()
        self.assertTrue(e == "" or
                        # This may be returned by SDL_mixer built with
                        # FluidSynth support. Setting environment variable
                        # SDL_SOUNDFONTS to the path of a valid sf2 file
                        # removes the error message.
                        e == "No SoundFonts have been requested",
                        e)
        pygame.set_error("hi")
        self.assertEqual(pygame.get_error(), "hi")
        pygame.set_error("")
        self.assertEqual(pygame.get_error(), "")
surface_test.py 文件源码 项目:Projects 作者: it2school 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def test_image_convert_bug_131(self):
        # Bitbucket bug #131: Unable to Surface.convert(32) some 1-bit images.
        # https://bitbucket.org/pygame/pygame/issue/131/unable-to-surfaceconvert-32-some-1-bit

        # Skip test_image_convert_bug_131 for headless tests.
        if os.environ.get('SDL_VIDEODRIVER') == 'dummy':
            return

        pygame.display.init()
        pygame.display.set_mode((640,480))

        im  = pygame.image.load(example_path(os.path.join("data", "city.png")))
        im2 = pygame.image.load(example_path(os.path.join("data", "brick.png")))

        self.assertEquals( im.get_palette(),  ((0, 0, 0, 255), (255, 255, 255, 255)) )
        self.assertEquals( im2.get_palette(), ((0, 0, 0, 255), (0, 0, 0, 255)) )

        self.assertEqual(repr(im.convert(32)),  '<Surface(24x24x32 SW)>')
        self.assertEqual(repr(im2.convert(32)), '<Surface(469x137x32 SW)>')

        # Ensure a palette format to palette format works.
        im3 = im.convert(8)
        self.assertEqual(repr(im3), '<Surface(24x24x8 SW)>')
        self.assertEqual(im3.get_palette(), im.get_palette())

        # It is still an error when the target format really does have
        # an empty palette (all the entries are black).
        self.assertRaises(pygame.error, im2.convert, 8)
        self.assertEqual(pygame.get_error(), "Empty destination palette")
recipe-521884.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def main(args):
    # look at command line
    streaming = False
    if args and args[0] == '-s':
        streaming = True
        args.pop(0)
    if not args:
        print >>sys.stderr, "usage: soundplay [-s] FILE"
        print >>sys.stderr, "  -s    use streaming mode"
        return 2

    # initialize pygame.mixer module
    # if these setting do not work with your audio system
    # change the global constants accordingly
    try:
        pygame.mixer.init(FREQ, BITSIZE, CHANNELS, BUFFER)
    except pygame.error, exc:
        print >>sys.stderr, "Could not initialize sound system: %s" % exc
        return 1

    try:
        for soundfile in args:
            try:
                # play it!
                if streaming:
                    playmusic(soundfile)
                else:
                    playsound(soundfile)
            except pygame.error, exc:
                print >>sys.stderr, "Could not play sound file: %s" % soundfile
                print exc
                continue
    except KeyboardInterrupt:
        # if user hits Ctrl-C, exit gracefully
        pass
    return 0
event.py 文件源码 项目:PyCut 作者: FOSSRIT 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
def _post(self, evt):
        try:
            pygame.event.post(evt)
        except pygame.error, e:
            if str(e) == 'Event queue full':
                print "Event queue full!"
                pass
            else:
                raise e
graphics.py 文件源码 项目:n1mm_view 作者: n1kdo 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def init_display():
    """
    set up the pygame display, full screen
    """

    # Check which frame buffer drivers are available
    # Start with fbcon since directfb hangs with composite output
    drivers = ['fbcon', 'directfb', 'svgalib', 'directx', 'windib']
    found = False
    for driver in drivers:
        # Make sure that SDL_VIDEODRIVER is set
        if not os.getenv('SDL_VIDEODRIVER'):
            os.putenv('SDL_VIDEODRIVER', driver)
        try:
            pygame.display.init()
        except pygame.error:
            #  logging.warn('Driver: %s failed.' % driver)
            continue
        found = True
        logging.debug('using %s driver', driver)
        break

    if not found:
        raise Exception('No suitable video driver found!')

    size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
    pygame.mouse.set_visible(0)
    if driver != 'directx':  # debugging hack runs in a window on Windows
        screen = pygame.display.set_mode(size, pygame.FULLSCREEN)
    else:
        logging.info('running in windowed mode')
        # set window origin for windowed usage
        os.putenv('SDL_VIDEO_WINDOW_POS', '0,0')
        # size = (size[0]-10, size[1] - 30)
        screen = pygame.display.set_mode(size, pygame.NOFRAME)

    logging.debug('display size: %d x %d', size[0], size[1])
    # Clear the screen to start
    screen.fill(BLACK)
    return screen, size
graphics.py 文件源码 项目:n1mm_view 作者: n1kdo 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def create_map():
    """
    create the base map for the choropleth.
    """
    logging.debug('create_map() -- Please wait while I create the world.')
    degrees_width = 118.0
    degrees_height = 55.0
    center_lat = 44.5
    center_lon = -110.0
    my_map = Basemap(  # ax=ax,
        projection='merc',  # default is cyl
        ellps='WGS84',
        lat_0=center_lat, lon_0=center_lon,
        llcrnrlat=center_lat - degrees_height / 2.0,
        llcrnrlon=center_lon - degrees_width / 2.0,
        urcrnrlat=center_lat + degrees_height / 2.0,
        urcrnrlon=center_lon + degrees_width / 2.0,
        resolution='i',  # 'c', 'l', 'i', 'h', 'f'
    )
    logging.debug('created map')
    logging.debug('loading shapes...')
    for section_name in CONTEST_SECTIONS.keys():
        # logging.debug('trying to load shape for %s', section_name)
        try:
            my_map.readshapefile('shapes/%s' % section_name, section_name, drawbounds=False)
        except IOError, err:
            logging.error('Could not load shape for %s' % section_name)

    logging.debug('loaded section shapes')
    return my_map
main.py 文件源码 项目:Pong-py 作者: alejandrogm90 项目源码 文件源码 阅读 52 收藏 0 点赞 0 评论 0
def load_image(filename, transparent=False):
    """Function to reurn a image object."""
    try:
        image = pygame.image.load(filename)
    except pygame.error:
        raise SystemExit
    image = image.convert()
    if transparent:
        color = image.get_at((0, 0))
        image.set_colorkey(color, RLEACCEL)
    return image
spritesheet.py 文件源码 项目:MDB 作者: gustavo-castro 项目源码 文件源码 阅读 46 收藏 0 点赞 0 评论 0
def __init__(self, filename):
        try:
            self.sheet = pygame.image.load(filename).convert()
        except pygame.error, message:
            print 'Unable to load spritesheet image:', filename
            raise message

    # Load a specific image from a specific rectangle
gui.py 文件源码 项目:photobooth 作者: LoiX07 项目源码 文件源码 阅读 48 收藏 0 点赞 0 评论 0
def show_picture(self, filename, size=(0, 0), offset=(0, 0), flip=False, alpha=255):
        """
        Display of a picture
        """
        # Use window size if none given
        if size == (0, 0):
            size = self.size
        try:
            # Load image from file
            image = pygame.image.load(filename)
        except pygame.error as exc:
            raise GuiException("ERROR: Can't open image '" + filename + "': " +
                               exc.message)
        # Extract image size and determine scaling
        image_size = image.get_rect().size
        image_scale = min([min(a, b) / b for a, b in zip(size, image_size)])
        # New image size
        new_size = [int(a * image_scale) for a in image_size]
        # Update offset
        offset = tuple(a + int((b - c) / 2)
                       for a, b, c in zip(offset, size, new_size))
        # Apply scaling and display picture
        image = pygame.transform.scale(image, new_size).convert()
        image.set_alpha(alpha)
        # Create surface and blit the image to it
        surface = pygame.Surface(new_size)
        surface.blit(image, (0, 0))
        if flip:
            surface = pygame.transform.flip(surface, True, False)
        self.surface_list.append((surface, offset))
        return new_size
loader.py 文件源码 项目:wargame 作者: maximinus 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def load_fonts(self, font_folder):
        font_config = self.configs.get('Fonts')
        for i in font_config.fonts:
            filepath = os.path.join(font_folder, font_config.fonts[i].file)
            size = font_config.fonts[i].size
            try:
                self.fonts[i] = pygame.font.Font(filepath, size)
            except OSError:
                logger.error('Could not load font {0}'.format(filepath))
        # store a standard font
        self.fonts['default'] = self.fonts[font_config.default]
loader.py 文件源码 项目:wargame 作者: maximinus 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def load_image_folder(self, folder, namespace):
        # loop through files in given folder
        for filename in os.listdir(folder):
            name = filename.split('.')[0]
            path = os.path.join(folder, filename)
            try:
                image = pygame.image.load(path).convert_alpha()
                self.images['{0}.{1}'.format(namespace, name)] = image
            except pygame.error:
                logger.error('Could not load image {0}'.format(path))
loader.py 文件源码 项目:wargame 作者: maximinus 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def get_image(self, image_name):
        try:
            return self.images[image_name]
        except KeyError:
            logger.error('No image name {0}'.format(image_name))
            return self.error_image
GameResources.py 文件源码 项目:sudoku-solver 作者: dancodery 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def load_image(name):
    """A better load of images."""
    fullname = os.path.join("images", name)
    try:
        image = pygame.image.load(fullname)
        if image.get_alpha() == None:
            image = image.convert()
        else:
            image = image.convert_alpha()
    except pygame.error:
        print("Oops! Could not load image:", fullname)
    return image, image.get_rect()
cli.py 文件源码 项目:solarwolf 作者: pygame 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def __pygamebox(title, message):
    try:
        import pygame
        pygame.quit() #clean out anything running
        pygame.display.init()
        pygame.font.init()
        screen = pygame.display.set_mode((460, 140))
        pygame.display.set_caption(title)
        font = pygame.font.Font(None, 18)
        foreg, backg, liteg = (0, 0, 0), (180, 180, 180), (210, 210, 210)
        ok = font.render('Ok', 1, foreg, liteg)
        okbox = ok.get_rect().inflate(200, 10)
        okbox.centerx = screen.get_rect().centerx
        okbox.bottom = screen.get_rect().bottom - 10
        screen.fill(backg)
        screen.fill(liteg, okbox)
        screen.blit(ok, okbox.inflate(-200, -10))
        pos = [10, 10]
        for text in message.split('\n'):
            if text:
                msg = font.render(text, 1, foreg, backg)
                screen.blit(msg, pos)
            pos[1] += font.get_height()
        pygame.display.flip()
        stopkeys = pygame.K_ESCAPE, pygame.K_SPACE, pygame.K_RETURN, pygame.K_KP_ENTER
        while 1:
            e = pygame.event.wait()
            if e.type == pygame.QUIT or \
                       (e.type == pygame.KEYDOWN and e.key in stopkeys) or \
                       (e.type == pygame.MOUSEBUTTONDOWN and okbox.collidepoint(e.pos)):
                break
        pygame.quit()
    except pygame.error:
        raise ImportError


问题


面经


文章

微信
公众号

扫码关注公众号