Commits

aholkner  committed 0f3a0f7

  • Participants
  • Parent commits ec9dd15
  • Branches ctypes-soc

Comments (0)

Files changed (68)

File SDL/video.py

             return None
         raise AttributeError
 
+    def __copy__(self):
+        f = SDL_PixelFormat()
+        f._palette = self._palette
+        f.BitsPerPixel = self.BitsPerPixel
+        f.BytesPerPixel = self.BytesPerPixel
+        f.Rloss = self.Rloss
+        f.Gloss = self.Gloss
+        f.Bloss = self.Bloss
+        f.Aloss = self.Aloss
+        f.Rshift = self.Rshift
+        f.Gshift = self.Gshift
+        f.Bshift = self.Bshift
+        f.Ashift = self.Ashift
+        f.Rmask = self.Rmask
+        f.Gmask = self.Gmask
+        f.Bmask = self.Bmask
+        f.Amask = self.Amask
+        f.colorkey = self.colorkey
+        f.alpha = self.alpha
+        return f
+
 class SDL_Surface(Structure):
     '''Read-only surface structure.
 
     '''
     title, icon = c_char_p(), c_char_p()
     _SDL_WM_GetCaption(byref(title), byref(icon))
-    return title.value.decode('utf-8'), icon.value.decode('utf-8')
+
+    if title.value:
+        title = title.value.decode('utf-8')
+    else:
+        title = None
+
+    if icon.value:
+        icon = icon.value.decode('utf-8')
+    else:
+        icon = None
+    return title, icon
 
 _SDL_WM_SetIcon = SDL.dll.private_function('SDL_WM_SetIcon',
     arg_types=[POINTER(SDL_Surface), POINTER(c_ubyte)],

File examples_pygame/aliens.py

+#! /usr/bin/env python
+
+import random, os.path
+
+#import basic pygame modules
+import pygame
+from pygame.locals import *
+
+#see if we can load more than standard BMP
+if not pygame.image.get_extended():
+    raise SystemExit, "Sorry, extended image module required"
+
+
+#game constants
+MAX_SHOTS      = 2      #most player bullets onscreen
+ALIEN_ODDS     = 22     #chances a new alien appears
+BOMB_ODDS      = 60    #chances a new bomb will drop
+ALIEN_RELOAD   = 12     #frames between new aliens
+SCREENRECT     = Rect(0, 0, 640, 480)
+SCORE          = 0
+
+
+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_images(*files):
+    imgs = []
+    for file in files:
+        imgs.append(load_image(file))
+    return imgs
+
+
+class dummysound:
+    def play(self): pass
+
+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
+
+
+class Player(pygame.sprite.Sprite):
+    speed = 10
+    bounce = 24
+    gun_offset = -11
+    images = []
+    def __init__(self):
+        pygame.sprite.Sprite.__init__(self, self.containers)
+        self.image = self.images[0]
+        self.rect = self.image.get_rect(midbottom=SCREENRECT.midbottom)
+        self.reloading = 0
+        self.origtop = self.rect.top
+        self.facing = -1
+
+    def move(self, direction):
+        if direction: self.facing = direction
+        self.rect.move_ip(direction*self.speed, 0)
+        self.rect = self.rect.clamp(SCREENRECT)
+        if direction < 0:
+            self.image = self.images[0]
+        elif direction > 0:
+            self.image = self.images[1]
+        self.rect.top = self.origtop - (self.rect.left/self.bounce%2)
+
+    def gunpos(self):
+        pos = self.facing*self.gun_offset + self.rect.centerx
+        return pos, self.rect.top
+
+
+class Alien(pygame.sprite.Sprite):
+    speed = 13
+    animcycle = 12
+    images = []
+    def __init__(self):
+        pygame.sprite.Sprite.__init__(self, self.containers)
+        self.image = self.images[0]
+        self.rect = self.image.get_rect()
+        self.facing = random.choice((-1,1)) * Alien.speed
+        self.frame = 0
+        if self.facing < 0:
+            self.rect.right = SCREENRECT.right
+
+    def update(self):
+        self.rect.move_ip(self.facing, 0)
+        if not SCREENRECT.contains(self.rect):
+            self.facing = -self.facing;
+            self.rect.top = self.rect.bottom + 1
+            self.rect = self.rect.clamp(SCREENRECT)
+        self.frame = self.frame + 1
+        self.image = self.images[self.frame/self.animcycle%3]
+
+
+class Explosion(pygame.sprite.Sprite):
+    defaultlife = 12
+    animcycle = 3
+    images = []
+    def __init__(self, actor):
+        pygame.sprite.Sprite.__init__(self, self.containers)
+        self.image = self.images[0]
+        self.rect = self.image.get_rect(center=actor.rect.center)
+        self.life = self.defaultlife
+
+    def update(self):
+        self.life = self.life - 1
+        self.image = self.images[self.life/self.animcycle%2]
+        if self.life <= 0: self.kill()
+
+
+class Shot(pygame.sprite.Sprite):
+    speed = -11
+    images = []
+    def __init__(self, pos):
+        pygame.sprite.Sprite.__init__(self, self.containers)
+        self.image = self.images[0]
+        self.rect = self.image.get_rect(midbottom=pos)
+
+    def update(self):
+        self.rect.move_ip(0, self.speed)
+        if self.rect.top <= 0:
+            self.kill()
+
+
+class Bomb(pygame.sprite.Sprite):
+    speed = 9
+    images = []
+    def __init__(self, alien):
+        pygame.sprite.Sprite.__init__(self, self.containers)
+        self.image = self.images[0]
+        self.rect = self.image.get_rect(midbottom=
+                    alien.rect.move(0,5).midbottom)
+
+    def update(self):
+        self.rect.move_ip(0, self.speed)
+        if self.rect.bottom >= 470:
+            Explosion(self)
+            self.kill()
+
+
+class Score(pygame.sprite.Sprite):
+    def __init__(self):
+        pygame.sprite.Sprite.__init__(self)
+        self.font = pygame.font.Font(None, 20)
+        self.font.set_italic(1)
+        self.color = Color('white')
+        self.lastscore = -1
+        self.update()
+        self.rect = self.image.get_rect().move(10, 450)
+
+    def update(self):
+        if SCORE != self.lastscore:
+            self.lastscore = SCORE
+            msg = "Score: %d" % SCORE
+            self.image = self.font.render(msg, 0, self.color)
+
+
+
+def main(winstyle = 0):
+    # Initialize pygame
+    pygame.init()
+    if pygame.mixer and not pygame.mixer.get_init():
+        print 'Warning, no sound'
+        pygame.mixer = None
+
+    # Set the display mode
+    winstyle = 0  # |FULLSCREEN
+    bestdepth = pygame.display.mode_ok(SCREENRECT.size, winstyle, 32)
+    screen = pygame.display.set_mode(SCREENRECT.size, winstyle, bestdepth)
+
+    #Load images, assign to sprite classes
+    #(do this before the classes are used, after screen setup)
+    img = load_image('player1.gif')
+    Player.images = [img, pygame.transform.flip(img, 1, 0)]
+    img = load_image('explosion1.gif')
+    Explosion.images = [img, pygame.transform.flip(img, 1, 1)]
+    Alien.images = load_images('alien1.gif', 'alien2.gif', 'alien3.gif')
+    Bomb.images = [load_image('bomb.gif')]
+    Shot.images = [load_image('shot.gif')]
+
+    #decorate the game window
+    icon = pygame.transform.scale(Alien.images[0], (32, 32))
+    pygame.display.set_icon(icon)
+    pygame.display.set_caption('Pygame Aliens')
+    pygame.mouse.set_visible(0)
+
+    #create the background, tile the bgd image
+    bgdtile = load_image('background.gif')
+    background = pygame.Surface(SCREENRECT.size)
+    for x in range(0, SCREENRECT.width, bgdtile.get_width()):
+        background.blit(bgdtile, (x, 0))
+    screen.blit(background, (0,0))
+    pygame.display.flip()
+
+    #load the sound effects
+    boom_sound = load_sound('boom.wav')
+    shoot_sound = load_sound('car_door.wav')
+    if pygame.mixer:
+        music = os.path.join('data', 'house_lo.wav')
+        pygame.mixer.music.load(music)
+        pygame.mixer.music.play(-1)
+
+    # Initialize Game Groups
+    aliens = pygame.sprite.Group()
+    shots = pygame.sprite.Group()
+    bombs = pygame.sprite.Group()
+    all = pygame.sprite.RenderUpdates()
+    lastalien = pygame.sprite.GroupSingle()
+
+    #assign default groups to each sprite class
+    Player.containers = all
+    Alien.containers = aliens, all, lastalien
+    Shot.containers = shots, all
+    Bomb.containers = bombs, all
+    Explosion.containers = all
+    Score.containers = all
+
+    #Create Some Starting Values
+    global score
+    alienreload = ALIEN_RELOAD
+    kills = 0
+    clock = pygame.time.Clock()
+
+    #initialize our starting sprites
+    global SCORE
+    player = Player()
+    Alien() #note, this 'lives' because it goes into a sprite group
+    if pygame.font:
+        all.add(Score())
+
+
+    while player.alive():
+
+        #get input
+        for event in pygame.event.get():
+            if event.type == QUIT or \
+                (event.type == KEYDOWN and event.key == K_ESCAPE):
+                    return
+        keystate = pygame.key.get_pressed()
+
+        # clear/erase the last drawn sprites
+        all.clear(screen, background)
+
+        #update all the sprites
+        all.update()
+
+        #handle player input
+        direction = keystate[K_RIGHT] - keystate[K_LEFT]
+        player.move(direction)
+        firing = keystate[K_SPACE]
+        if not player.reloading and firing and len(shots) < MAX_SHOTS:
+            Shot(player.gunpos())
+            shoot_sound.play()
+        player.reloading = firing
+
+        # Create new alien
+        if alienreload:
+            alienreload = alienreload - 1
+        elif not int(random.random() * ALIEN_ODDS):
+            Alien()
+            alienreload = ALIEN_RELOAD
+
+        # Drop bombs
+        if lastalien and not int(random.random() * BOMB_ODDS):
+            Bomb(lastalien.sprite)
+
+        # Detect collisions
+        for alien in pygame.sprite.spritecollide(player, aliens, 1):
+            boom_sound.play()
+            Explosion(alien)
+            Explosion(player)
+            SCORE = SCORE + 1
+            player.kill()
+
+        for alien in pygame.sprite.groupcollide(shots, aliens, 1, 1).keys():
+            boom_sound.play()
+            Explosion(alien)
+            SCORE = SCORE + 1
+
+        for bomb in pygame.sprite.spritecollide(player, bombs, 1):
+            boom_sound.play()
+            Explosion(player)
+            Explosion(bomb)
+            player.kill()
+
+        #draw the scene
+        dirty = all.draw(screen)
+        pygame.display.update(dirty)
+
+        #cap the framerate
+        clock.tick(40)
+
+    if pygame.mixer:
+        pygame.mixer.music.fadeout(1000)
+    pygame.time.wait(1000)
+
+
+
+#call the "main" function if running this script
+if __name__ == '__main__': main()
+

File examples_pygame/arraydemo.py

+#!/usr/bin/env python
+
+import os
+try:
+    import pygame
+    import Numeric as N
+    from pygame.locals import *
+    surfarray = pygame.surfarray
+    if not surfarray: raise ImportError
+except ImportError:
+    raise ImportError, 'Error Importing Pygame/surfarray or Numeric'
+
+
+pygame.init()
+print 'Press the mouse button to advance image.'
+print 'Press the "s" key to save the current image.'
+
+
+def surfdemo_show(array_img, name):
+    "displays a surface, waits for user to continue"
+    screen = pygame.display.set_mode(array_img.shape[:2], 0, 32)
+    surfarray.blit_array(screen, array_img)
+    pygame.display.flip()
+    pygame.display.set_caption(name)
+    while 1:
+        e = pygame.event.wait()
+        if e.type == MOUSEBUTTONDOWN: break
+        elif e.type == KEYDOWN and e.key == K_s:
+            #pygame.image.save(screen, name+'.bmp')
+            #s = pygame.Surface(screen.get_size(), 0, 32)
+            #s = s.convert_alpha()
+            #s.fill((0,0,0,255))
+            #s.blit(screen, (0,0))
+            #s.fill((222,0,0,50), (0,0,40,40))
+            #pygame.image.save_extended(s, name+'.png')
+            #pygame.image.save(s, name+'.png')
+            #pygame.image.save(screen, name+'_screen.png')
+            #pygame.image.save(s, name+'.tga')
+            pygame.image.save(screen, name+'.png')
+        elif e.type == QUIT: raise SystemExit
+
+
+
+
+#allblack
+allblack = N.zeros((128, 128))
+surfdemo_show(allblack, 'allblack')
+
+
+#striped
+striped = N.zeros((128, 128, 3))
+striped[:] = (255, 0, 0)
+striped[:,::3] = (0, 255, 255)
+surfdemo_show(striped, 'striped')
+
+
+#imgarray
+imagename = os.path.join('data', 'arraydemo.bmp')
+imgsurface = pygame.image.load(imagename)
+imgarray = surfarray.array2d(imgsurface)
+surfdemo_show(imgarray, 'imgarray')
+
+
+#flipped
+flipped = imgarray[:,::-1]
+surfdemo_show(flipped, 'flipped')
+
+
+#scaledown
+scaledown = imgarray[::2,::2]
+surfdemo_show(scaledown, 'scaledown')
+
+
+#scaleup
+size = N.array(imgarray.shape)*2
+scaleup = N.zeros(size)
+scaleup[::2,::2] = imgarray
+scaleup[1::2,::2] = imgarray
+scaleup[:,1::2] = scaleup[:,::2]
+surfdemo_show(scaleup, 'scaleup')
+
+
+#redimg
+rgbarray = surfarray.array3d(imgsurface)
+redimg = N.array(rgbarray)
+redimg[:,:,1:] = 0
+surfdemo_show(redimg, 'redimg')
+
+
+#soften
+soften = N.array(rgbarray)*1
+soften[1:,:]  += rgbarray[:-1,:]*8
+soften[:-1,:] += rgbarray[1:,:]*8
+soften[:,1:]  += rgbarray[:,:-1]*8
+soften[:,:-1] += rgbarray[:,1:]*8
+soften /= 33
+surfdemo_show(soften, 'soften')
+
+
+#crossfade (50%)
+src = N.array(rgbarray)
+dest = N.zeros(rgbarray.shape)
+dest[:] = 20, 50, 100
+diff = (dest - src) * 0.50
+xfade = src + diff.astype(N.Int)
+surfdemo_show(xfade, 'xfade')
+
+
+
+#alldone

File examples_pygame/blit_blends.py

+#!/usr/bin/env python
+
+# fake additive blending.  Using Numeric.  it doesn't clamp.
+# press r,g,b
+
+import os, pygame
+from pygame.locals import *
+
+try:
+    import pygame.surfarray
+    import Numeric
+except:
+    print "no surfarray for you!  install Numeric"
+
+import time
+        
+
+def main():
+    pygame.init()
+    screen = pygame.display.set_mode((640, 480))
+
+    im1= pygame.Surface(screen.get_size())
+    #im1= im1.convert()
+    im1.fill((100, 0, 0))
+
+    
+
+    im2= pygame.Surface(screen.get_size())
+    im2.fill((0, 50, 0))
+    # we make a srcalpha copy of it.
+    #im3= im2.convert(SRCALPHA)
+    im3 = im2
+    im3.set_alpha(127)
+
+    images = {}
+    images[K_1] = im2
+    images[K_2] = pygame.image.load(os.path.join("data", "chimp.bmp"))
+    images[K_3] = pygame.image.load(os.path.join("data", "alien3.gif"))
+    images[K_4] = pygame.image.load(os.path.join("data", "liquid.bmp"))
+    img_to_blit = im2.convert()
+    iaa = img_to_blit.convert_alpha()
+
+
+
+    blits = {}
+    blits[K_a] = BLEND_ADD
+    blits[K_s] = BLEND_SUB
+    blits[K_m] = BLEND_MULT
+    blits[K_EQUALS] = BLEND_MAX
+    blits[K_MINUS] = BLEND_MIN
+
+
+    screen.blit(im1, (0, 0))
+    pygame.display.flip()
+    clock = pygame.time.Clock()
+    print "one pixel is:%s:" % [im1.get_at((0,0))]
+    
+    while 1:
+        clock.tick(60)
+
+        for event in pygame.event.get():
+            if event.type == QUIT:
+                return
+            if event.type == KEYDOWN:
+                usage()
+
+            if event.type == KEYDOWN and event.key == K_ESCAPE:
+                return
+
+            elif event.type == KEYDOWN and event.key in images.keys():
+                img_to_blit = images[event.key]
+                iaa = img_to_blit.convert_alpha()
+
+            elif event.type == KEYDOWN and event.key in blits.keys():
+                t1 = time.time()
+                # blits is a dict keyed with key -> blit flag.  eg BLEND_ADD.
+                im1.blit(img_to_blit, (0,0), None, blits[event.key])
+                t2 = time.time()
+                print "one pixel is:%s:" % [im1.get_at((0,0))]
+                print "time to do:%s:" % (t2-t1)
+
+            elif event.type == KEYDOWN and event.key in [K_o]:
+                t1 = time.time()
+                # blits is a dict keyed with key -> blit flag.  eg BLEND_ADD.
+                im1.blit(iaa, (0,0))
+                t2 = time.time()
+                print "one pixel is:%s:" % [im1.get_at((0,0))]
+                print "time to do:%s:" % (t2-t1)
+
+
+            elif event.type == KEYDOWN and event.key == K_SPACE:
+                # this additive blend without clamp two surfaces.
+                #im1.set_alpha(127)
+                #im1.blit(im1, (0,0))
+                #im1.set_alpha(255)
+                t1 = time.time()
+
+                im1p = pygame.surfarray.pixels2d(im1)
+                im2p = pygame.surfarray.pixels2d(im2)
+                im1p += im2p
+                del im1p
+                del im2p
+                t2 = time.time()
+                print "one pixel is:%s:" % [im1.get_at((0,0))]
+                print "time to do:%s:" % (t2-t1)
+
+            elif event.type == KEYDOWN and event.key in [K_z]:
+                t1 = time.time()
+                im1p = pygame.surfarray.pixels3d(im1)
+                im2p = pygame.surfarray.pixels3d(im2)
+                im1p16 = im1p.astype(Numeric.UInt16)
+                im2p16 = im1p.astype(Numeric.UInt16)
+                im1p16 += im2p16
+                im1p16 = Numeric.minimum(im1p16, 255)
+                pygame.surfarray.blit_array(im1, im1p16)
+
+                del im1p
+                del im2p
+                t2 = time.time()
+                print "one pixel is:%s:" % [im1.get_at((0,0))]
+                print "time to do:%s:" % (t2-t1)
+
+            elif event.type == KEYDOWN and event.key in [K_r, K_g, K_b]:
+                # this adds one to each pixel.
+                colmap={}
+                colmap[K_r] = 0x10000
+                colmap[K_g] = 0x00100
+                colmap[K_b] = 0x00001
+                im1p = pygame.surfarray.pixels2d(im1)
+                im1p += colmap[event.key]
+                del im1p
+                print "one pixel is:%s:" % [im1.get_at((0,0))]
+
+            elif event.type == KEYDOWN and event.key == K_p:
+                print "one pixel is:%s:" % [im1.get_at((0,0))]
+
+
+
+
+
+            elif event.type == KEYDOWN and event.key == K_f:
+                # this additive blend without clamp two surfaces.
+
+                t1 = time.time()
+                im1.set_alpha(127)
+                im1.blit(im2, (0,0))
+                im1.set_alpha(255)
+
+                t2 = time.time()
+                print "one pixel is:%s:" % [im1.get_at((0,0))]
+                print "time to do:%s:" % (t2-t1)
+
+
+        screen.blit(im1, (0, 0))
+        pygame.display.flip()
+
+def usage():
+    print "press keys 1-5 to change image to blit."
+    print "A - ADD, S- SUB, M- MULT, - MIN, + MAX"
+
+if __name__ == '__main__': 
+    usage()
+    main()

File examples_pygame/chimp.py

+#!/usr/bin/env python
+"""
+This simple example is used for the line-by-line tutorial
+that comes with pygame. It is based on a 'popular' web banner.
+Note there are comments here, but for the full explanation, 
+follow along in the tutorial.
+"""
+
+
+#Import Modules
+import os, pygame
+from pygame.locals import *
+
+if not pygame.font: print 'Warning, fonts disabled'
+if not pygame.mixer: print 'Warning, sound disabled'
+
+
+#functions to create our resources
+def load_image(name, colorkey=None):
+    fullname = os.path.join('data', name)
+    try:
+        image = pygame.image.load(fullname)
+    except pygame.error, message:
+        print 'Cannot load image:', fullname
+        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, 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', name)
+    try:
+        sound = pygame.mixer.Sound(fullname)
+    except pygame.error, message:
+        print 'Cannot load sound:', fullname
+        raise SystemExit, message
+    return sound
+        
+
+#classes for our game objects
+class Fist(pygame.sprite.Sprite):
+    """moves a clenched fist on the screen, following the mouse"""
+    def __init__(self):
+        pygame.sprite.Sprite.__init__(self) #call Sprite initializer
+        self.image, self.rect = load_image('fist.bmp', -1)
+        self.punching = 0
+
+    def update(self):
+        "move the fist based on the mouse position"
+        pos = pygame.mouse.get_pos()
+        self.rect.midtop = pos
+        if self.punching:
+            self.rect.move_ip(5, 10)
+
+    def punch(self, target):
+        "returns true if the fist collides with the target"
+        if not self.punching:
+            self.punching = 1
+            hitbox = self.rect.inflate(-5, -5)
+            return hitbox.colliderect(target.rect)
+
+    def unpunch(self):
+        "called to pull the fist back"
+        self.punching = 0
+
+
+class Chimp(pygame.sprite.Sprite):
+    """moves a monkey critter across the screen. it can spin the
+       monkey when it is punched."""
+    def __init__(self):
+        pygame.sprite.Sprite.__init__(self) #call Sprite intializer
+        self.image, self.rect = load_image('chimp.bmp', -1)
+        screen = pygame.display.get_surface()
+        self.area = screen.get_rect()
+        self.rect.topleft = 10, 10
+        self.move = 9
+        self.dizzy = 0
+
+    def update(self):
+        "walk or spin, depending on the monkeys state"
+        if self.dizzy:
+            self._spin()
+        else:
+            self._walk()
+
+    def _walk(self):
+        "move the monkey across the screen, and turn at the ends"
+        newpos = self.rect.move((self.move, 0))
+        if self.rect.left < self.area.left or \
+            self.rect.right > self.area.right:
+            self.move = -self.move
+            newpos = self.rect.move((self.move, 0))
+            self.image = pygame.transform.flip(self.image, 1, 0)
+        self.rect = newpos
+
+    def _spin(self):
+        "spin the monkey image"
+        center = self.rect.center
+        self.dizzy = self.dizzy + 12
+        if self.dizzy >= 360:
+            self.dizzy = 0
+            self.image = self.original
+        else:
+            rotate = pygame.transform.rotate
+            self.image = rotate(self.original, self.dizzy)
+        self.rect = self.image.get_rect(center=center)
+
+    def punched(self):
+        "this will cause the monkey to start spinning"
+        if not self.dizzy:
+            self.dizzy = 1
+            self.original = self.image
+        
+
+def main():
+    """this function is called when the program starts.
+       it initializes everything it needs, then runs in
+       a loop until the function returns."""
+#Initialize Everything
+    pygame.init()
+    screen = pygame.display.set_mode((468, 60))
+    pygame.display.set_caption('Monkey Fever')
+    pygame.mouse.set_visible(0)
+
+#Create The Backgound
+    background = pygame.Surface(screen.get_size())
+    background = background.convert()
+    background.fill((250, 250, 250))
+    
+#Put Text On The Background, Centered
+    if pygame.font:
+        font = pygame.font.Font(None, 36)
+        text = font.render("Pummel The Chimp, And Win $$$", 1, (10, 10, 10))
+        textpos = text.get_rect(centerx=background.get_width()/2)
+        background.blit(text, textpos)
+
+#Display The Background
+    screen.blit(background, (0, 0))
+    pygame.display.flip()
+    
+#Prepare Game Objects
+    clock = pygame.time.Clock()
+    whiff_sound = load_sound('whiff.wav')
+    punch_sound = load_sound('punch.wav')
+    chimp = Chimp()
+    fist = Fist()
+    allsprites = pygame.sprite.RenderPlain((fist, chimp))
+    
+#Main Loop
+    while 1:
+        clock.tick(60)
+
+    #Handle Input Events
+        for event in pygame.event.get():
+            if event.type == QUIT:
+                return
+            elif event.type == KEYDOWN and event.key == K_ESCAPE:
+                return
+            elif event.type == MOUSEBUTTONDOWN:
+                if fist.punch(chimp):
+                    punch_sound.play() #punch
+                    chimp.punched()
+                else:
+                    whiff_sound.play() #miss
+            elif event.type == MOUSEBUTTONUP:
+                fist.unpunch()
+
+        allsprites.update()
+
+    #Draw Everything
+        screen.blit(background, (0, 0))
+        allsprites.draw(screen)
+        pygame.display.flip()
+
+#Game Over
+
+
+#this calls the 'main' function when this script is executed
+if __name__ == '__main__': main()

File examples_pygame/cursors.py

+
+import pygame
+
+
+arrow = ( "xX                      ",
+          "X.X                     ",
+          "X..X                    ",
+          "X...X                   ",
+          "X....X                  ",
+          "X.....X                 ",
+          "X......X                ",
+          "X.......X               ",
+          "X........X              ",
+          "X.........X             ",
+          "X......XXXXX            ",
+          "X...X..X                ",
+          "X..XX..X                ",
+          "X.X XX..X               ",
+          "XX   X..X               ",
+          "X     X..X              ",
+          "      X..X              ",
+          "       X..X             ",
+          "       X..X             ",
+          "        XX              ",
+          "                        ",
+          "                        ",
+          "                        ",
+          "                        ")
+
+
+no = ("                        ",
+         "                        ",
+         "         XXXXXX         ",
+         "       XX......XX       ",
+         "      X..........X      ",
+         "     X....XXXX....X     ",
+         "    X...XX    XX...X    ",
+         "   X.....X      X...X   ",
+         "   X..X...X      X..X   ",
+         "  X...XX...X     X...X  ",
+         "  X..X  X...X     X..X  ",
+         "  X..X   X...X    X..X  ",
+         "  X..X    X.,.X   X..X  ",
+         "  X..X     X...X  X..X  ",
+         "  X...X     X...XX...X  ",
+         "   X..X      X...X..X   ",
+         "   X...X      X.....X   ",
+         "    X...XX     X...X    ",
+         "     X....XXXXX...X     ",
+         "      X..........X      ",
+         "       XX......XX       ",
+         "         XXXXXX         ",
+         "                        ",
+         "                        ",
+        )
+
+def TestCursor(arrow):
+    hotspot = None
+    for y in range(len(arrow)):
+        for x in range(len(arrow[y])):
+            if arrow[y][x] in ['x', ',', 'O']:
+                hotspot = x,y
+                break
+        if hotspot != None:
+            break
+    if hotspot == None:
+        raise Exception("No hotspot specified for cursor '%s'!" %
+cursorname)
+    s2 = []
+    for line in arrow:
+        s2.append(line.replace('x', 'X').replace(',', '.').replace('O',
+'o'))
+    cursor, mask = pygame.cursors.compile(s2, 'X', '.', 'o')
+    size = len(arrow[0]), len(arrow)
+    pygame.mouse.set_cursor(size, hotspot, cursor, mask)
+
+def main():
+    pygame.init()
+    pygame.font.init()
+    font = pygame.font.Font(None, 24)
+    bg = pygame.display.set_mode((800, 600), 0, 24)
+    bg.fill((255,255,255))
+    bg.blit(font.render("Click to advance", 1, (0, 0, 0)), (0, 0))
+    pygame.display.update()
+    for cursor in [no, arrow]:
+        TestCursor(cursor)
+        quit = 0
+        while not quit:
+            pygame.event.pump()
+            for e in pygame.event.get():
+                if e.type == pygame.MOUSEBUTTONDOWN:
+                    quit = 1
+    pygame.quit()
+
+main()
+

File examples_pygame/data/alien1.gif

Added
New image

File examples_pygame/data/alien2.gif

Added
New image

File examples_pygame/data/alien3.gif

Added
New image

File examples_pygame/data/arraydemo.bmp

Added
New image

File examples_pygame/data/asprite.bmp

Added
New image

File examples_pygame/data/background.gif

Added
New image

File examples_pygame/data/bomb.gif

Added
New image

File examples_pygame/data/boom.wav

Binary file added.

File examples_pygame/data/car_door.wav

Binary file added.

File examples_pygame/data/chimp.bmp

Added
New image

File examples_pygame/data/danger.gif

Added
New image

File examples_pygame/data/explosion1.gif

Added
New image

File examples_pygame/data/fist.bmp

Added
New image

File examples_pygame/data/house_lo.wav

Binary file added.

File examples_pygame/data/liquid.bmp

Added
New image

File examples_pygame/data/oldplayer.gif

Added
New image

File examples_pygame/data/player1.gif

Added
New image

File examples_pygame/data/punch.wav

Binary file added.

File examples_pygame/data/secosmic_lo.wav

Binary file added.

File examples_pygame/data/shot.gif

Added
New image

File examples_pygame/data/whiff.wav

Binary file added.

File examples_pygame/data/yuv_1.pgm

Added
New image

File examples_pygame/eventlist.py

+
+"""Eventlist is a sloppy style of pygame, but is a handy
+tool for learning about pygame events and input. At the
+top of the screen are the state of several device values,
+and a scrolling list of events are displayed on the bottom.
+
+This is not quality 'ui' code at all, but you can see how
+to implement very non-interactive status displays, or even
+a crude text output control.
+"""
+
+from pygame import *
+
+ImgOnOff = []
+Font = None
+LastKey = None
+
+def showtext(win, pos, text, color, bgcolor):
+    textimg = Font.render(text, 1, color, bgcolor)
+    win.blit(textimg, pos)
+    return pos[0] + textimg.get_width() + 5, pos[1]
+
+
+def drawstatus(win):
+    bgcolor = 50, 50, 50
+    win.fill(bgcolor, (0, 0, 640, 120))
+    win.blit(Font.render('Status Area', 1, (155, 155, 155), bgcolor), (2, 2))
+
+    pos = showtext(win, (10, 30), 'Mouse Focus', (255, 255, 255), bgcolor)
+    win.blit(ImgOnOff[mouse.get_focused()], pos)
+
+    pos = showtext(win, (330, 30), 'Keyboard Focus', (255, 255, 255), bgcolor)
+    win.blit(ImgOnOff[key.get_focused()], pos)
+
+    pos = showtext(win, (10, 60), 'Mouse Position', (255, 255, 255), bgcolor)
+    p = '%s, %s' % mouse.get_pos()
+    pos = showtext(win, pos, p, bgcolor, (255, 255, 55))
+
+    pos = showtext(win, (330, 60), 'Last Keypress', (255, 255, 255), bgcolor)
+    if LastKey:
+        p = '%d, %s' % (LastKey, key.name(LastKey))
+    else:
+        p = 'None'
+    pos = showtext(win, pos, p, bgcolor, (255, 255, 55))
+
+    pos = showtext(win, (10, 90), 'Input Grabbed', (255, 255, 255), bgcolor)
+    win.blit(ImgOnOff[event.get_grab()], pos)
+
+
+def drawhistory(win, history):
+    win.blit(Font.render('Event History Area', 1, (155, 155, 155), (0,0,0)), (2, 132))
+    ypos = 450
+    h = list(history)
+    h.reverse()
+    for line in h:
+        r = win.blit(line, (10, ypos))
+        win.fill(0, (r.right, r.top, 620, r.height))
+        ypos -= Font.get_height()
+
+
+def main():
+    init()
+
+    win = display.set_mode((640, 480), RESIZABLE)
+    display.set_caption("Mouse Focus Workout")
+
+    global Font
+    Font = font.Font(None, 26)
+
+    global ImgOnOff
+    ImgOnOff.append(Font.render("Off", 1, (0, 0, 0), (255, 50, 50)))
+    ImgOnOff.append(Font.render("On", 1, (0, 0, 0), (50, 255, 50)))
+
+    history = []
+
+    #let's turn on the joysticks just so we can play with em
+    for x in range(joystick.get_count()):
+        j = joystick.Joystick(x)
+        j.init()
+        txt = 'Enabled joystick: ' + j.get_name()
+        img = Font.render(txt, 1, (50, 200, 50), (0, 0, 0))
+        history.append(img)
+    if not joystick.get_count():
+        img = Font.render('No Joysticks to Initialize', 1, (50, 200, 50), (0, 0, 0))
+        history.append(img)
+
+    while 1:
+        for e in event.get():
+            if e.type == QUIT:
+                return
+            if e.type == KEYDOWN:
+                if e.key == K_ESCAPE:
+                    return
+                else:
+                    global LastKey
+                    LastKey = e.key
+            if e.type == MOUSEBUTTONDOWN:
+                event.set_grab(1)
+            elif e.type == MOUSEBUTTONUP:
+                event.set_grab(0)
+            if e.type == VIDEORESIZE:
+                win = display.set_mode(e.size, RESIZABLE)
+
+            if e.type != MOUSEMOTION:
+                txt = '%s: %s' % (event.event_name(e.type), e.dict)
+                img = Font.render(txt, 1, (50, 200, 50), (0, 0, 0))
+                history.append(img)
+                history = history[-13:]
+
+
+        drawstatus(win)
+        drawhistory(win, history)
+
+        display.flip()
+        time.wait(10)
+
+
+
+if __name__ == '__main__': main()

File examples_pygame/fastevents.py

+"""  This is a stress test for the fastevents module.
+
+*Fast events does not appear faster!*
+
+So far it looks like normal pygame.event is faster by up to two times.
+So maybe fastevent isn't fast at all.
+
+Tested on windowsXP sp2 athlon, and freebsd.
+
+However... on my debian duron 850 machine fastevents is faster.
+"""
+from pygame import *
+
+# the config to try different settings out with the event queues.
+
+# use the fastevent module or not.
+use_fast_events = 1
+
+# use pygame.display.flip().
+#    otherwise we test raw event processing throughput.
+with_display = 1
+
+# limit the game loop to 40 fps.
+slow_tick = 0
+
+NUM_EVENTS_TO_POST = 200000
+
+
+
+if use_fast_events:
+    event_module = fastevent
+else:
+    event_module = event
+
+
+
+
+from threading import Thread
+
+class post_them(Thread):
+    def __init__(self):
+        Thread.__init__(self)
+        self.done = []
+        self.stop = []
+
+    def run(self):
+        self.done = []
+        self.stop = []
+        for x in range(NUM_EVENTS_TO_POST):
+            ee = event.Event(USEREVENT)
+            try_post = 1
+
+            # the pygame.event.post raises an exception if the event
+            #   queue is full.  so wait a little bit, and try again.
+            while try_post:
+                try:
+                    event_module.post(ee)
+                    try_post = 0
+                except:
+                    pytime.sleep(0.001)
+                    try_post = 1
+                
+            if self.stop:
+                return
+        self.done.append(1)
+        
+        
+
+import time as pytime
+
+def main():
+    init()
+    
+    if use_fast_events:
+        fastevent.init()
+
+    c = time.Clock()
+
+    win = display.set_mode((640, 480), RESIZABLE)
+    display.set_caption("fastevent Workout")
+
+    poster = post_them()
+
+    t1 = pytime.time()
+    poster.start()
+
+
+    while 1:
+#        for e in event.get():
+        #for x in range(200):
+        #    ee = event.Event(USEREVENT)
+        #    r = event_module.post(ee)
+        #    print r
+        
+        #for e in event_module.get():
+        event_list = []
+        event_list = event_module.get()
+
+        for e in event_list:
+            if e.type == QUIT:
+                print c.get_fps()
+                poster.stop.append(1)
+                return
+            if e.type == KEYDOWN:
+                if e.key == K_ESCAPE:
+                    print c.get_fps()
+                    poster.stop.append(1)
+                    return
+        if poster.done:
+            print c.get_fps()
+            print c
+            t2 = pytime.time()
+            print "total time:%s" % (t2 - t1)
+            print "events/second:%s" % (NUM_EVENTS_TO_POST / (t2 - t1))
+            return
+        if with_display:
+            display.flip()
+        if slow_tick:
+            c.tick(40)
+        
+        
+
+
+
+
+if __name__ == '__main__': main()

File examples_pygame/fonty.py

+#!/usr/bin/env python
+
+"""Here we load a .TTF font file, and display it in
+a basic pygame window. It demonstrates several of the
+Font object attributes. Nothing exciting in here, but
+it makes a great example for basic window, event, and
+font management."""
+
+
+import pygame
+from pygame.locals import *
+
+
+def main():
+    #initialize
+    pygame.init()
+    resolution = 400, 200
+    screen = pygame.display.set_mode(resolution)
+
+    #the python 1.5.2 way to set the cursor
+    apply(pygame.mouse.set_cursor, pygame.cursors.diamond)
+    #the python 2.0 way to set the cursor
+    #pygame.mouse.set_cursor(*pygame.cursors.diamond)
+
+    fg = 250, 240, 230
+    bg = 5, 5, 5
+    wincolor = 40, 40, 90
+
+    #fill background
+    screen.fill(wincolor)
+
+    #load font, prepare values
+    font = pygame.font.Font(None, 80)
+    text = 'Fonty'
+    size = font.size(text)
+
+    #no AA, no transparancy, normal
+    ren = font.render(text, 0, fg, bg)
+    screen.blit(ren, (10, 10))
+
+    #no AA, transparancy, underline
+    font.set_underline(1)
+    ren = font.render(text, 0, fg)
+    screen.blit(ren, (10, 40 + size[1]))
+    font.set_underline(0)
+
+
+    a_sys_font = pygame.font.SysFont("Arial", 60)
+
+
+    #AA, no transparancy, bold
+    a_sys_font.set_bold(1)
+    ren = a_sys_font.render(text, 1, fg, bg)
+    screen.blit(ren, (30 + size[0], 10))
+    a_sys_font.set_bold(0)
+
+    #AA, transparancy, italic
+    a_sys_font.set_italic(1)
+    ren = a_sys_font.render(text, 1, fg)
+    screen.blit(ren, (30 + size[0], 40 + size[1]))
+    a_sys_font.set_italic(0)
+
+
+    ##some_japanese_unicode = u"\u304b\u3070\u306b"
+    
+    #AA, transparancy, italic
+    ##ren = a_sys_font.render(some_japanese_unicode, 1, fg)
+    ##screen.blit(ren, (30 + size[0], 40 + size[1]))
+    
+
+
+
+
+    #show the surface and await user quit
+    pygame.display.flip()
+    while 1:
+        #use event.wait to keep from polling 100% cpu
+        if pygame.event.wait().type in (QUIT, KEYDOWN, MOUSEBUTTONDOWN):
+            break
+
+
+
+if __name__ == '__main__': main()
+    

File examples_pygame/glcube.py

+#!/usr/bin/env python
+
+"""Draw a cube on the screen. every frame we orbit
+the camera around by a small amount and it appears
+the object is spinning. note i've setup some simple
+data structures here to represent a multicolored cube,
+we then go through a semi-unopimized loop to draw
+the cube points onto the screen. opengl does all the
+hard work for us. :]
+"""
+
+import pygame
+from pygame.locals import *
+
+try:
+    from OpenGL.GL import *
+    from OpenGL.GLU import *
+except:
+    print 'The GLCUBE example requires PyOpenGL'
+    raise SystemExit
+
+
+
+#some simple data for a colored cube
+#here we have the 3D point position and color
+#for each corner. then we have a list of indices
+#that describe each face, and a list of indieces
+#that describes each edge
+
+
+CUBE_POINTS = (
+    (0.5, -0.5, -0.5),  (0.5, 0.5, -0.5),
+    (-0.5, 0.5, -0.5),  (-0.5, -0.5, -0.5),
+    (0.5, -0.5, 0.5),   (0.5, 0.5, 0.5),
+    (-0.5, -0.5, 0.5),  (-0.5, 0.5, 0.5)
+)
+
+#colors are 0-1 floating values
+CUBE_COLORS = (
+    (1, 0, 0), (1, 1, 0), (0, 1, 0), (0, 0, 0),
+    (1, 0, 1), (1, 1, 1), (0, 0, 1), (0, 1, 1)
+)
+
+CUBE_QUAD_VERTS = (
+    (0, 1, 2, 3), (3, 2, 7, 6), (6, 7, 5, 4),
+    (4, 5, 1, 0), (1, 5, 7, 2), (4, 0, 3, 6)
+)
+
+CUBE_EDGES = (
+    (0,1), (0,3), (0,4), (2,1), (2,3), (2,7),
+    (6,3), (6,4), (6,7), (5,1), (5,4), (5,7),
+)
+
+
+
+def drawcube():
+    "draw the cube"
+    allpoints = zip(CUBE_POINTS, CUBE_COLORS)
+
+    glBegin(GL_QUADS)
+    for face in CUBE_QUAD_VERTS:
+        for vert in face:
+            pos, color = allpoints[vert]
+            glColor3fv(color)
+            glVertex3fv(pos)
+    glEnd()
+
+    glColor3f(1.0, 1.0, 1.0)
+    glBegin(GL_LINES)
+    for line in CUBE_EDGES:
+        for vert in line:
+            pos, color = allpoints[vert]
+            glVertex3fv(pos)
+
+    glEnd()
+
+
+def main():
+    "run the demo"
+    #initialize pygame and setup an opengl display
+    pygame.init()
+    pygame.display.set_mode((640,480), OPENGL|DOUBLEBUF)
+    glEnable(GL_DEPTH_TEST)        #use our zbuffer
+
+    #setup the camera
+    glMatrixMode(GL_PROJECTION)
+    gluPerspective(45.0,640/480.0,0.1,100.0)    #setup lens
+    glTranslatef(0.0, 0.0, -3.0)                #move back
+    glRotatef(25, 1, 0, 0)                       #orbit higher
+
+
+    while 1:
+        #check for quit'n events
+        event = pygame.event.poll()
+        if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
+            break
+
+        #clear screen and move camera
+        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
+
+        #orbit camera around by 1 degree
+        glRotatef(1, 0, 1, 0)                    
+
+        drawcube()
+        pygame.display.flip()
+        pygame.time.wait(10)
+
+
+if __name__ == '__main__': main()

File examples_pygame/liquid.py

+#!/usr/bin/env python
+
+"""This examples demonstrates a simplish water effect of an
+image. It attempts to create a hardware display surface that
+can use pageflipping for faster updates. Note that the colormap
+from the loaded GIF image is copied to the colormap for the
+display surface.
+
+This is based on the demo named F2KWarp by Brad Graham of Freedom2000
+done in BlitzBasic. I was just translating the BlitzBasic code to
+pygame to compare the results. I didn't bother porting the text and
+sound stuff, that's an easy enough challenge for the reader :]"""
+
+import pygame, os
+from pygame.locals import *
+from math import sin
+
+def main():
+    #initialize and setup screen
+    pygame.init()
+    screen = pygame.display.set_mode((640, 480), HWSURFACE|DOUBLEBUF)
+
+    #load image and quadruple
+    imagename = os.path.join('data', 'liquid.bmp')
+    bitmap = pygame.image.load(imagename)
+    bitmap = pygame.transform.scale2x(bitmap)
+    bitmap = pygame.transform.scale2x(bitmap)
+
+    #get the image and screen in the same format
+    if screen.get_bitsize() == 8:
+        screen.set_palette(bitmap.get_palette())
+    else:
+        bitmap = bitmap.convert()
+
+    #prep some variables
+    anim = 0.0
+
+    #mainloop
+    xblocks = range(0, 640, 20)
+    yblocks = range(0, 480, 20)
+    stopevents = QUIT, KEYDOWN, MOUSEBUTTONDOWN
+    while 1:
+        for e in pygame.event.get():
+            if e.type in stopevents:
+                return
+
+        anim = anim + 0.2
+        for x in xblocks:
+            xpos = (x + (sin(anim + x * .01) * 15)) + 20
+            for y in yblocks:
+                ypos = (y + (sin(anim + y * .01) * 15)) + 20
+                screen.blit(bitmap, (x, y), (xpos, ypos, 20, 20))
+
+        pygame.display.flip()
+
+
+if __name__ == '__main__': main()
+
+
+
+"""BTW, here is the code from the BlitzBasic example this was derived
+from. i've snipped the sound and text stuff out.
+-----------------------------------------------------------------
+; Brad@freedom2000.com
+
+; Load a bmp pic (800x600) and slice it into 1600 squares
+Graphics 640,480
+SetBuffer BackBuffer()
+bitmap$="f2kwarp.bmp"
+pic=LoadAnimImage(bitmap$,20,15,0,1600)
+
+; use SIN to move all 1600 squares around to give liquid effect
+Repeat
+f=0:w=w+10:If w=360 Then w=0
+For y=0 To 599 Step 15
+For x = 0 To 799 Step 20
+f=f+1:If f=1600 Then f=0
+DrawBlock pic,(x+(Sin(w+x)*40))/1.7+80,(y+(Sin(w+y)*40))/1.7+60,f
+Next:Next:Flip:Cls
+Until KeyDown(1)
+"""

File examples_pygame/macosx/aliens_app_example/English.lproj/MainMenu.nib/JavaCompiling.plist

+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>JavaSourceSubpath</key>
+	<string>_MainMenu_EOArchive_English.java</string>
+</dict>
+</plist>

File examples_pygame/macosx/aliens_app_example/English.lproj/MainMenu.nib/_MainMenu_EOArchive_English.java

+// _MainMenu_EOArchive_English.java
+// Generated by EnterpriseObjects palette at Tuesday, March 2, 2004 8:45:51 PM America/New_York
+
+import com.webobjects.eoapplication.*;
+import com.webobjects.eocontrol.*;
+import com.webobjects.eointerface.*;
+import com.webobjects.eointerface.swing.*;
+import com.webobjects.foundation.*;
+import javax.swing.*;
+
+public class _MainMenu_EOArchive_English extends com.webobjects.eoapplication.EOArchive {
+    PygameAppDelegate _pygameAppDelegate0;
+
+    public _MainMenu_EOArchive_English(Object owner, NSDisposableRegistry registry) {
+        super(owner, registry);
+    }
+
+    protected void _construct() {
+        Object owner = _owner();
+        EOArchive._ObjectInstantiationDelegate delegate = (owner instanceof EOArchive._ObjectInstantiationDelegate) ? (EOArchive._ObjectInstantiationDelegate)owner : null;
+        Object replacement;
+
+        super._construct();
+
+
+        if ((delegate != null) && ((replacement = delegate.objectForOutletPath(this, "delegate")) != null)) {
+            _pygameAppDelegate0 = (replacement == EOArchive._ObjectInstantiationDelegate.NullObject) ? null : (PygameAppDelegate)replacement;
+            _replacedObjects.setObjectForKey(replacement, "_pygameAppDelegate0");
+        } else {
+            _pygameAppDelegate0 = (PygameAppDelegate)_registered(new PygameAppDelegate(), "PygameAppDelegate");
+        }
+    }
+
+    protected void _awaken() {
+        super._awaken();
+        .addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(_owner(), "unhideAllApplications", ), ""));
+        .addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(_owner(), "hide", ), ""));
+        .addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(_owner(), "hideOtherApplications", ), ""));
+        .addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(_owner(), "orderFrontStandardAboutPanel", ), ""));
+
+        if (_replacedObjects.objectForKey("_pygameAppDelegate0") == null) {
+            _connect(_owner(), _pygameAppDelegate0, "delegate");
+        }
+
+        .addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(_owner(), "terminate", ), ""));
+    }
+
+    protected void _init() {
+        super._init();
+        .addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(null, "undo", ), ""));
+        .addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(null, "paste", ), ""));
+        .addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(null, "arrangeInFront", ), ""));
+        .addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(null, "copy", ), ""));
+        .addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(null, "showHelp", ), ""));
+        .addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(null, "clearRecentDocuments", ), ""));
+        .addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(null, "selectAll", ), ""));
+        .addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(null, "performMiniaturize", ), ""));
+        .addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(null, "toggleContinuousSpellChecking", ), ""));
+        .addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(null, "print", ), ""));
+        .addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(null, "cut", ), ""));
+        .addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(null, "runPageLayout", ), ""));
+        .addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(null, "checkSpelling", ), ""));
+        .addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(null, "delete", ), ""));
+        .addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(null, "redo", ), ""));
+        .addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(null, "performClose", ), ""));
+        .addActionListener((com.webobjects.eointerface.swing.EOControlActionAdapter)_registered(new com.webobjects.eointerface.swing.EOControlActionAdapter(null, "showGuessPanel", ), ""));
+    }
+}

