Working with Surface Objects

Loading images into Pygame is done with a simple one-liner pygame.image.load takes the file name of the image you want to load and returns a surface object, which is a container for an image. Surfaces can represent many types of image, but Pygame hides most of these details from us so we can treat them in much the same way. Once you have a surface in memory, you can draw on it, transform it, or copy it to another surface to build up an image. Even the screen is represented as a surface object....

Understanding Keyboard Control

Most keyboards in use today are qwerty keyboards, so called because the initial six letters on the first letter row spell out QWERTY. There are variations between brands keys can be slightly different shapes and sizes, but they tend to be in approximately the same position on the keyboard. This is a good thing, since computer users don't want to have to relearn how to type every time they buy a new keyboard All keyboards I have used have had five rows for standard typing keys one row for...

List Methods

Along with these operators, lists support a number of methods. Let's use the sort method to sort our shopping list into alphabetical order gt gt gt my_list.sort gt gt gt my_list 'chopsticks', 'dark soy sauce', 'fugu', 'ramen', 'sake', 'shiitake mushrooms', 'wasabi' The sort method sorts the contents of the list. The order depends on the contents of the list, but for a list of strings the sort is in alphabetical order. You will notice that Python doesn't print anything after the call to sort...

Understanding Events

In Hello World we only handled the QUIT event, which is essential unless you want to have immortal Pygame windows Pygame creates other events to inform you of things such as mouse movement and key presses. Events can be generated at any time, no matter what your program is currently doing. For example, your code could be drawing a tank on the screen when the user presses the fire button on the joypad. Because you can't react to events the instant they happen, Pygame stores them in a queue until...

Making Things Move

I n the real world, objects move in a variety of different ways, depending on what they are doing, and a game must approximate those motions to create a convincing virtual representation. A few games can get away with unrealistic motion Pac-Man, for example, moves in a straight line with a constant speed and can change direction in an instant, but if you applied that kind of motion to a car in a driving game it would destroy the illusion. After all, in a driving game you would expect the car to...

Translation Matrix

A translation matrix is a matrix that adds a vector to the point being transformed. If we transform the points of a 3D model by a translation matrix, it will move the model so that its center is at a new coordinate in the world. You can create a translation matrix by calling Matrix44.translation, which takes the translation vector as three values. The following code creates and displays a translation matrix gt gt gt translation Matrix44.translation 10, 5, 2 gt gt gt translation.transform p1 The...

Seeing Textures in Action

Let's write a script to demonstrate uploading a texture and using it when rendering an OpenGL primitive. We are going to draw a single textured quad, and to show that it isn't simply a sprite we will rotate it around the x axis. In the init function of Listing 11-2 is a call to glEnable GL_TEXTURE_2D , which enables OpenGL textures. If you ever have problems getting textures to work in OpenGL, check whether you have made this call. Listing 11-2. Textures in Action opengltex.py SCREEN_SIZE 800,...

Seeing Models in Action

Let's write a class to load a Wavefront OBJ file and render it with OpenGL. I have created a model of a futuristic tank see Figure 11-5 , which was built with AC3D www.inivis.com and exported it as mytank.obj and mytank.mtl. My artistic skills are limited feel free to replace my model with your own 3D object. You can use any 3D modeler software that has the capability to export OBJ files. Figure 11-5. Futuristic tank object in AC3D Figure 11-5. Futuristic tank object in AC3D The class we will...

Skyboxes

A common solution to the problem of rendering distant scenery is the skybox, which is simply a textured cube with scenery on each side. The front, back, left, and right sides of the cube show a view toward the horizon. The top of the cube is an image of the sky and the bottom of the cube is the ground. When the skybox is drawn around the camera, the player is surrounded on all sides with images of distance scenery, which creates a convincing illusion of being there. A skybox is a model of a...

Unit Vectors

Vectors actually describe two things magnitude and direction. For instance, soldier Alpha can use the vector AB to figure out how far he has to travel magnitude , but the vector also tells him in which direction to face direction . Normally these two pieces of information are tied up together in a vector, but occasionally you only require one or the other. We have already seen how to calculate the magnitude, but we can also remove the magnitude information from the vector by dividing the...

Game Entities

