Commits

Anonymous committed 5783e7b

import fixups and icons

  • Participants
  • Parent commits e6ad637

Comments (0)

Files changed (8)

 # BREAK = change breaks existing code
 # BUG	= fixed a bug that was (or could have been) crashing
 
+January 17, 2001
+        smarter importing code
+        default pygame icon for window
+
 January 16, 2001
-	implemented basic unit tests
+	started implementing basic unit tests
 	several bug cleanups with Rects (thx unit tests)
 
 January 14, 2001

File examples/aliens.py

 
 #game constants
 MAX_SHOTS      = 2      #most player bullets onscreen
-ALIEN_ODDS     = 29     #chances a new alien appears
-BOMB_ODDS      = 150    #chances a new bomb will drop
+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):
             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 = 255, 255, 255
+        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
     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():
             boom_sound.play()
             Explosion(alien)
             Explosion(player)
-            kills = kills + 1
+            SCORE = SCORE + 1
             player.kill()
 
         for alien in pygame.sprite.groupcollide(shots, aliens, 1, 1).keys():
             boom_sound.play()
             Explosion(alien)
-            kills = kills + 1
+            SCORE = SCORE + 1
                     
         for bomb in pygame.sprite.spritecollide(player, bombs, 1):         
             boom_sound.play()

File lib/__init__.py

 ##
 ##    Pete Shinners
 ##    pete@shinners.org
+"""Pygame is a set of Python modules designed for writing games.
+It is written on top of the excellent SDL library. This allows you
+to create fully featured games and multimedia programs in the python
+language. The package is highly portable, with games running on
+Windows, MacOS, OSX, BeOS, FreeBSD, IRIX, and Linux.
+"""
 
-# main pygame source
-# lets get things coordinated
+import sys, os
+if sys.platform=='darwin':
+    # this may change someday, but we want to chdir to where our file is if we're in / for no
+    # good reason..
+    if (os.getcwd() == '/') and len(sys.argv):
+        os.chdir(os.path.split(sys.argv[0])[0])
+    else:
+        argv0=''
+        if len(sys.argv): argv0=sys.argv[0]
+        print "WARNING!  Running pygame apps from any method other than through python.app (aka through the finder or launchservices) is UNSUPPORTED!"
+        print "          If you insist on using the terminal, type \"open %s\", and hold down the option key if you need to" % (argv0)
+        print "          specify additional command line arguments.  A dialog box will pop up and make you happy, I promise."
+        print ""
+        print "          I sure hope you ran as \"%s %s\" exactly, otherwise you will really have problems."%(sys.executable,' '.join(sys.argv))
+        print "          WindowServer doesn't like what you're doing as is, and it gets really funky if you run things from the path for whatever reason."
+        print ""
+        # not ready for prime time yet, it just rewrites the commandline so windowserver can pick it up
+        #import pygame.macosx
 
-def import_all_pygame():
-    import sys
-    if sys.platform=='darwin':
-        import os
-        # this may change someday, but we want to chdir to where our file is if we're in / for no
-        # good reason..
-        if (os.getcwd() == '/') and len(sys.argv):
-            os.chdir(os.path.split(sys.argv[0])[0])
-        else:
-            argv0=''
-            if len(sys.argv): argv0=sys.argv[0]
-            print "WARNING!  Running pygame apps from any method other than through python.app (aka through the finder or launchservices) is UNSUPPORTED!"
-            print "          If you insist on using the terminal, type \"open %s\", and hold down the option key if you need to" % (argv0)
-            print "          specify additional command line arguments.  A dialog box will pop up and make you happy, I promise."
-            print ""
-            print "          I sure hope you ran as \"%s %s\" exactly, otherwise you will really have problems."%(sys.executable,' '.join(sys.argv))
-            print "          WindowServer doesn't like what you're doing as is, and it gets really funky if you run things from the path for whatever reason."
-            print ""
-            # not ready for prime time yet, it just rewrites the commandline so windowserver can pick it up
-            #import pygame.macosx
 
