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
python类error()的实例源码
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
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
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(), "")
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)
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)
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)
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
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]
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]
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()
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()
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
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
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)
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
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
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
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(), "")
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
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!')
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.')
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()
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
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()
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
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,
)
def setUp(self):
pygame.cdrom.init()
#TODO:
try:
self.cd = pygame.cdrom.CD(0)
except pygame.error:
self.cd = None
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]])
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]])