File examples_pygame/macosx/aliens_app_example/English.lproj/MainMenu.nib/classes.nib

+{
+    IBClasses = (
+        {CLASS = FirstResponder; LANGUAGE = ObjC; SUPERCLASS = NSObject; }, 
+        {
+            ACTIONS = {}; 
+            CLASS = PygameAppDelegate; 
+            LANGUAGE = ObjC; 
+            OUTLETS = {}; 
+            SUPERCLASS = NSObject; 
+        }
+    ); 
+    IBVersion = 1; 
+}

File examples_pygame/macosx/aliens_app_example/English.lproj/MainMenu.nib/info.nib

+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>IBDocumentLocation</key>
+	<string>269 494 356 240 0 0 1600 1002 </string>
+	<key>IBEditorPositions</key>
+	<dict>
+		<key>29</key>
+		<string>125 344 278 44 0 0 1600 1002 </string>
+	</dict>
+	<key>IBFramework Version</key>
+	<string>349.0</string>
+	<key>IBOpenObjects</key>
+	<array>
+		<integer>29</integer>
+	</array>
+	<key>IBSystem Version</key>
+	<string>7D24</string>
+</dict>
+</plist>

File examples_pygame/macosx/aliens_app_example/English.lproj/MainMenu.nib/keyedobjects.nib