-    def makemodules(**mods): return mods
-    modules = makemodules(
-        base=2, cdrom=0, constants=2, cursors=0, display=0,
-        draw=0, event=0, font=0, image=0, joystick=0,
-        key=0, mixer=0, mouse=0, movie=0, rect=1, sprite=0,
-        surface=0, time=0, transform=0, surfarray=0, version=2
-    )
-    for mod, required in modules.items():
-        try:
-            module = __import__('pygame.'+mod, None, None, ['pygame.'+mod])
-            globals()[mod] = module
-            if required == 2:
-                for item in dir(module):
-                    if item[0] != '_':
-                        globals()[item] = getattr(module, item)
-        except ImportError:
-            if required:
-                CannotImportPygame = ImportError
-                MissingModule =  "Cannot Import 'pygame.%s'"%mod
-                raise CannotImportPygame, MissingModule
-            globals()[mod] = None
+#we need to import like this, each at a time. the cleanest way to import
+#our modules is with the import command (not the __import__ function)
 
-import_all_pygame()
-del import_all_pygame
+#first, the "required" modules
+from pygame.base import *
+from pygame.constants import *
+from pygame.version import *
+from pygame.rect import Rect
+import pygame.rwobject
+import pygame.surflock
 
-Surface = getattr(surface, 'Surface', lambda:Missing_Pygame_Function)
-Rect = getattr(rect, 'Rect', lambda:Missing_Pygame_Function)
+#next, the "standard" modules
+#we still allow them to be missing for stripped down pygame distributions
+try: import pygame.cdrom
+except (ImportError,IOError):cdrom=None
 
+try: import pygame.cursors
+except (ImportError,IOError):cursors=None
 
+try: import pygame.display
+except (ImportError,IOError):display=None
+
+try: import pygame.draw
+except (ImportError,IOError):draw=None
+
+try: import pygame.event
+except (ImportError,IOError):event=None
+
+try: import pygame.image
+except (ImportError,IOError):image=None
+
+try: import pygame.joystick
+except (ImportError,IOError):joystick=None
+
+try: import pygame.key
+except (ImportError,IOError):key=None
+
+try: import pygame.mouse
+except (ImportError,IOError):mouse=None
+
+try: import pygame.sprite
+except (ImportError,IOError):sprite=None
+
+try: from pygame.surface import *
+except (ImportError,IOError):Surface = lambda:Missing_Function
+
+try: import pygame.time
+except (ImportError,IOError):time=None
+
+try: import pygame.transform
+except (ImportError,IOError):transform=None
+
+#lastly, the "optional" pygame modules
+try: import pygame.font
+except (ImportError,IOError):font=None
+
+try: import pygame.mixer
+except (ImportError,IOError):mixer=None
+
+try: import pygame.movie
+except (ImportError,IOError):movie=None
+
+try: import pygame.surfarray
+except (ImportError,IOError):surfarray=None
+
+#there's also a couple "internal" modules not needed
+#by users, but putting them here helps "dependency finder"
+#programs get everything they need (like py2exe)
+try: import pygame.imageext; del imageext
+except (ImportError,IOError):pass
+
+try: import pygame.mixer_music; del mixer_music
+except (ImportError,IOError):pass
+
+
+#cleanup namespace
+del pygame, os, sys, rwobject, surflock

File lib/pygame.ico

Added
New image

File lib/pygame_icon.bmp

Added
New image