Although we have three different types of entities, it is a good idea to come up with a base class for a game entity that contains common properties and actions. That way, we won't need to duplicate code for each of the entities, and we can easily add other entities without much extra work. An entity will need to store its name ant, leaf, or spider , as well as its current location, destination, speed, and the image used to represent it on screen. You may find it odd that the leaf entity will...

Table Blending Equation Constants Blend Equation Constant Explanation

GL_FUNC_ADD Adds the source and destination colors GL FUNC SUBTRACT Subtracts the destination from the source color GL FUNC REVERSE SUBTRACT Subtracts the source from the destination color Calculates the minimum darkest of the source and destination colors Calculates the maximum brightest of the source and destination colors Combines the source and destination colors with a logic operation see the OpenGL documentation for information on logic operations Another OpenGL function involved in...

TimeBased Movement in D

We can use the Vector3 class to do time-based movement in 3D in much the same way as we do in two dimensions. As an example, let's use a little 3D vector math to calculate a target vector and work out the intermediate coordinates for a projectile weapon see Figure 8-3 . Figure 8-3. Calculating a target vector Soldier Alpha has walked a few meters away from his original position in Figure 8-2, and is now standing at point -6, 2, 0 . The spy droid is still hovering at 7, 5, 10 , monitoring...

Index

assignment operator , 11 backslash character , and strings, 6 bitwise OR operator, 46 colon character, 9 comparison operator , 21 curly braces , 15 equal sign, and variables, 5 index operator , 7 modulus operator , 4, 29, 247 multiply operator, and strings, 7 plus operator lists and, 12 strings and, 6 vectors and, 104 plus equals operator, and lists, 12 power operator , 4 gt gt gt prompt , 2 quotation marks , and strings, 6 camera in, 175 coordinate system, 167-168 depth, creating illusion of,...

Building the Brains

Game Pygame

Each ant is going to have four states in its state machine, which should be enough to simulate ant-like behavior. The first step in defining the state machine is to work out what each state should do, which are the actions for the state see Table 7-1 . Table 7-1. Actions for the Ant States Table 7-1. Actions for the Ant States Walk toward a random point in the world. We also need to define the links that connect states together. These take the form of a condition and the name of the state to...

Game Objects Vector Class

The Vector2 class that we built earlier is good enough for basic vector maths, and you could use it as a starting point for your own vector class just about every game developer has written a vector class at some point . However, to get up and running quickly, you can use a Vector2 class I wrote as part of Game Objects, a framework to simplify writing games. You can download Game Objects from www.willmcgugan .com game-objects . The Vector2 class is part of a larger collection of classes in the...

I

containing every color, generating, 67-68 blitting, 82-83 clipping area, 79 converting, 77-78 creating, 77 filling, 80 getting pixels in, 81 locking, 81-82 overview of, 76 setting pixels in, 80 subsurfaces, 79 imp AI, pseudocode for, 140 import statement Pygame , 46 importing class from Game Objects library, 183 classes, 32 classes to Game Objects library, 285 modules, 35-36 init function, 46, 125 _init_ method, 27, 133 initializing mixer, 216-217 OpenGL, 198-199 Inno Setup software, 294...

Seeing Fog in Action

Rather than write an entire script to test fog, let's modify the spinning tank from the previous chapter Listing 11-8 . We will start by adding a few lines to the init function to enable fog and set the fog parameters. The following lines create a simple linear fog that fades to white glFogfv GL_FOG_COLOR, 1.0, 1.0, 1.0 glFogi GL_FOG_MODE, GL_LINEAR glFogf GL_FOG_START, 1.5 glFogf GL_FOG_END, 3.5 If you run the modified Listing 11-8 now, you will see something like Figure 12-2. The fog starts...

Implementing State Machines

The two states for the imp's brain form a very simple state machine. A state generally defines two things What the NPC is doing at that moment At what point it should switch to another state The condition to get from the exploring state to the seeking state is self.can_see player in other words, Can I the imp see the player The opposite condition not self.can_see player is used to get back from seeking to exploring. Figure 7-1 is a diagram of the imp's state machine, which is effectively its...

Perspective Projections

A far more common projection in games and 3D computer graphics in general is the perspective projection, because it takes into account the distance of an object from the viewer. A perspective projection replicates the way that objects farther from the viewer appear smaller than objects close up. Objects rendered with a perspective projection will also appear to narrow toward the horizon, an effect known as foreshortening see Figure 8-5 . Listing 8-6 is a function that projects a 3D coordinate...

