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

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

项目:Projects    作者:it2school    | 项目源码 | 文件源码
def load_image(file, transparent):
    "loads an image, prepares it for play"
    file = os.path.join(main_dir, 'data', file)
    try:
        surface = pygame.image.load(file)
    except pygame.error:
        raise SystemExit('Could not load image "%s" %s' %
                         (file, pygame.get_error()))
    if transparent:
        corner = surface.get_at((0, 0))
        surface.set_colorkey(corner, RLEACCEL)
    return surface.convert()



# The logic for all the different sprite types
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def load_sound(file):
    if not pygame.mixer: return dummysound()
    file = os.path.join(main_dir, 'data', file)
    try:
        sound = pygame.mixer.Sound(file)
        return sound
    except pygame.error:
        print ('Warning, unable to load, %s' % file)
    return dummysound()



# each type of game object gets an init and an
# update function. the update function is called
# once per frame, and it is when each object should
# change it's current position and state. the Player
# object actually gets a "move" function instead of
# update, since it is passed extra information about
# the keyboard
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def not_init_assertions(self):
        self.assert_(not pygame.display.get_init(),
                     "display shouldn't be initialized" )
        if 'pygame.mixer' in sys.modules:
            self.assert_(not pygame.mixer.get_init(),
                         "mixer shouldn't be initialized" )
        if 'pygame.font' in sys.modules:
            self.assert_(not pygame.font.get_init(),
                         "init shouldn't be initialized" )

        ## !!! TODO : Remove when scrap works for OS X
        import platform
        if platform.system().startswith('Darwin'):
            return

        try:
            self.assertRaises(pygame.error, pygame.scrap.get)
        except NotImplementedError:
            # Scrap is optional.
            pass

        # pygame.cdrom
        # pygame.joystick
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_get_error(self):

        # __doc__ (as of 2008-08-02) for pygame.base.get_error:

          # pygame.get_error(): return errorstr
          # get the current error message
          #
          # SDL maintains an internal error message. This message will usually
          # be given to you when pygame.error is raised. You will rarely need to
          # call this function.
          #

        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 sound font
                        # 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(), "")
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_subsurface(self):
        # Blitting a surface to its subsurface is allowed.
        surf = self._make_surface(32, srcalpha=True)
        comp = surf.copy()
        comp.blit(surf, (3, 0))
        sub = surf.subsurface((3, 0, 6, 6))
        sub.blit(surf, (0, 0))
        del sub
        self._assert_same(surf, comp)
        # Blitting a subsurface to its owner is forbidden because of
        # lock conficts. This limitation allows the overlap check
        # in PySurface_Blit of alphablit.c to be simplified.
        def do_blit(d, s):
            d.blit(s, (0, 0))
        sub = surf.subsurface((1, 1, 2, 2))
        self.failUnlessRaises(pygame.error, do_blit, surf, sub)
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_size(self):
        f = pygame_font.Font(None, 20)
        text = as_unicode("Xg")
        size = f.size(text)
        w, h = size
        self.assert_(isinstance(w, int) and isinstance(h, int))
        s = f.render(text, False, (255, 255, 255))
        self.assert_(size == s.get_size())
        btext = text.encode("ascii")
        self.assert_(f.size(btext) == size)
        text = as_unicode(r"\u212A")
        btext = text.encode("UTF-16")[2:] # Keep the byte order consistent.
        bsize = f.size(btext)
        try:
            size = f.size(text)
        except pygame.error:
            pass
        else:
            self.assert_(size != bsize)
项目:rexmenu    作者:robmcmullen    | 项目源码 | 文件源码
def __init__(self, font, rom="", emulator="advmame", title="", imgpath="", find_image=None, max_size=-1, extra_paths=[]):
        if imgpath:
            filename, _ = os.path.splitext(os.path.basename(imgpath))
            if "_" in filename:
                rom, title = filename.split("_", 1)
            else:
                rom = title = filename
        elif rom:
            imgpath = find_image(rom, emulator, extra_paths)
        if title:
            self.title = title
        else:
            self.title = rom
        self.cmdline = shlex.split(emulator)
        self.cmdline.append(rom)
        try:
            self.image = pygame.image.load(imgpath).convert(24)
            self.rect = self.image.get_rect()
            if max_size > 0:
                self.rescale(max_size)
        except pygame.error:
            self.image = None
        self.label = font.render(self.title, 1, grey)
        self.label_size = font.size(self.title)