File lib/version.py

 releases. (hmm, until we get to versions > 10)
 """
 
-ver = '1.3.4'
+ver = '1.3.5'
 
 def __hiddendummyfunc():
     """pygame.version.ver 
 
 METADATA = {
     "name":             "pygame",
-    "version":          "1.3.4",
+    "version":          "1.3.5",
     "license":          "LGPL",
     "url":              "http://www.pygame.org",
     "author":           "Pete Shinners",

File src/display.c

 #include "pygame.h"
 
 
+static char* icon_defaultname = "pygame_icon.bmp";
+static PyObject* self_module = NULL;
+
 
 staticforward PyTypeObject PyVidInfo_Type;
 static PyObject* PyVidInfo_New(const SDL_VideoInfo* info);
 	int flags = SDL_SWSURFACE, depth = 0;
 	int w, h, hasbuf;
 	char* title, *icontitle;
+	static int icon_was_set = 0;
 
 	if(!PyArg_ParseTuple(arg, "(ii)|ii", &w, &h, &flags, &depth))
 		return NULL;
 	if(!title || !*title)
 		SDL_WM_SetCaption("pygame window", "pygame");
 
+
 	/*probably won't do much, but can't hurt, and might help*/
 	SDL_PumpEvents();
 
-
 	if(DisplaySurfaceObject)
 		((PySurfaceObject*)DisplaySurfaceObject)->surf = surf;
 	else
 		DisplaySurfaceObject = PySurface_New(surf);
 
+
+	/*set the default icon. we may not want to do this on darwin?*/
+	if(!icon_was_set)
+	{
+		SDL_Surface* icon;
+		char* iconpath;
+		char* path = PyModule_GetFilename(self_module);
+		icon_was_set = 1;
+		if(!path)
+			PyErr_Clear();
+		else
+		{
+			char* end = strstr(path, "display.");
+			if(end)
+			{
+				iconpath = PyMem_Malloc(strlen(path) + 20);
+				if(iconpath)
+				{
+					strcpy(iconpath, path);
+					end = strstr(iconpath, "display.");
+					strcpy(end, icon_defaultname);
+
+					icon = SDL_LoadBMP(iconpath);
+					if(icon)
+					{
+						SDL_SetColorKey(icon, SDL_SRCCOLORKEY, 0);
+						SDL_WM_SetIcon(icon, NULL);
+						SDL_FreeSurface(icon);
+					}
+					PyMem_Free(iconpath);
+				}
+			}
+		}
+	}
+
 	Py_INCREF(DisplaySurfaceObject);
 	return DisplaySurfaceObject;
 }
 static GAME_Rect* screencroprect(GAME_Rect* r, int w, int h, GAME_Rect* cur)
 {
 	if(r->x > w || r->y > h || (r->x + r->w) <= 0 || (r->y + r->h) <= 0)
-		return 0;
-	else
+{printf("update rejecting rect %d,%d,%d,%d\n", (int)r->x, (int)r->y, (int)r->w, (int)r->h);
+                return 0;
+}       else
 	{
 		int right = min(r->x + r->w, w);
 		int bottom = min(r->y + r->h, h);
 	int wide, high;
 	PyObject* obj;
 
+	VIDEO_INIT_CHECK();
+
+	screen = SDL_GetVideoSurface();
+	if(!screen)
+		return RAISE(PyExc_SDLError, SDL_GetError());
+	wide = screen->w;
+	high = screen->h;
+	if(screen->flags & SDL_OPENGL)
+		return RAISE(PyExc_SDLError, "Cannot update an OPENGL display");
+
+        
 	/*determine type of argument we got*/
 	if(PyTuple_Size(arg) == 0)
-		gr = &temp;
+        {
+            SDL_UpdateRect(screen, 0, 0, 0, 0);
+            RETURN_NONE
+        }
 	else
 	{
 		obj = PyTuple_GET_ITEM(arg, 0);
 			}
 		}
 	}
-	VIDEO_INIT_CHECK();
 
