def init(backend=None): global _is_init # select the camera module to import here. backends = [b.lower() for b in get_backends()] if not backends: raise error("No camera backends are supported on your platform!") backend = backends[0] if backend is None else backend.lower() if backend not in backends: warnings.warn( "We don't think this is a supported backend on this system, " "but we'll try it...", Warning, stacklevel=2, ) try: _setup_backend(backend) except ImportError: emsg = f"Backend '{backend}' is not supported on your platform!" if backend in ("opencv", "opencv-mac", "videocapture"): dep = "vidcap" if backend == "videocapture" else "OpenCV" emsg += ( f" Make sure you have '{dep}' installed to be able to use this backend" ) raise error(emsg) _is_init = True
def load(_filename): filepath = os.path.join(FileLoaderGraphic.DIR_PATH, _filename) try: surface = pygame.image.load(filepath) surface = surface.convert_alpha() return surface except: pygame.error("Failed to load '%s'" % filepath)
def _pre_init_placeholder(): if not _is_init: raise error("pygame.camera is not initialized") # camera was init, and yet functions are not monkey patched. This should # not happen raise NotImplementedError()
def __to_pygame_rect(self, rect, errormessage="Need a pygame.Rect or these rects"): if type(rect) != pRect: if type(rect) != Rect: raise error(errormessage + " (got '{}')".format(type(rect))) rect = pRect(rect.left, rect.top, rect.width, rect.height) return rect
def loadSound(filename): """ pygame.mixer.sound(filename) will fail silently - wtf? """ if os.path.isfile(filename): return pygame.mixer.Sound(filename) if os.path.isfile('virus/'+filename): return pygame.mixer.Sound('virus/'+filename) raise pygame.error("Sound "+filename+" does not exist.")
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 (buffer=array)
def _array_samples(sound, raw): # Info is a (freq, format, stereo) tuple info = mixer.get_init () if not info: raise pygame.error("Mixer not initialized") fmtbytes = (abs (info[1]) & 0xff) >> 3 channels = info[2] if raw: data = sound.get_buffer ().raw else: data = sound.get_buffer () shape = (len (data) // fmtbytes, ) if channels > 1: shape = (shape[0] // channels, channels) # mixer.init () does not support different formats from the ones below, # so MSB/LSB stuff is silently ignored. typecode = { 8 : numpy.uint8, # AUDIO_U8 16 : numpy.uint16, # AUDIO_U16 / AUDIO_U16SYS -8 : numpy.int8, # AUDIO_S8 -16 : numpy.int16 # AUDUI_S16 / AUDIO_S16SYS }[info[1]] array = numpy.fromstring (data, typecode) array.shape = shape return array
def samples (sound): """pygame._numpysndarray.samples(Sound): return array Reference Sound samples into an array. Creates a new array that directly references the samples in a Sound object. Modifying the array will change the Sound. The array will always be in the format returned from pygame.mixer.get_init(). """ # Info is a (freq, format, stereo) tuple info = pygame.mixer.get_init () if not info: raise pygame.error("Mixer not initialized") fmtbytes = (abs (info[1]) & 0xff) >> 3 channels = info[2] data = sound.get_buffer () shape = (data.length // fmtbytes, ) if channels > 1: shape = (shape[0] // channels, channels) # mixer.init () does not support different formats from the ones below, # so MSB/LSB stuff is silently ignored. typecode = { 8 : numpy.uint8, # AUDIO_U8 16 : numpy.uint16, # AUDIO_U16 -8 : numpy.int8, # AUDIO_S8 -16 : numpy.int16 # AUDUI_S16 }[info[1]] array = numpy.frombuffer (data, typecode) array.shape = shape return array
def download_image(self): try: self.image = pygame.transform.scale(pygame.image.load(self.path), (self.width, self.height)) return self.image except pygame.error: raise pygame.error("Images does not loaded!")
def get_right_axis(self): self.update_axis() if self.right_axis is not None: right = Vector(self.right_axis[0], self.right_axis[1]) return right else: raise pygame.error("right axis is 'None'")
def get_left_axis(self): self.update_axis() if self.left_axis is not None: left = Vector(self.left_axis[0], self.left_axis[1]) return left else: raise pygame.error("left axis is 'None'")
def samples(sound): """pygame._numpysndarray.samples(Sound): return array Reference Sound samples into an array. Creates a new array that directly references the samples in a Sound object. Modifying the array will change the Sound. The array will always be in the format returned from pygame.mixer.get_init(). """ # Info is a (freq, format, stereo) tuple info = pygame.mixer.get_init() if not info: raise pygame.error("Mixer not initialized") fmtbytes = (abs(info[1]) & 0xff) >> 3 channels = info[2] data = sound.get_buffer() shape = (data.length // fmtbytes, ) if channels > 1: shape = (shape[0] // channels, channels) # mixer.init () does not support different formats from the ones below, # so MSB/LSB stuff is silently ignored. typecode = { 8: numpy.uint8, # AUDIO_U8 16: numpy.uint16, # AUDIO_U16 -8: numpy.int8, # AUDIO_S8 -16: numpy.int16 # AUDUI_S16 }[info[1]] array = numpy.frombuffer(data, typecode) array.shape = shape return array
def _array_samples(sound, raw): # Info is a (freq, format, stereo) tuple info = mixer.get_init() if not info: raise pygame.error("Mixer not initialized") fmtbytes = (abs(info[1]) & 0xff) >> 3 channels = info[2] if raw: data = sound.get_buffer().raw else: data = sound.get_buffer() shape = (len(data) // fmtbytes, ) if channels > 1: shape = (shape[0] // channels, channels) # mixer.init () does not support different formats from the ones below, # so MSB/LSB stuff is silently ignored. typecode = { 8: numpy.uint8, # AUDIO_U8 16: numpy.uint16, # AUDIO_U16 / AUDIO_U16SYS -8: numpy.int8, # AUDIO_S8 -16: numpy.int16 # AUDUI_S16 / AUDIO_S16SYS }[info[1]] array = numpy.fromstring(data, typecode) array.shape = shape return array
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 main(): numpass, numfail = pg.init() print(f'pass:{numpass}, fail:{numfail}') inited = pg.get_init() print(f'Inited: {inited}') try: raise pg.error('Custom Error') except RuntimeError as re: print(f'Exception: {re}') pg.set_error('Set Error') err = pg.get_error() print(f'Error: {err}') major, minor, path = pg.get_sdl_version() print(f'SDL: {major}.{minor}.{path}') pg.register_quit(quit) unencoded = '你好' encoded = pg.encode_string(unencoded, encoding='utf-8') print(f'Encoded: {encoded}, Original: {unencoded}') encoded_path = pg.encode_file_path(os.path.join(__file__)) print(f'Encoded Path: {encoded_path}') print(f'{pg.version.PygameVersion(1, 2, 3)}, {pg.vernum}')
def __init__(self): self.createLogger() self.score_one = "0" self.score_two = "0" try: self.paused = pygame.image.load("img/pause2.png").convert_alpha() except pygame.error(), message: raise SystemExit, message
def __init__(self): # Load img, we need it here for size of img try: self.twob3_icon = pygame.image.load("img/2b3.png").convert() self.square = pygame.image.load("img/square3.png") # one case self.square2 = pygame.image.load("img/square.png") # one case self.square3 = pygame.image.load("img/square2.png") # one case self.tr = pygame.image.load("img/red.png") # Player 1 skin 1 self.rt = pygame.image.load( "img/red_t.png") # Player 1 transparency skin 1 self.tb = pygame.image.load("img/blue.png") # Player 2 skin 1 self.bt = pygame.image.load( "img/blue_t.png") # Player 2 transparency skin 1 self.tr2 = pygame.image.load("img/red2.png") # Player 1 skin 2 self.rt2 = pygame.image.load( "img/red2_t.png") # Player 1 transparency skin 2 self.tb2 = pygame.image.load("img/blue2.png") # Player 2 skin 2 self.bt2 = pygame.image.load( "img/blue2_t.png") # Player 2 transparency skin 2 self.tr3 = pygame.image.load("img/red3.png") # Player 1 skin 3 self.rt3 = pygame.image.load( "img/red3_t.png") # Player 1 transparency skin 3 self.tb3 = pygame.image.load("img/blue3.png") # Player 2 skin 3 self.bt3 = pygame.image.load( "img/blue3_t.png") # Player 2 transparency skin 3 self.md = pygame.image.load( "img/gomoku_menu_down.png").convert_alpha() # Menu down self.mu = pygame.image.load("img/gomoku_menu_up.png") # Menu up self.w1 = pygame.image.load( "img/samourai-player1.png").convert() # Win Player 1 self.w2 = pygame.image.load( "img/samourai-player2.png").convert() # Win Player 2 self.wia = pygame.image.load( "img/samourai-IA.png").convert() # Win IA self.turnp1 = pygame.image.load( "img/Menu/Player_one.png").convert_alpha() # Player 1 turn self.turnp1_s = pygame.image.load( "img/Menu/Player_one_s.png").convert_alpha() # Player 1 turn self.turnp2 = pygame.image.load( "img/Menu/Player_two.png").convert_alpha( ) # Player 2 / IA turn self.turnp2_s = pygame.image.load( "img/Menu/Player_two_s.png").convert_alpha( ) # Player 2 / IA turn self.sound_on = pygame.image.load("img/sound.png").convert_alpha() self.sound_off = pygame.image.load( "img/soundoff.png").convert_alpha() self.arrow_right_on = pygame.image.load( "img/arrow_right.png").convert_alpha() self.arrow_right_off = pygame.image.load( "img/arrow_right_off.png").convert_alpha() self.arrow_left_on = pygame.image.load( "img/arrow_left.png").convert_alpha() self.arrow_left_off = pygame.image.load( "img/arrow_left_off.png").convert_alpha() self.sound_play = 1 except pygame.error(), message: raise SystemExit, message
def load_image(name, surface, size=None, position=(0, 0)): try: image = pygame.image.load(name) except pygame.error() as message: #print("Cannot load image:", name) raise SystemExit from message if size is not None: image = smoothscale(image, size) surface.blit(image, position)
def __init__(self, position, *groups): if not self.init_flag: raise pg.error("Didn't initialize class before calling constructor") super().__init__(*groups) self.position = pg.Vector2(position) self.velocity = pg.Vector2() # Initialize to zero, unless set otherwise self.hitbox = pg.Rect(self.HITBOX).move(*position) self.rect = pg.Rect(self.RECT).move(*position) self.image = self.IMAGE self.health = self.MAX_HEALTH
def init(): """init() -> None initialize pygame.fastevent """ global _ft_init if not pygame.display.get_init(): raise error("video system not initialized") register_quit(_quit_hook) _ft_init = True
def poll_button(self, button: str) -> bool: """ Returns true is button <id> is pressed down :param button: Keyname for button :return: Boolean True is button pressed down """ try: return self.pressed[button] except KeyError: raise pg.error("Attempted polling of undefined key")
def imagen(filename, transparente=False): try: image = pygame.image.load(filename) except pygame.error(): if transparente: color = image.get_at((0, 0)) image.set_colorkey(color) return image
def __init__(self, game): self.game = game self.windows = [] self.event = [] if USE_FULLSCREEN==1: self.screen = pygame.display.set_mode((RESX, RESY), pygame.FULLSCREEN) else: self.screen = pygame.display.set_mode((RESX, RESY)) try: self.back_image = pygame.image.load("back.png") except pygame.error(), message: sys.exit()
def set_rect(self, **kwargs): """set the world location of the renderer's view rect""" # may be an opportunity here for a memoization performance gain to # keep tiles if the move does not select a new region del self._visible_tiles[:] for k in kwargs: if k not in self._allowed_rect: raise pygame.error('rect attribute not permitted: %s' % (k,)) setattr(self._rect, k, kwargs[k]) self.get_tiles() del self.dirty_rects[:]
def get_user_image(self): try: self.userPath = self.get_path_from_file() imageSize = self.get_kb_size_from_path(self.userPath) if (self.check_image_size(imageSize, lowerKbBound, upperKbBound)): return self.userPath else: raise pygame.error( "Image must be greater than 20 kb and less than 10 mb") except pygame.error: print(pygame.get_error())
def imagen(filename, transparent=False): 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) return image
def __init__(self): screen = pygame.display.set_mode((1280, 1024), DOUBLEBUF, 32) # Load pictures for the Menu try: self.main_bg = pygame.image.load("img/Menu/main_background.png").convert() self.play = pygame.image.load("img/Menu/play.png").convert_alpha() self.settings = pygame.image.load("img/Menu/settings.png").convert_alpha() self.quit = pygame.image.load("img/Menu/quit.png").convert_alpha() self.settings_bg = pygame.image.load("img/Menu/settings_background.png").convert() self.map_size = pygame.image.load("img/Menu/map_size.png").convert_alpha() self.up = pygame.image.load("img/Menu/up.png").convert_alpha() self.up_s = pygame.image.load("img/Menu/up_s.png").convert_alpha() self.down = pygame.image.load("img/Menu/down.png").convert_alpha() self.down_s = pygame.image.load("img/Menu/down_s.png").convert_alpha() self.rules = pygame.image.load("img/Menu/rules.png").convert_alpha() self.mode = pygame.image.load("img/Menu/mode.png").convert_alpha() self.double_3 = pygame.image.load("img/Menu/double three.png").convert_alpha() self.five_brk = pygame.image.load("img/Menu/five breakable.png").convert_alpha() self.capture = pygame.image.load("img/Menu/capture.png").convert_alpha() self.vs_ai = pygame.image.load("img/Menu/versus_AI.png").convert_alpha() self.two_players = pygame.image.load("img/Menu/2_players.png").convert_alpha() self.save = pygame.image.load("img/Menu/save.png").convert_alpha() self.go_back = pygame.image.load("img/Menu/go_back.png").convert_alpha() self.nb = [] self.nb.append(pygame.image.load("img/Menu/zero.png").convert_alpha()) self.nb.append(pygame.image.load("img/Menu/one.png").convert_alpha()) self.nb.append(pygame.image.load("img/Menu/two.png").convert_alpha()) self.nb.append(pygame.image.load("img/Menu/three.png").convert_alpha()) self.nb.append(pygame.image.load("img/Menu/four.png").convert_alpha()) self.nb.append(pygame.image.load("img/Menu/five.png").convert_alpha()) self.nb.append(pygame.image.load("img/Menu/six.png").convert_alpha()) self.nb.append(pygame.image.load("img/Menu/seven.png").convert_alpha()) self.nb.append(pygame.image.load("img/Menu/eight.png").convert_alpha()) self.nb.append(pygame.image.load("img/Menu/nine.png").convert_alpha()) self.nb_s = [] self.nb_s.append(pygame.image.load("img/Menu/zero_s.png").convert_alpha()) self.nb_s.append(pygame.image.load("img/Menu/one_s.png").convert_alpha()) self.nb_s.append(pygame.image.load("img/Menu/two_s.png").convert_alpha()) self.nb_s.append(pygame.image.load("img/Menu/three_s.png").convert_alpha()) self.nb_s.append(pygame.image.load("img/Menu/four_s.png").convert_alpha()) self.nb_s.append(pygame.image.load("img/Menu/five_s.png").convert_alpha()) self.nb_s.append(pygame.image.load("img/Menu/six_s.png").convert_alpha()) self.nb_s.append(pygame.image.load("img/Menu/seven_s.png").convert_alpha()) self.nb_s.append(pygame.image.load("img/Menu/eight_s.png").convert_alpha()) self.nb_s.append(pygame.image.load("img/Menu/nine_s.png").convert_alpha()) self.tick = pygame.image.load("img/Menu/tick.png").convert_alpha() except pygame.error(), message: raise SystemExit, message
def load_sound(self, name): class NoneSound: def play(self): pass if not pygame.mixer: return NoneSound() fullname = os.path.join(self.path, name) try: sound = pygame.mixer.Sound(fullname) except pygame.error(message): print("Cannot load sound:", wav) raise SystemExit(message) return sound
def imagen(filename, transparent=False): try: image = pygame.image.load(filename) except pygame.error(message): raise SystemExit(message) #AS imagens serão convertidas para um modo interior do python image = image.convert() if transparent: #Pega a cor da posição 0,0 e passa o RLEACCEL para tranparência color = image.get_at((0, 0)) image.set_colorkey(color, RLEACCEL) return image
def load_png(name): """ Load image and return image object""" fullname = os.path.join('data', name) try: image = pygame.image.load(fullname) if image.get_alpha is None: image = image.convert() else: image = image.convert_alpha() except pygame.error(message): print('Cannot load image:', fullname) raise SystemExit(message) return image, image.get_rect()
def load_image(filename, colorkey=None): filename = os.path.join("data", filename) try: image = pygame.image.load(filename) except pygame.error(message): print("Cannot Load image:", filename) raise SystemExit(message) 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
def load_png(name): '''load image and return image object''' fullname = os.path.join('images', name) try: image = pygame.image.load(fullname) if image.get_alpha() is None: image = image.convert() else: image = image.convert_alpha() except pygame.error(message): print("Cannot load image:", fullname) raise SystemExit(message) return image, image.get_rect()
def load_png(name): """ Load image and return image object """ #fullname = os.path.join("data", name) fullname = name try : image = pygame.image.load(fullname) if image.get_alpha() is None: image = image.convert() else: image = image.convert_alpha() except pygame.error(): print('Cannot load image:', fullname) raise SystemExit() return image, image.get_rect()
def download_tower(self): try: for x in range(self.load_index, self.load_index + self.number_of_imgs): add_str = str(x) self.images.append( pygame.transform.scale( pygame.image.load(self.path + self.identifier + add_str + ".png"), (self.image_size, self.image_size))) self.loaded = True except pygame.error: self.loaded = False raise pygame.error("Images does not loaded!")
def on_render(self): try: pygame.display.flip() w = (self.windowSize[1]/self.openingScreen.h()*.9) * self.openingScreen.w() self.openingScreen.resizeSurf = self.openingScreen.resize(int(w),int(self.windowSize[1])) self._display_surf.blit(self.openingScreen.resizeSurf, ((self.windowSize[0]/2 - self.openingScreen.resizeSurf.get_width()/2), self.openingScreen.position)) self._display_surf.get_width() self._display_surf.blit( self.Ascensiontitletext.text_surf, ((self._display_surf.get_width()/2 - self.openingScreen.resizeSurf.get_width()/2 + 15), 20)) self._display_surf.blit(self.startleveltext.text_surf, ((self.windowSize[0]/2 - self.openingScreen.resizeSurf.get_width()/2 + 15), self.Ascensiontitletext.text_surf.get_height()+15)) pygame.display.flip() except: print(pygame.error())
def imagem(filename, transparent=False): '''Se queres por tranparent o fundo da imagem passada, coloque dois argumentos ,um é a imagem e outro é True, com vírgula assim:("image.png",True)''' try: image = pygame.image.load(filename) except pygame.error(message): raise SystemExit(message) image = image.convert() if transparent: color = image.get_at( (0, 0)) #O RLEACCEL pegará a cor e retorna como transparent image.set_colorkey(color, RLEACCEL) return image
def load_pygame_image_file(image_path: str, **kwargs) -> 'pygame.Surface': """ Loads an image and returns a surface. :param image_path: Image file :param kwargs: Optional keyword arguments :return: Surface """ # Try to load the image try: if 'test' in kwargs.keys(): raise pygame.error('File is not a Windows BMP file') surface = pygame.image.load(image_path) except pygame.error as exc: # Check if file is not a Windows file if str(exc) == 'File is not a Windows BMP file': pil_invalid_exception = Exception # Check if Pillow exists try: # noinspection PyPackageRequirements from PIL import Image, UnidentifiedImageError pil_invalid_exception = UnidentifiedImageError img_pil = Image.open(image_path) # noinspection PyTypeChecker surface = pygame.image.fromstring(img_pil.tobytes(), img_pil.size, img_pil.mode).convert() except (ModuleNotFoundError, ImportError): warn( f'Image file "{image_path}" could not be loaded, as pygame.error ' f'is raised. To avoid this issue install the Pillow library' ) raise except pil_invalid_exception: warn( f'The image "{image_path}" could not be loaded using Pillow' ) raise else: raise return surface
def stop_audio(pin): my_logger.debug("stop all audio") #pygame.mixer.init() if pygame.mixer.music.get_busy() == True: try: pygame.mixer.music.fadeout(500) pygame.mixer.music.stop() except pygame.error(e): my_logger.debug("error" + e) pass else: my_logger.debug("no current audio playing, not stopping") # turn off the amplifier my_logger.debug("Turning off amp") GPIO.output(26, GPIO.HIGH)
def __init__(self, game): self.game = game self.windows = [] self.event = [] # drag & drop support self.oldmousepos = [-1, -1] self.oldposdragwindow = [-1, -1] self.drag_window = None if USE_FULLSCREEN==1: self.screen = pygame.display.set_mode((RESX, RESY), pygame.FULLSCREEN) else: self.screen = pygame.display.set_mode((RESX, RESY)) self.screen.set_colorkey(COLOR_TRANSPARENT) try: self.back_image = pygame.image.load("src/gui/back.png") except pygame.error(), message: sys.exit()
def load_image(name, colorkey=None): try: fullname = os.path.join(data_dir, name) image = pygame.image.load(fullname) except TypeError: raise pygame.error except pygame.error: print('Cannot load image:', fullname) raise pygame.error(str(geterror())) image = image.convert() if colorkey is not None: if colorkey == -1: colorkey = image.get_at((0, 0)) image.set_colorkey(colorkey, pygame.RLEACCEL) return image, image.get_rect()
def load_images(names, colorkey=None): images = [] for name in names: fullname = os.path.join('data', name) try: image = pygame.image.load(fullname) except: print 'Cannot load image:', name raise pygame.error(message) image = image.convert() if colorkey is not None: if colorkey is -1: colorkey = image.get_at((5,5)) image.set_colorkey(colorkey, RLEACCEL) images.append(image) return images
def loadMusic(self, key): match = False for e in self._soundexts: try: # Try loading this music lwith this extension pygame.mixer.music.load(os.path.join(PATH_MUSIC, "%s%s" % (key, e))) match = True except pygame.error: # If this sound couldn't be loaded with this extension, # it's probably because that wasn't the right extension. # Just keep on going and try other extensions continue # If no match was found at all, raise an error # stating that this sound file doesn't exist at all. if not match: raise pygame.error()
def init_joystick(joy_id=-1): """Initialize joysticks. This must be called before PyGame will start sending joystick events. If joy_id is -1 all joysticks will be intialized. The initialized joysticks are returned as a dict keyed by joystick id. """ joysticks = {} if joy_id in range(pygame.joystick.get_count()): joy_ids = [joy_id] elif joy_id == -1: joy_ids = range(pygame.joystick.get_count()) else: raise pygame.error('Invalid joystick device number: %d' % joy_id) for joy_id in joy_ids: joystick = pygame.joystick.Joystick(joy_id) joystick.init() joysticks[joy_id] = joystick return joysticks
def getSound(self, key): match = False if not key in self._sounds: # Go through the allowed extensions for sound files. for e in self._soundexts: try: # Try loading this sound with this extension self._sounds[key] = pygame.mixer.Sound(\ os.path.join(PATH_SOUNDS, "%s%s" % (key, e))) # If that worked, we have our match match = True except pygame.error: # If this sound couldn't be loaded with this extension, # it's probably because that wasn't the right extension. # Just keep on going and try other extensions continue # If no match was found at all, raise an error # stating that this sound file doesn't exist at all. if not match: raise pygame.error() return self._sounds[key]
def init(): """Initialise the screen and game screen, and set default options. """ try: flags = 0 if options.fullscreen(): flags |= FULLSCREEN # flags |= RESIZABLE # initialise the screen global screen screen = pygame.display.set_mode(options.dimensions(), flags) # initialise the game_screen global game_screen game_screen = pygame.Surface(options.game_dimensions()) pygame.mouse.set_visible(False) pygame.display.update() except pygame.error as msg: raise pygame.error("Failed to initialize render engine {0}".format(str(msg)))
def load_image(self, name, colorkey=None, scale=1,): fullname = os.path.join(self.path, name) try: image = pygame.image.load(fullname) except pygame.error(message): print("Cannot load image:", name) raise SystemExit(message) # Apply color key image = image.convert() if colorkey is not None: if colorkey is -1: colorkey = image.get_at((0,0)) image.set_colorkey(colorkey, RLEACCEL) # Scale image if scale == 2: image = pygame.transform.scale2x(image) elif scale > 2: width = image.get_width()* scale height = image.get_height() * scale image = pygame.transform.smoothscale(image, (width, height)) return image
def get_events(self): "yields all un-processed events" if not self.active(): raise pygame.error("PyGame object is no longer active") for event in pygame.event.get(): yield event
def _render_end(self): if not self.active(): raise pygame.error("PyGame object is no longer active") pygame.display.flip() self._drawing = False
def _render_begin(self): if not self.active(): raise pygame.error("PyGame object is no longer active") self._surf.fill(self._bg_color) self._drawing = True
map_opt = pygame.image.load("img/Menu/map_opt.png").convert_alpha() map_opt_s = pygame.image.load("img/Menu/map_opt_selected.png").convert_alpha() level1 = pygame.image.load("img/Menu/level1.png").convert_alpha() level1_s = pygame.image.load("img/Menu/level1_selected.png").convert_alpha() level2 = pygame.image.load("img/Menu/level2.png").convert_alpha() level2_s = pygame.image.load("img/Menu/level2_selected.png").convert_alpha() tracking = pygame.image.load("img/Menu/tracking.png").convert_alpha() tracking_s = pygame.image.load("img/Menu/tracking_selected.png").convert_alpha() yes = pygame.image.load("img/Menu/yes.png").convert_alpha() yes_s = pygame.image.load("img/Menu/yes_selected.png").convert_alpha() no = pygame.image.load("img/Menu/No.png").convert_alpha() no_s = pygame.image.load("img/Menu/No_selected.png").convert_alpha() go_back = pygame.image.load("img/Menu/go_back.png").convert_alpha() go_back_s = pygame.image.load("img/Menu/go_back_selected.png").convert_alpha() except pygame.error(), message: raise SystemExit, message try: with open('score', 'r+') as file_score: line = file_score.readline().rstrip('\n') if (line != ""): game.score_one = line line = file_score.readline().rstrip('\n') if (line != ""): game.score_two = line except IOError, message: print message #Launch menu loop menu = 0
def __init__(self, screen, rect, functions={}, key_calls={}, vars={}, syntax={}, localsx=None): if not pygame.display.get_init(): raise pygame.error("Display not initialized. Initialize the display before creating a Console") if not pygame.font.get_init(): pygame.font.init() self.parent_screen = screen self.rect = pygame.Rect(rect) self.size = self.rect.size self.user_vars = vars self.user_syntax = syntax self.user_namespace = {} self.__locals=localsx self.variables = {\ "bg_alpha":int,\ "bg_color": list,\ "txt_color_i": list,\ "txt_color_o": list,\ "ps1": str,\ "ps2": str,\ "ps3": str,\ "active": bool,\ "repeat_rate": list,\ "preserve_events":bool,\ "python_mode":bool,\ "motd":list } self.load_cfg() self.set_interpreter() pygame.key.set_repeat(*self.repeat_rate) self.bg_layer = pygame.Surface(self.size) self.bg_layer.set_alpha(self.bg_alpha) self.txt_layer = pygame.Surface(self.size) self.txt_layer.set_colorkey(self.bg_color) try: self.font = pygame.font.Font(os.path.join(font_path,"default.ttf"), 14) except IOError: self.font = pygame.font.SysFont("monospace", 14) self.font_height = self.font.get_linesize() self.max_lines = (self.size[HEIGHT] / self.font_height) - 1 self.max_chars = (self.size[WIDTH]/(self.font.size(ascii_letters)[WIDTH]/len(ascii_letters))) - 1 self.txt_wrapper = textwrap.TextWrapper() self.c_out = self.motd self.c_hist = [""] self.c_hist_pos = 0 self.c_in = "" self.c_pos = 0 self.c_draw_pos = 0 self.c_scroll = 0 self.changed = True self.func_calls = {} self.key_calls = {} self.add_func_calls({"echo":self.output, "clear": self.clear, "help":self.help}) self.add_func_calls(functions) self.add_key_calls({"l":self.clear, "c":self.clear_input, "w":self.set_active}) self.add_key_calls(key_calls)
def __init__(self, filename): try: self.sheet = pygame.image.load(filename).convert() except pygame.error(message): print ('Unable to load spritesheet image:' + filename) raise SystemExit(message)
def load_pgm(filename, rgb_mapper=grayscale_gradient, little_endian=False): """Load PGM and return pygame.Surface. This is only needed for 16-bit PGM formats, which pygame does not support. Return None for non-16-bit PGMs. >>> pgm0 = load_pgm('test/16_bit_ascii.pgm') >>> pgm0.get_size() (24, 7) >>> pgm1 = load_pgm('test/16_bit_ascii_without_comments.pgm') >>> (pygame.image.tostring(pgm0, 'RGB') == ... pygame.image.tostring(pgm1, 'RGB')) True >>> pgm_binary0 = load_pgm('test/16_bit_binary.pgm') >>> pgm_binary0.get_size() (20, 100) >>> load_pgm('test/8_bit_binary.pgm') is None True """ with open(filename, mode='rb') as input_file: file_contents = input_file.read() result = re.search(MAGIC_REGEX + 3 * NUMBER_REGEX, file_contents) if not result: return None magic_id = result.group(1) size = (int(result.group(2)), int(result.group(3))) max_value = int(result.group(4)) raw_data = file_contents[result.end():] if max_value <= 255: return None expected_length = size[0] * size[1] if magic_id == b'P2': byte_array = [ int(value) for value in re.sub(COMMENT_REGEX, b' ', raw_data).split() ][:expected_length] elif magic_id == b'P5': byte_array = array.array('H') # Ignore any junk at the end of the file. byte_array.fromstring(raw_data[:2 * expected_length]) if sys.byteorder != ('little' if little_endian else 'big'): byte_array.byteswap() else: # This cannot happen since we would have raised an exception on not # matching the regular expression. assert False if len(byte_array) < expected_length: raise pygame.error('file truncated') data = bytearray(rgb_mapper(byte_array, max_value)) return pygame.image.frombuffer(data, size, 'RGB')
from __future__ import print_function import pygame as pg from pygame.locals import * '''Prepares the game by handling pygame initialization, loading graphics, loading sounds, animations, fps, and so on.''' results = pg.init() if results[1] > 0: print("Could not initialize all needed pygame modules, will try \ to initialize them manually and report any errors") try: pg.mixer.init() pg.display.init() except pg.error, message: raise pg.error("Could not load one or more modules : {}").format(message) SCREEN_X = 800 SCREEN_Y = 600 SCREEN = pg.display.set_mode((SCREEN_X, SCREEN_Y)) CAPTION = "asteroids clone" pg.display.set_caption(CAPTION) SCREEN_RECT = SCREEN.get_rect() CLOCK = pg.time.Clock() # Define some game variables current_level = 1 ENEMY_ROWS = 4 ENEMY_COLS = 7 ENEMY_VEL_X = 20 ENEMY_VEL_Y = 40