Fog Parameters

Call glEnable GL_FOG to have OpenGL apply fog to all polygons that are rendered. There are a number of fog parameters you can set with the glFog range of functions, which take a constant for the value you want to set followed by the value itself. The color of the fog can be set with a call to glFogfv with the GL_FOG_COLOR constant, followed by the color you want to use. For example, the following line sets the fog color to pure white to simulate a snow blizzard, perhaps glFogfv GL_FOG_COLOR,...

Matrix Multiplication

Often in a game you will need to do several transformations to a 3D object. For a tank game you would likely want to translate it to a position in the world and then rotate it to face the direction it is heading. You could transform the tank with both matrices, but it is possible to create a single matrix that has the combined effect by using matrix multiplication. When you multiply a matrix by another, you get a single matrix that does both transformations. Let's test that by multiplying two...

Using pyexe

To turn a Python file into an executable file, you can use py2exe, which is itself a Python module. py2exe isn't part of Python's standard library, but it can easily be installed with the following command Before creating an executable for your Python code, you need to write setup, py, which contains information about your project and launches py2exe. Let's create a setup.py Listing B-1 for the Ant state machine listing in Chapter 7. Listing B-1. Creating an Executable Python Project setup.py...

Summary Ios

Making a nonplayer character behave in a realistic fashion is the goal of artificial intelligence in games. Good AI adds an extra dimension to the game because players will feel that they are in a real world rather than a computer program. Poor AI can destroy the illusion of realism as easily as glitches in the graphics or unrealistic sounds possibly even more so. A player might be able to believe that a crudely drawn stick figure is a real person, but only as long as it doesn't bump into walls...

OBJ Format for D Models

To work with 3D models we are going to use the Wavefront OBJ format extension .obj , which is a simple text format that has been in existence for many years. Most software that works with 3D models will be able to at least write OBJ files, and probably read them as well. They are text based, so you can open them in a text editor such as Windows Notepad, or the equivalent on other platforms. OBJ files often come with a material library file with the extension .mtl , which contains various...

Building the Installer

After running our project through py2exe, we can now use any installer builder software to create installer executables. There are many to choose from some are commercial and very expensive , but there are some very good free options. We are going to use the free software, Inno Setup, which produces professional-looking installers. You can download Inno Setup from www.jrsoftware.org isinfo.php. Inno Setup compiles the executable from a script file extension .iss , which is a simple text format...

Windows with No Borders

Generally when you create a Pygame window you will want a standard window with title bars and border. It is possible, though, to create a window that doesn't have these features so that the user will not be able to move or resize the window, or close it via the close button. One instance of such a use is the window used for splash screens. Some games can take a while to load because they contain many image and sound files. If there is nothing visible on the screen while this is happening, the...

Texture Parameters

Pygame Tutorial

OpenGL is very flexible in the way it renders 3D scenes. There are a number of texture parameters that can be set to create visual effects and adjust how textures are used to render polygons. This section covers some commonly used texture parameters the full list is beyond the scope of this book, but you can read the OpenGL documentation online www.opengl.org sdk docs man for all the details. In Listing 11-2 we set two texture parameters, GL_TEXTURE_MIN_FILTER and GL_TEXTURE_MAX_FILTER, which...

Exploring AI

Artificial intelligence isn't essential to creating an entertaining game. I used to love to play classic platform games where the hero has to leap from platform to platform and brazenly jump on the heads of monsters. Although the monsters in these games are NPCs, their actions are a little rudimentary to be considered AI. Let's look inside the head of a typical platform game monster Listing 7-1 . This listing is pseudocode, which is code that's used to demonstrate a technique but that doesn't...

Note It may seem a little odd but when you move a camera about in a D world you

Opengl Pygame

Listing 9-8. Flying Around Cube World firstopengl.py SCREEN_SIZE 800, 600 from OpenGL.GL import from OpenGL.GLU import from gameobjects.matrix44 import from gameobjects.vector3 import gluPerspective 60.0, float width height, .1, 1000. glShadeModel GL_FLAT glClearColor 1.0, 1.0, 1.0, 0.0 glEnable GL_LIGHTING glEnable GL_LIGHT0 glLight GL_LIGHT0, GL_POSITION, 0, 1, 1, 0 self.position position self.color color vertices 0.0, 0.0, 1.0 1.0, 0.0, 1.0 1.0, 1.0, 1.0 0.0, 1.0, 1.0 0.0, 0.0, 0.0 1.0, 0.0,...