-	screen = SDL_GetVideoSurface();
-	if(!screen)
-		return RAISE(PyExc_SDLError, SDL_GetError());
-	wide = screen->w;
-	high = screen->h;
-
-
-	if(screen->flags & SDL_OPENGL)
-		return RAISE(PyExc_SDLError, "Cannot update() an OPENGL display");
-
-	if(gr) /*single or no rect given*/
-	{
-		if(screencroprect(gr, wide, high, &temp))
-			SDL_UpdateRect(screen, temp.x, temp.y, temp.w, temp.h);
+        if(gr)
+        {
+                if(screencroprect(gr, wide, high, &temp))
+                        SDL_UpdateRect(screen, temp.x, temp.y, temp.w, temp.h);
+        }
+        else
+        {
+                PyObject* seq;
+                PyObject* r;
+                int loop, num, count;
+                SDL_Rect* rects;
+                if(PyTuple_Size(arg) != 1)
+                        return RAISE(PyExc_ValueError, "update requires a rectstyle or sequence of recstyles");
+                seq = PyTuple_GET_ITEM(arg, 0);
+                if(!seq || !PySequence_Check(seq))
+                        return RAISE(PyExc_ValueError, "update requires a rectstyle or sequence of recstyles");
+        
+                num = PySequence_Length(seq);
+                rects = PyMem_New(SDL_Rect, num);
+                if(!rects) return NULL;
+                count = 0;
+                for(loop = 0; loop < num; ++loop)
+                {
+                        GAME_Rect* cur_rect = (GAME_Rect*)(rects + count);
+        
+                        /*get rect from the sequence*/
+                        r = PySequence_GetItem(seq, loop);
+                        if(r == Py_None)
+                        {
+                                Py_DECREF(r);
+                                continue;
+                        }
+                        gr = GameRect_FromObject(r, cur_rect);
+                        Py_XDECREF(r);
+                        if(!gr)
+                        {
+                                PyMem_Free((char*)rects);
+                                return RAISE(PyExc_ValueError, "update_rects requires a single list of rects");
+                        }
+                        
+                        if(gr->w < 1 && gr->h < 1)
+                                continue;
+        
+                        /*bail out if rect not onscreen*/
+                        if(!screencroprect(gr, wide, high, cur_rect))
+                                continue;
+        
+                        ++count;
+                }
+        
+                SDL_UpdateRects(screen, count, rects);
+                PyMem_Free((char*)rects);
 	}
-	else /*sequence given*/
-	{
-		PyObject* seq;
-		PyObject* r;
-		int loop, num, count;
-		SDL_Rect* rects;
-
-		if(PyTuple_Size(arg) != 1)
-			return RAISE(PyExc_ValueError, "update requires a rectstyle or sequence of recstyles");
-		seq = PyTuple_GET_ITEM(arg, 0);
-		if(!seq || !PySequence_Check(seq))
-			return RAISE(PyExc_ValueError, "update requires a rectstyle or sequence of recstyles");
-
-		num = PySequence_Length(seq);
-		rects = PyMem_New(SDL_Rect, num);
-		if(!rects) return NULL;
-		count = 0;
-		for(loop = 0; loop < num; ++loop)
-		{
-			GAME_Rect* cur_rect = (GAME_Rect*)(rects + count);
-
-			/*get rect from the sequence*/
-			r = PySequence_GetItem(seq, loop);
-			if(r == Py_None)
-			{
-				Py_DECREF(r);
-				continue;
-			}
-			gr = GameRect_FromObject(r, cur_rect);
-			Py_XDECREF(r);
-			if(!gr)
-			{
-				PyMem_Free((char*)rects);
-				return RAISE(PyExc_ValueError, "update_rects requires a single list of rects");
-			}
-			
-			if(gr->w < 1 && gr->h < 1)
-				continue;
-
-			/*bail out if rect not onscreen*/
-			if(!screencroprect(gr, wide, high, cur_rect))
-				continue;
-
-			++count;
-		}
-
-		SDL_UpdateRects(screen, count, rects);
-		PyMem_Free((char*)rects);
-	}
-	
 	RETURN_NONE
 }
 
     /* create the module */
 	module = Py_InitModule3("display", display_builtins, doc_pygame_display_MODULE);
 	dict = PyModule_GetDict(module);
+	self_module = module;
 
 	/* export the c api */
 	c_api[0] = &PyVidInfo_Type;