Binary file added.

File examples_pygame/macosx/aliens_app_example/English.lproj/aliens.icns

Binary file added.

File examples_pygame/macosx/aliens_app_example/README.txt

+*********************************************************************
+ THESE INSTRUCTIONS ARE ONLY FOR MAC OS X 10.3, AND WILL ONLY CREATE 
+ STANDALONE BUNDLES FOR MAC OS X 10.3.  THERE IS NO SUPPORT FOR 
+ MAC OS X 10.2.
+*********************************************************************
+
+You will need the following packages installed to use this example:
+    macholib v2.0a0 or later
+        http://undefined.org/python/#macholib
+        (or http://undefined.org/python/macholib-v2.0a0.tgz if not listed)
+
+    PyProtocols v0.9.2 or later
+        http://peak.telecommunity.com/PyProtocols.html
+        
+    Both of these should eventually be in the PackageManager repository at:
+        http://undefined.org/python/pimp/
+
+To create the bundle:
+    pythonw ./buildapp.py --semi-standalone build

File examples_pygame/macosx/aliens_app_example/aliens.py

+#! /usr/bin/env python
+
+import random, os.path
+
+#import basic pygame modules
+import pygame
+from pygame.locals import *
+
+#see if we can load more than standard BMP
+if not pygame.image.get_extended():
+    raise SystemExit, "Sorry, extended image module required"
+
+
+#game constants
+MAX_SHOTS      = 2      #most player bullets onscreen
+ALIEN_ODDS     = 22     #chances a new alien appears
+BOMB_ODDS      = 60    #chances a new bomb will drop
+ALIEN_RELOAD   = 12     #frames between new aliens
+SCREENRECT     = Rect(0, 0, 640, 480)
+SCORE          = 0
+
+
+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_images(*files):
+    imgs = []
+    for file in files:
+        imgs.append(load_image(file))
+    return imgs
+
+
+class dummysound:
+    def play(self): pass
+
+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
+
+
+class Player(pygame.sprite.Sprite):
+    speed = 10
+    bounce = 24
+    gun_offset = -11
+    images = []
+    def __init__(self):
+        pygame.sprite.Sprite.__init__(self, self.containers)
+        self.image = self.images[0]
+        self.rect = self.image.get_rect()
+        self.reloading = 0
+        self.rect.centerx = SCREENRECT.centerx
+        self.rect.bottom = SCREENRECT.bottom - 1
+        self.origtop = self.rect.top
+        self.facing = -1
+
+    def move(self, direction):
+        if direction: self.facing = direction
+        self.rect.move_ip(direction*self.speed, 0)
+        self.rect = self.rect.clamp(SCREENRECT)
+        if direction < 0:
+            self.image = self.images[0]
+        elif direction > 0:
+            self.image = self.images[1]
+        self.rect.top = self.origtop - (self.rect.left/self.bounce%2)
+
+    def gunpos(self):
+        pos = self.facing*self.gun_offset + self.rect.centerx
+        return pos, self.rect.top
+
+
+class Alien(pygame.sprite.Sprite):
+    speed = 13
+    animcycle = 12
+    images = []
+    def __init__(self):
+        pygame.sprite.Sprite.__init__(self, self.containers)
+        self.image = self.images[0]
+        self.rect = self.image.get_rect()
+        self.facing = random.choice((-1,1)) * Alien.speed
+        self.frame = 0
+        if self.facing < 0:
+            self.rect.right = SCREENRECT.right
+
+    def update(self):
+        self.rect.move_ip(self.facing, 0)
+        if not SCREENRECT.contains(self.rect):
+            self.facing = -self.facing;
+            self.rect.top = self.rect.bottom + 1
+            self.rect = self.rect.clamp(SCREENRECT)
+        self.frame = self.frame + 1
+        self.image = self.images[self.frame/self.animcycle%3]
+
+
+class Explosion(pygame.sprite.Sprite):
+    defaultlife = 12
+    animcycle = 3
+    images = []
+    def __init__(self, actor):
+        pygame.sprite.Sprite.__init__(self, self.containers)
+        self.image = self.images[0]
+        self.rect = self.image.get_rect()
+        self.life = self.defaultlife
+        self.rect.center = actor.rect.center
+
+    def update(self):
+        self.life = self.life - 1
+        self.image = self.images[self.life/self.animcycle%2]
+        if self.life <= 0: self.kill()
+
+
+class Shot(pygame.sprite.Sprite):
+    speed = -11
+    images = []
+    def __init__(self, pos):
+        pygame.sprite.Sprite.__init__(self, self.containers)
+        self.image = self.images[0]
+        self.rect = self.image.get_rect()
+        self.rect.midbottom = pos
+
+    def update(self):
+        self.rect.move_ip(0, self.speed)
+        if self.rect.top <= 0:
+            self.kill()
+
+
+class Bomb(pygame.sprite.Sprite):
+    speed = 9
+    images = []
+    def __init__(self, alien):
+        pygame.sprite.Sprite.__init__(self, self.containers)
+        self.image = self.images[0]
+        self.rect = self.image.get_rect()
+        self.rect.centerx = alien.rect.centerx
+        self.rect.bottom = alien.rect.bottom + 5
+
+    def update(self):
+        self.rect.move_ip(0, self.speed)
+        if self.rect.bottom >= 470:
+            Explosion(self)
+            self.kill()
+
+
+class Score(pygame.sprite.Sprite):
+    def __init__(self):
+        pygame.sprite.Sprite.__init__(self)
+        self.font = pygame.font.Font(None, 20)
+        self.font.set_italic(1)
+        self.color = Color('white')
+        self.lastscore = -1
+        self.update()
+        self.rect = self.image.get_rect().move(10, 450)
+
+    def update(self):
+        if SCORE != self.lastscore:
+            self.lastscore = SCORE
+            msg = "Score: %d" % SCORE
+            self.image = self.font.render(msg, 0, self.color)
+
+
+
+def main(winstyle = 0):
+    # Initialize pygame
+    pygame.init()
+    if pygame.mixer and not pygame.mixer.get_init():
+        print 'Warning, no sound'
+        pygame.mixer = None
+
+    # Set the display mode
+    winstyle = 0  # |FULLSCREEN
+    bestdepth = pygame.display.mode_ok(SCREENRECT.size, winstyle, 32)
+    screen = pygame.display.set_mode(SCREENRECT.size, winstyle, bestdepth)
+
+    #Load images, assign to sprite classes
+    #(do this before the classes are used, after screen setup)
+    img = load_image('player1.gif')
+    Player.images = [img, pygame.transform.flip(img, 1, 0)]
+    img = load_image('explosion1.gif')
+    Explosion.images = [img, pygame.transform.flip(img, 1, 1)]
+    Alien.images = load_images('alien1.gif', 'alien2.gif', 'alien3.gif')
+    Bomb.images = [load_image('bomb.gif')]
+    Shot.images = [load_image('shot.gif')]
+
+    #decorate the game window
+    icon = pygame.transform.scale(Alien.images[0], (32, 32))
+    pygame.display.set_icon(icon)
+    pygame.display.set_caption('Pygame Aliens')
+    pygame.mouse.set_visible(0)
+
+    #create the background, tile the bgd image
+    bgdtile = load_image('background.gif')
+    background = pygame.Surface(SCREENRECT.size)
+    for x in range(0, SCREENRECT.width, bgdtile.get_width()):
+        background.blit(bgdtile, (x, 0))
+    screen.blit(background, (0,0))
+    pygame.display.flip()
+
+    #load the sound effects
+    boom_sound = load_sound('boom.wav')
+    shoot_sound = load_sound('car_door.wav')
+    if pygame.mixer:
+        music = os.path.join('data', 'house_lo.wav')
+        pygame.mixer.music.load(music)
+        pygame.mixer.music.play(-1)
+
+    # Initialize Game Groups
+    aliens = pygame.sprite.Group()
+    shots = pygame.sprite.Group()
+    bombs = pygame.sprite.Group()
+    all = pygame.sprite.RenderUpdates()
+    lastalien = pygame.sprite.GroupSingle()
+
+    #assign default groups to each sprite class
+    Player.containers = all