Rotational Movement with the Mouse

You have seen that drawing a mouse cursor on the screen is quite straightforward you simply need to get the coordinates of the mouse from a MOUSEMOTION event or directly from the pygame.mouse.get_pos function. Either method is fine if you just want to display a mouse cursor, but mouse movement can also be used to control something other than an absolute position, such as rotating or looking up and down in a 3D game. In this case, we can't use the mouse position directly because the coordinates...

Storing Sound

Early computer games used chips that created simple tones to produce electronic bleeps and whistles, but were incapable of producing complex sounds. These days, gaming hardware can store and reproduce real-life sounds to create a rich extra dimension to the gameplay. The sound card on your computer can both record and play back high-quality audio. Sound can be represented as a wave. Figure 10-1 shows a sound wave that represents a brief portion of a sound a fraction of a second a full sound...

Using the Matrix Class

The Game Objects library contains a class named Matrix44 that we can use with Pygame. Let's experiment with it in the interactive interpreter. The following code shows how you would import Matrix44 and start using it gt gt gt from gameobjects.matrix44 import gt gt gt identity Matrix44 gt gt gt print identity The first line imports the Matrix44 class from the gameobjects.matrix44 module. The second line creates a Matrix44 object, which defaults to the identity matrix, and names it identity. The...

Pygame in Action

Back when I was a youngling, the scrolly message was a very popular effect among hobbyist graphics programmers. A scrolly message, or marquee as it is now known, is simply text sliding across the screen from right to left. Listing 3-7 is a Pygame implementation of a scrolly message. It's not without its faults, the most major of which is that it will move at an inconsistent speed, and may be faster or slower on different computers. This is a problem that you will learn how to solve in the next...

Tip A quicker way to create a transformation about all three axes is to use the

Matrix Pygame Math

Figure 9-5. 3D transformations in action Figure 9-5. 3D transformations in action Listing 9-3. Matrix transformation in action rotation3d.py SCREEN_SIZE 640, 480 CUBE_SIZE 300 from gameobjects.vector3 import Vector3 from gameobjects.matrix44 import Matrix44 as Matrix def calculate_viewing_distance fov, screen_width d screen_width 2.0 tan fov 2.0 return d screen pygame.display.set_mode SCREEN_SIZE, 0 'courier new' is a fixed width font font pygame.font.SysFont courier new, 16, True ball Create a...

Python in Practice 1

The game we are going to create is more of a simulation than a game, but it should be enough to introduce a few important game concepts. We will create a number of tanks and let them take shots at each other. The winner is simply the last tank left in the game. Listing 2-7 shows the code that completes the tank game. Listing 2-7. tankgame.py from tank import Tank tanks a Tank Alice , b Tank Bob , c Tank Carol alive_tanks len tanks for tank_name in sorted tanks.keys print tank_name, tanks...

Detecting Key Presses

There are two ways to detect a key press in Pygame. One way is to handle KEYDOWN events, which are issued when a key is pressed, and KEYUP events, which are issued when the key is released. This is great for typing text because we will always get keyboard events even if a key has been pressed and released in the time since the last frame. Events will also capture very quick taps of the key for fire buttons. But when we use keyboard input for movement, we simply need to know if the key is...

Understanding Frame Rate

The first thing we need to know about movement in a computer game is that nothing really moves at least not in any physical sense. A computer screen or television set presents us with a sequence of images, and when the time between the images is short enough, our brain blends the images together to create the illusion of fluid motion. The number of images, or frames, required to produce smooth motion can vary from person to person. Movies use 24 frames per second, but computer games tend to...

Creating Artificial Intelligence for Games

You may have looked in the Pygame documentation for a pygame.ai module. There isn't one, because each game can have vastly different requirements when it comes to creating NPCs. The code for an ape that throws barrels at plumbers wouldn't require much work all the ape needs to determine is whether it should throw the barrel to the left or right, something you could probably simulate in a single line of Python code Creating a convincing enemy combatant in a futuristic first-person shooter may...

Blending Colors

