PyGame
PyGame is a Python port of the SDL (Simple Directmedia Layer) Library. As the name suggests it's focus is writing games but is well suited to developing other types of applications and visualizations.
PyGame supplies the following:
- Surfaces(Hardware/Software Accelerated)
- OpenGL
- Fonts
- Events(Keyboard, Mouse, Joysticks)
- Audio
- Video
- Sprites, Images
- Basic Drawing Routines
An Example
Hello World (WITH BOXES!)
Because I know EXCITING, I thought I'd try showing you an "action packed" demo instead of the boring ol' hello world type stuff. First, a preview of what you're going to see produce:
bounce.py: Initialization and Event handling
This first file is the main program. It is responsible for initializing PyGame and setting everything up for drawing.
Download bounce.py
box.py: Box Class w/ Drawing code
Box.py defines the Box class and it's draw method.
Boxes consist of a screen height and width, a box height and width, a box velocity (as x and y components) in terms of standard python types. Boxes also include a Pygame Surface(called screen), 2 colors (background and box), and a Rect object. (Rect's represent drawable screen regions.)
The boxes are all moving, so when we draw a box, we first want to clear the rectangle on the screen where we used to be. So that is the first thing we do in the draw method. Next, we determine if we are near an edge or not. If the box has arrived at an edge we just reverse our velocity with respect to that edge. (If you hit the left or right sides you reverse self.vx, otherwise reverse self.vy.)
When our box is not bouncing, it's simply moving, so we just update it's coordinates by adding the velocity values to them(nx = self.x + self.vx). We then create a new Rect at our new coordinates and draw that rectangle to the screen.
Download box.py
More Examples
Heat
Heat is a visualization of a partial differential equation problem that I look at briefly in my Numeric Examples. Basically it is a color coded view of the field as it settles down
Life
Life is an implementation of the Game of Life that automatically generates a large field of cells and lets it develop. This could easily be the beginnings of a screensaver or quickly adapted into a more traditional game of life (much smaller grid, place cells with your mouse, hit play and see if the colony lives or dies).
If you're not familiar with the Game of Life the concept is simple. Each green cell represents a living thing. Depending on the number of neighbors each cell has, it is either happy (and reproduces), average( it just sits there ), or depressed (it dies).
There is no traditional goal in this game. You don't really "win" or "lose". It's usually just interesting to see what sort of patterns come out of this simple algorithm.
The performance of this problem on this size grid is not nearly as good as I'd like but I haven't had sufficient time to optimize it. Perhaps optimization can be left to you as an exercise?
:~)