项目:wargame    作者:maximinus    | 项目源码 | 文件源码
def load(self, root_folder):
        # config files under ROOT/resources/config
        # iterate through those files
        for subdir, dirs, files in os.walk(root_folder):
            for file in files:
                # load this yaml file
                filepath = os.path.join(subdir, file)
                data = yaml.load(open(filepath, 'r'))
                path = PurePath(filepath).parts
                path = '/'.join(path[path.index('resources'):])
                config = get_config_item(data, path)
                if config is None:
                    logger.error('Failed to load {0}'.format(path))
                    continue
                # store this item
                self.data[config.data.type] = config.data
项目:solarwolf    作者:pygame    | 项目源码 | 文件源码
def textlined(self, color, text, center=None, pos='center'):
        darkcolor = [int(c//2) for c in color]
        if text is None: text = ' '
        try:
            if gfx.surface.get_bytesize()>1:
                img1 = self.font.render(text, 1, color)
                img2 = self.font.render(text, 1, darkcolor)
            else:
                img1 = img2 = self.font.render(text, 0, color)
                img2 = self.font.render(text, 0, darkcolor)
        except (pygame.error, TypeError):
            img1 = img2 = pygame.Surface((10, 10))

        newsize = img1.get_width()+4, img1.get_height()+4
        img = pygame.Surface(newsize)
        img.blit(img2, (0, 0))
        img.blit(img2, (0, 4))
        img.blit(img2, (4, 0))
        img.blit(img2, (4, 4))
        img.blit(img1, (2, 2))
        img = img.convert()
        img.set_colorkey((0,0,0), pygame.RLEACCEL)
        r = self._positionrect(img, center, pos)
        return [img, r]
项目:solarwolf    作者:pygame    | 项目源码 | 文件源码
def textshadowed(self, color, text, center=None, pos='center'):
        darkcolor = [int(c//2) for c in color]
        if text is None: text = ' '
        try:
            if gfx.surface.get_bytesize()>1:
                img1 = self.font.render(text, 1, color)
                img2 = self.font.render(text, 1, darkcolor)
            else:
                img1 = img2 = self.font.render(text, 0, color)
                img2 = self.font.render(text, 0, darkcolor)
        except (pygame.error, TypeError):
            img1 = img2 = pygame.Surface((10, 10))

        newsize = img1.get_width()+2, img1.get_height()+2
        img = pygame.Surface(newsize)
        img.blit(img2, (2, 2))
        img.blit(img1, (0, 0))
        img = img.convert()
        img.set_colorkey((0,0,0), pygame.RLEACCEL)
        r = self._positionrect(img, center, pos)
        return [img, r]
项目:solarwolf    作者:pygame    | 项目源码 | 文件源码
def initialize(size, fullscreen):
    global surface, rect, starobj
    try:
        flags = 0
        if fullscreen:
            flags |= FULLSCREEN
        #depth = pygame.display.mode_ok(size, flags, 16)
        surface = pygame.display.set_mode(size, flags)#, depth)
        rect = surface.get_rect()

        pygame.mouse.set_visible(0)

        if surface.get_bytesize() == 1:
            loadpalette()

    except pygame.error as msg:
        raise pygame.error('Cannot Initialize Graphics')
    starobj = stars.Stars()
项目:WebSecurityEverywhere    作者:McuMirror    | 项目源码 | 文件源码
def load_image(filename):
    filename = filepath(filename)
    try:
        image = pygame.image.load(filename)
        image = pygame.transform.scale(image, (image.get_width()*2, image.get_height()*2))
    except pygame.error:
        raise SystemExit, "Unable to load: " + filename
    return image.convert_alpha()

# def show_popup_new(screen, text):
    # font = pygame.font.Font(None, 20)
    # label = font.render(text, 1, (yellow))
    # label_x = (LCD_WIDTH/2)-(label.get_width()/2)
    # label_y = (LCD_HEIGHT/2)-(font.get_height()/2)
    # pygame.draw.rect(screen, red, (label_x, label_y, 20,40), 0)
    # screen.blit(label, (label_x, label_y))        
    # rotated = pygame.transform.rotate(screen, 90)
    # screen.blit(rotated, (0, 0))
    # pygame.display.flip()
项目:WebSecurityEverywhere    作者:McuMirror    | 项目源码 | 文件源码
def saveSettings():
    print "- Saving settings"
    try:
        outfile = open('config.pkl', 'wb')
        # Use a dictionary (rather than pickling 'raw' values) so
        # the number & order of things can change without breaking.
        print("-- ok")
        d = { 
            'displayDelay' : displayDelay,
            'countryBlocked' : countryBlocked,
            'countryForced' : countryForced,
            'WifiAPkeyLenght' : WifiAPkeyLenght
            }
        pickle.dump(d, outfile)
        outfile.close()
    except:
        print("-- error")
        pass
项目:WebSecurityEverywhere    作者:McuMirror    | 项目源码 | 文件源码
def loadSettings():
    global displayDelay
    global countryBlocked
    global countryForced
    global WifiAPkeyLenght
    print "- Loading settings"
    try:
        infile = open('config.pkl', 'rb')
        d = pickle.load(infile)
        infile.close()
        print("-- ok")
        if 'displayDelay' in d: displayDelay = d['displayDelay']
        if 'countryBlocked' in d: countryBlocked = d['countryBlocked']
        if 'countryForced' in d: countryForced = d['countryForced']
        if 'WifiAPkeyLenght' in d: WifiAPkeyLenght = d['WifiAPkeyLenght']
    except:
        print("-- error")
        pass
项目:AIFun    作者:Plottel    | 项目源码 | 文件源码
def make_sound (array):
    """pygame._numpysndarray.make_sound(array): return Sound

    Convert an array into a Sound object.

    Create a new playable Sound object from an array. The mixer module
    must be initialized and the array format must be similar to the mixer
    audio format.
    """
    # Info is a (freq, format, stereo) tuple
    info = pygame.mixer.get_init ()
    if not info:
        raise pygame.error("Mixer not initialized")
    channels = info[2]

    shape = array.shape
    if channels == 1:
        if len (shape) != 1:
            raise ValueError("Array must be 1-dimensional for mono mixer")
    else:
        if len (shape) != 2:
            raise ValueError("Array must be 2-dimensional for stereo mixer")
        elif shape[1] != channels:
            raise ValueError("Array depth must match number of mixer channels")
    return mixer.Sound (array)
项目:AIFun    作者:Plottel    | 项目源码 | 文件源码
def load_sound(file):
    if not pygame.mixer: return dummysound()
    file = os.path.join('data', file)
    try:
        sound = pygame.mixer.Sound(file)
        return sound
    except pygame.error:
        print 'Warning, unable to load,', file
    return dummysound()



# each type of game object gets an init and an
# update function. the update function is called
# once per frame, and it is when each object should
# change it's current position and state. the Player
# object actually gets a "move" function instead of
# update, since it is passed extra information about
# the keyboard
项目:AIFun    作者:Plottel    | 项目源码 | 文件源码
def load_sound(file):
    if not pygame.mixer: return dummysound()
    file = os.path.join(main_dir, 'data', file)
    try:
        sound = pygame.mixer.Sound(file)
        return sound
    except pygame.error:
        print ('Warning, unable to load, %s' % file)
    return dummysound()



# each type of game object gets an init and an
# update function. the update function is called
# once per frame, and it is when each object should
# change it's current position and state. the Player
# object actually gets a "move" function instead of
# update, since it is passed extra information about
# the keyboard
项目:AIFun    作者:Plottel    | 项目源码 | 文件源码
def not_init_assertions(self):
        self.assert_(not pygame.display.get_init(),
                     "display shouldn't be initialized" )
        self.assert_(not pygame.mixer.get_init(),
                     "mixer shouldn't be initialized" )
        self.assert_(not pygame.font.get_init(),
                     "init shouldn't be initialized" )

        ## !!! TODO : Remove when scrap works for OS X
        import platform
        if platform.system().startswith('Darwin'):
            return

        try:
            self.assertRaises(pygame.error, pygame.scrap.get)
        except NotImplementedError:
            # Scrap is optional.
            pass

        # pygame.cdrom
        # pygame.joystick
项目:AIFun    作者:Plottel    | 项目源码 | 文件源码
def test_get_error(self):

        # __doc__ (as of 2008-08-02) for pygame.base.get_error:

          # pygame.get_error(): return errorstr
          # get the current error message
          # 
          # SDL maintains an internal error message. This message will usually
          # be given to you when pygame.error is raised. You will rarely need to
          # call this function.
          # 

        self.assertEqual(pygame.get_error(), "")
        pygame.set_error("hi")
        self.assertEqual(pygame.get_error(), "hi")
        pygame.set_error("")
        self.assertEqual(pygame.get_error(), "")
项目:Slither    作者:PySlither    | 项目源码 | 文件源码
def loadSound(self, name):
        '''Load a sound. Set this function to a variable then call variable.play()'''
        try:
            pygame.mixer.get_init()
        except:
            pass
        class NoneSound:
            def play(self): pass
        if not pygame.mixer:
            return NoneSound()
        fullname = os.path.join(scriptdir, name)
        try:
            sound = pygame.mixer.Sound(fullname)
        except pygame.error as e:
            print ('Cannot load sound: %s' % fullname)
            raise e
        return sound
项目:pyweather    作者:rbischoff    | 项目源码 | 文件源码
def __get_driver(self):
        has_driver = False
        for driver in self._drivers:
            if not os.getenv('SDL_VIDEODRIVER'):
                os.putenv('SDL_VIDEODRIVER', driver)
            try:
                pygame.display.init()
            except pygame.error:
                print('Driver: {} not loaded.'.format(driver))
                continue
            print('Driver: {} used.'.format(driver))
            has_driver = True
            break

        if not has_driver:
            raise AssertionError('No video driver available for use!')
项目:picraftzero    作者:WayneKeenan    | 项目源码 | 文件源码
def _setup_video():
        "Ininitializes a new pygame screen using the framebuffer"
        # Based on "Python GUI in Linux frame buffer"
        # http://www.karoltomala.com/blog/?p=679
        disp_no = os.getenv("DISPLAY")

        # Check which frame buffer drivers are available
        # Start with fbcon since directfb hangs with composite output
        drivers = ['x11', 'fbcon', 'directfb', 'svgalib', 'Quartz']
        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:
                logger.error('Driver: {0} failed.'.format(driver))
                continue
            found = True
            break

        if not found:
            logger.error('No suitable SDL video driver found to start the event subsystem, pygame joysticks may not work.')
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def load_image(file):
    "loads an image, prepares it for play"
    file = os.path.join('data', file)
    try:
        surface = pygame.image.load(file)
    except pygame.error:
        raise SystemExit('Could not load image "%s" %s'%(file, pygame.get_error()))
    return surface.convert()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def load_sound(file):
    if not pygame.mixer: return dummysound()
    file = os.path.join('data', file)
    try:
        sound = pygame.mixer.Sound(file)
        return sound
    except pygame.error:
        print ('Warning, unable to load,', file)
    return dummysound()



# each type of game object gets an init and an
# update function. the update function is called
# once per frame, and it is when each object should
# change it's current position and state. the Player
# object actually gets a "move" function instead of
# update, since it is passed extra information about
# the keyboard
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def load_image(name, colorkey=None):
    fullname = os.path.join(data_dir, name)
    try:
        image = pygame.image.load(fullname)
    except pygame.error:
        print ('Cannot load image:', fullname)
        raise SystemExit(str(geterror()))
    image = image.convert()
    if colorkey is not None:
        if colorkey is -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey, RLEACCEL)
    return image, image.get_rect()
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def load_sound(name):
    class NoneSound:
        def play(self): pass
    if not pygame.mixer or not pygame.mixer.get_init():
        return NoneSound()
    fullname = os.path.join(data_dir, name)
    try:
        sound = pygame.mixer.Sound(fullname)
    except pygame.error:
        print ('Cannot load sound: %s' % fullname)
        raise SystemExit(str(geterror()))
    return sound


#classes for our game objects
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_quit(self):
        """ get_num_channels() Should throw pygame.error if uninitialized
        after mixer.quit() """

        mixer.init()
        mixer.quit()

        self.assertRaises (
            pygame.error, mixer.get_num_channels,
        )
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def setUp(self):
        pygame.cdrom.init()

        #TODO:
        try:
            self.cd = pygame.cdrom.CD(0)
        except pygame.error:
            self.cd = None
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_array(self):
        if not arraytype:
            self.fail("no array package installed")

        def check_array(size, channels, test_data):
            try:
                pygame.mixer.init(22050, size, channels)
            except pygame.error:
                # Not all sizes are supported on all systems.
                return
            try:
                __, sz, __ = pygame.mixer.get_init()
                if sz == size:
                    srcarr = array(test_data, self.array_dtypes[size])
                    snd = pygame.sndarray.make_sound(srcarr)
                    arr = pygame.sndarray.array(snd)
                    self._assert_compatible(arr, size)
                    self.failUnless(alltrue(arr == srcarr),
                                    "size: %i\n%s\n%s" %
                                    (size, arr, test_data))
            finally:
                pygame.mixer.quit()

        check_array(8, 1, [0, 0x0f, 0xf0, 0xff])
        check_array(8, 2,
                    [[0, 0x80], [0x2D, 0x41], [0x64, 0xA1], [0xff, 0x40]])
        check_array(16, 1, [0, 0x00ff, 0xff00, 0xffff])
        check_array(16, 2, [[0, 0xffff], [0xffff, 0],
                            [0x00ff, 0xff00], [0x0f0f, 0xf0f0]])
        check_array(-8, 1, [0, -0x80, 0x7f, 0x64])
        check_array(-8, 2,
                    [[0, -0x80], [-0x64, 0x64], [0x25, -0x50], [0xff, 0]])
        check_array(-16, 1, [0, 0x7fff, -0x7fff, -1])
        check_array(-16, 2, [[0, -0x7fff], [-0x7fff, 0],
                             [0x7fff, 0], [0, 0x7fff]])
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_make_sound(self):
        if not arraytype:
            self.fail("no array package installed")

        def check_sound(size, channels, test_data):
            try:
                pygame.mixer.init(22050, size, channels)
            except pygame.error:
                # Not all sizes are supported on all systems.
                return
            try:
                __, sz, __ = pygame.mixer.get_init()
                if sz == size:
                    srcarr = array(test_data, self.array_dtypes[size])
                    snd = pygame.sndarray.make_sound(srcarr)
                    arr = pygame.sndarray.samples(snd)
                    self.failUnless(alltrue(arr == srcarr),
                                    "size: %i\n%s\n%s" %
                                    (size, arr, test_data))
            finally:
                pygame.mixer.quit()

        check_sound(8, 1, [0, 0x0f, 0xf0, 0xff])
        check_sound(8, 2,
                    [[0, 0x80], [0x2D, 0x41], [0x64, 0xA1], [0xff, 0x40]])
        check_sound(16, 1, [0, 0x00ff, 0xff00, 0xffff])
        check_sound(16, 2, [[0, 0xffff], [0xffff, 0],
                            [0x00ff, 0xff00], [0x0f0f, 0xf0f0]])
        check_sound(-8, 1, [0, -0x80, 0x7f, 0x64])
        check_sound(-8, 2,
                    [[0, -0x80], [-0x64, 0x64], [0x25, -0x50], [0xff, 0]])
        check_sound(-16, 1, [0, 0x7fff, -0x7fff, -1])
        check_sound(-16, 2, [[0, -0x7fff], [-0x7fff, 0],
                             [0x7fff, 0], [0, 0x7fff]])
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_load_non_string_file(self):
        self.assertRaises(pygame.error, imageext.load_extended, [])
项目:Projects    作者:it2school    | 项目源码 | 文件源码
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)
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_load_bad_filename(self):
        u = as_unicode(r"a\x00b\x00c.png")
        self.assertRaises(pygame.error, imageext.load_extended, u)
项目:Projects    作者:it2school    | 项目源码 | 文件源码
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)
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def test_load_unknown_extension(self):
        s = "foo.bar"
        self.assertRaises(pygame.error, imageext.load_extended, s)
项目:Projects    作者:it2school    | 项目源码 | 文件源码
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))
项目:Projects    作者:it2school    | 项目源码 | 文件源码
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(), "")
项目:Projects    作者:it2school    | 项目源码 | 文件源码
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")
项目:code    作者:ActiveState    | 项目源码 | 文件源码
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
项目:PyCut    作者:FOSSRIT    | 项目源码 | 文件源码
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
项目:n1mm_view    作者:n1kdo    | 项目源码 | 文件源码
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
项目:n1mm_view    作者:n1kdo    | 项目源码 | 文件源码
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
项目:Pong-py    作者:alejandrogm90    | 项目源码 | 文件源码
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
项目:MDB    作者:gustavo-castro    | 项目源码 | 文件源码
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
项目:photobooth    作者:LoiX07    | 项目源码 | 文件源码
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
项目:wargame    作者:maximinus    | 项目源码 | 文件源码
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]
项目:wargame    作者:maximinus    | 项目源码 | 文件源码
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))
项目:wargame    作者:maximinus    | 项目源码 | 文件源码
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
项目:sudoku-solver    作者:dancodery    | 项目源码 | 文件源码
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()
项目:solarwolf    作者:pygame    | 项目源码 | 文件源码
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