def test_load_non_string_file(self):
self.assertRaises(pygame.error, imageext.load_extended, [])
python类error()的实例源码
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)
def test_load_bad_filename(self):
u = as_unicode(r"a\x00b\x00c.png")
self.assertRaises(pygame.error, imageext.load_extended, u)
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)
def test_load_unknown_extension(self):
s = "foo.bar"
self.assertRaises(pygame.error, imageext.load_extended, s)
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))
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(), "")
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")
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
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
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
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
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
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
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
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]
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))
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
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()
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