Something else you may want to do with colors is blend one color gradually into another. Let's say we have a zombie in a horror game that is normally a sickly shade of zombie green but has recently emerged from a lava pit and is currently glowing a bright shade of fireball orange. Over time the zombie will cool down and return to its usual color. But how do we calculate the intermediate colors to make the transition look smooth We can use something called linear interpolation, which is a fancy...

Exploring Vectors

We used two values to generate diagonal movement a speed for the x component of the position and another for the y component. These two values combined form what is known as a vector. A vector is something that game developers borrowed from mathematics and they are used in many areas, in both 2D and 3D games. Vectors are similar to points in that they both have a value for x and y in 2D , but they are used for different purposes. A point at coordinate 10, 20 will always be the same point on the...

Tip Tiling works best with textures that have been designed to be seamlessthat

An alternative setting for the wrap parameter is GL_MIRRORED_REPEAT, which is similar to GL_REPEAT but mirrors the sample point when it goes over the texture edge. To see this in action, insert the following two lines before the while True line in the run function of Listing 11-2 glTexParameteri GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT glTexParameteri GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAt Now when you run Listing 11-2 you should see that the repeated images are...

FullScreen Displays

In Hello World we used the following line to create a Pygame window screen pygame.display.set_mode 640, 480 , 0, 32 The first parameter is the size of the window we want to create. A size of 640, 480 creates a small window that will fit comfortably on most desktops, but you can select a different size if you wish. Running in a window is great for debugging, but most games fill the entire screen with the action and don't have the usual borders and title bar. Full-screen mode is usually faster...

Note You may have to flip the normals on the faces of the cube which makes them

Skybox Rendering Opengl

Generating the skybox textures may require a little more effort because each texture must seamlessly align with the four other textures it shares an edge with. If you are artistically inclined, you may be able to draw or paint these textures, but it is probably easier to use 3D modeling software to render six views of a scene for each face of the skybox. An excellent choice for rendering skyboxes is Terragen www.planetside.co.uk terragen , which creates remarkably realistic-looking images of...

Diagonal Movement 1

Let's use vectors to create more accurate diagonal movement. How would we move a sprite from one position on the screen to another, at a constant speed The first step is to create a vector from the current position to the destination using Vector2.from_points or something similar . We only need the direction information in this vector, but not the magnitude, so we normalize it to give us the sprite's heading. Inside the game loop we calculate how far the sprite has moved with speed...

pygamedrawaaline

You may have noticed from the previous line drawing functions that the lines have a jagged appearance. This is because a pixel can only be drawn at a coordinate on a grid, which may not lie directly underneath a line if it is not horizontal or vertical. This effect is called aliasing, something which computer scientists have put a lot of work into avoiding. Any technique that attempts to avoid or reduce aliasing is called antialiasing. Pygame can draw antialiased lines that appear significantly...

Removing List Items

Along with changing items in a list, you can remove items from it. Let's say we want to remove apple pie because it just doesn't seem to fit with the rest of our shopping list. We can do this with the del operator, which will remove any item from our list in this case, it is the last item, so we will use negative indexing gt gt gt del my_list -1 gt gt gt my_list 'chopsticks', 'dark soy sauce', 'wasabi', 'fugu', 'sake' Lists support a number of operators that work in a similar way to strings....

Modifying List Items

Python lists are mutable, which means you can change them after they have been created. So as well as retrieving the contents of a list with the index operator, you can change the item at any index by assigning a new item to it. Let's say we specifically want to get dark soy sauce we can change the second item by assigning it a new value with the assignment operator gt gt gt my_list l 'dark soy sauce' gt gt gt my_list 'chopsticks', 'dark soy sauce', 'wasabi', 'fugu', 'sake', 'apple pie'

Its About Time

The trick to solving this problem is to make the motion time-based. We need to know how much time has passed since the previous frame so we can position everything on the screen accordingly. The pygame.time module contains a Clock object that we can use to keep track of time. To create a clock object, call its constructor pygame.time.Clock Once you have a clock object, you should call its member function tick once per frame, which returns the time passed since the previous call in milliseconds...

Resizable Pygame Windows

Occasionally you may want the user to be able to resize a Pygame window, which you typically do by clicking on the corner of the window and dragging with the mouse. It's easy enough to do this by using the RESIZABLE flag when you call set_mode. Pygame informs your code if the user has changed the window size by sending a VIDEORESIZE event that contains the new width and height of the window. When you get one of these events, you should call pygame. display.set_mode again to set the display to...