Beispiel #1
0
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
Beispiel #2
0
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
Beispiel #3
0
 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'")
Beispiel #4
0
 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'")
Beispiel #5
0
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.")
Beispiel #6
0
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 __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 
Beispiel #8
0
	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()
Beispiel #9
0
    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 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[:]
Beispiel #11
0
 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
Beispiel #12
0
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()
Beispiel #13
0
	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()
Beispiel #14
0
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]
Beispiel #18
0
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)))
Beispiel #19
0
 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
Beispiel #20
0
 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
Beispiel #21
0
        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
Beispiel #22
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)
Beispiel #23
0
 def __init__(self, filename):
     try:
         self.sheet = pygame.image.load(filename).convert()
     except pygame.error(message):
         print ('Unable to load spritesheet image:' + filename)
         raise SystemExit(message)
Beispiel #24
0
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')
Beispiel #25
0
 def _render_end(self):
     if not self.active():
         raise pygame.error("PyGame object is no longer active")
     pygame.display.flip()
     self._drawing = False
Beispiel #26
0
 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
Beispiel #27
0
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