Figure The flat plane becomes a full rotating cube
Let's say you wanted to speed up and twist your rotating cube around a bit more. It's easy to fiddle with MatrixMode, especially since you've thought ahead and included a number of variables with which to do it x,y, and z rots are the rotations on each axis xrot yrot zrot 0.0 These variables, xrot, yrot, and zrot, can be used to rotate the cube in a new way on the x-, y-, and x-axes. Do so by adding a few lines to the top of drawgraphics glLoadidentity glTranslatef 0.0, 0.0, -5.0 global rquad...
Figure Opening the Lua standalone interpreter
CiUtocumuHs i.tHbinU. ui.c bin 5. ftjpyi-iijlil lt lii -JHlCl Tm rnf, I'M C-R in y h-j ii-Mi gt i i l t t If 1f ititTttf I ttff t ft t EtlltElf 'f tmiTfmiTmwtimfTmiifTmmTmTifMmiiiFTPn 1 gt ii Wmmmmmm'riiTi'fimmmmr lmmmmmmmmfiiftimmmttmutimmif In the interpreter, each command that you type executes immediately after you press the Enter key, and that line is considered to be a whole Lua chunk more on Lua chunks in just a bit . The Lua interpreter is fairly smart, and if you need to enter...
Interpreted versus Compiled Languages
A high-level interpreted language translates the programmer's written code step-by-step at runtime, or when the program is actually running. A high-level compiled language translates a programmer's written code before the program is run, a process normally called compiling. This changes the written code into an executable or object-code that can then be run as a program on a computer. Many modern programming languages allow themselves to be both interpreted and compiled, but normally a...
Event Handling
Handlers for key presses and mouse clicks are necessary for any computer game. Mouse events will be picked up by the individual actor that controls the player, but monitoring for the keyboard and windows events must also occur in case a player wants to close a window or quit using the Escape key. This can be done fairly easily see Figure 7.8 by using SDL_KEYDOWN to watch for SDLK_q or SDLK_ESCAPE. called by main loop Checks for keypresses sets gamestate to nil if player wants to quit if...
Tkinter Images
Tkinter uses the image class as a foundation to display graphic objects. Graphic objects Tkinter can display include both bitmap Bitmapimage and GIF photoimage images. The functions image_names and image_types are used to handle all the images within the image class. The first returns a list containing the names of all available images, and the second returns a list that contains all the existing types that were created. Images, once created, provide a handful of methods image. width , image....
Table Python Multimedia Audio Services 1
An interface to the WAV sound format. Supports stereo and mono but not compression and decompression Provides utility functions that determine the type of a sound file Python also possesses a Winsound module that provides access to the basic sound-playing machinery on Windows platforms. Winsound includes a single function from the platform API, PlaySound, which takes in a sound parameter argument that can be either a filename, a string that's a string of audio data or None. Winsound's flags are...
Beyond
One problem with 3D titles is the massive amounts of knowledge and work required to design, maintain, and update them. Another is the constant re-engineering each independent gaming company must fund and support in order to create the latest and greatest. Beyond is a reusable object framework for game design that was created to address these problems. The idea behind the Beyond project was to identify which parts of the process are works that could be reusable, and then wrap them up as...
LibgdRuby
GD is a library by Thomas Boutell that is used for dynamically creating graphic images, particularly PNG and JPEG images, and Libgd-Ruby is a package extension library that allows Ruby to wrap around GD. Libgd is written in C, and is considered freeware. It is dependent on several other libraries, including libc6, the GNU C Library, FreeType 2, the GD Graphics Library, and The Independent JPEG Group's JPEG runtime library. Details can be found at the following links Libgd-Ruby. GD Library. http...
Table Tkinter Widget Methods Function
Returns the name of the window that contains the widget and has focus Returns the identity of the window that has focus Returns the window that last had focus Returns the value of a Tkinter variable Grabs all events for the entire screen for the widget Returns none, iocai, or giobai depending upon the grab value set to a window Returns all options available for a widget as a tuple Moves a widget to the top of the window stack Same as iift Moves a widget to the bottom of the windows stack Sets a...
Figure Using brackets to input a string over multiple lines
ClIDocuiWllS and S. 1hh-1n4 ii.vd lua 5.0 copiiri ht lt c gt 1994-2w3 incgpaf tuc-rio gt function EtarunctiimO gt gt ppint C'TjMsi Tin our Jfi build in a. fucntion' gt gt gt plaint ''s it i4snt B-xecutedl y t,p gt ypint ,Bit 15- si-sit iinj for a cig n f ron fl ' 1 Lua comes packaged with additional library string functions. These are not necessary to import Lua but are very helpful if you are working on an application with heavy string handling. These functions are listed in Table 6.6 the...
Sdl Getmousestate Slow
This law is usually expressed by G m1 G m2 rA2, where G is the gravitational constant, ml is the mass of the first object, m2 is the mass of the second object, and r is the distance between the two objects. This formula is used in obstacie_update by taking the gravity_constant and the mass of an object a .mass and accelerating actors towards other actors if the actor has mass then compute a gravitational acceleration towards it local r a.position - self.position local d2 r r if d2 1 100 100...
Dictionaries
Python has a third structure that is also similar to a list these are called dictionaries and are indexed by assigned keys instead of automatic numeric list. Often called associative arrays or hashes in other languages, dictionaries are created in Python in much the same way as lists, except that they are used to create indexes that can be referenced by corresponding keys. An example of this might be a phone directory, where each telephone number value can be referenced by a person's name key ....
Creating a Main Event Loop that Listens for Events
To create a main loop, you normally define a main function containing a while loop do stuff if name main main This ensures that main is called and your while loop keeps running during the course of the game. As good coding practice, initialize a few variables inside of main global screen global background global snakesprites global block You are also going to take advantage of a Pygame clock feature and use random's seed method to set a random number seed. Since you are going to be experiencing...
Table Freedom Force CutScene Methods
isplaying Determines whether a cut-scene or scripted sequence is startcsN rmalScreen Starts a cut-scene but doesn't go into widescreen mode isCSplaying Returns true if a cut-scene is currently playing playTransition Plays the logo transition Using these methods to start and stop a cut-scene would look like the following Define Cutscene MyCutscene Start Cutscene startCS , End Cutscene endCS , Those who have been paying attention will notice that cut-scenes in Freedom Force are Python lists here...
Table Tkinter Keyboard Events Effect
Pressed Alt and another key Pressed Ctrl and another key Pressed the Esc key Press any key carries the character pressed via a callback Pressed the Enter key Pressed Shift and another key The object that originated the callback exposes the attributes for events. These attributes are listed in Table 4.22. lt Button -1 gt lt Button -2 gt lt Button -3 gt lt B1 -Motion gt lt ButtonRelease -1 gt lt Double - Button - lt Enter gt lt Leave gt lt Alt -x gt lt Control -X gt lt Escape gt lt key gt lt...
Figure The embedding Python process
Py Initialize Py Finalize return Py_initialize is the basic initialization function it allocates resources for the interpreter to start using the API. In particular, it initializes and creates the Python sys, exceptions, builtin , and main modules. Py_initialize searches for modules assuming that the Python library is in a fixed location, which is a detail that may need to be altered, depending on the operating system. Trouble with this function may indicate a need to set the operating system's...
ToonTown
ToonTown, an online cartoon style mulit-player game, is the latest from the Walt Disney Imagineering studio. Players create their own cartoon avatars and explore a rich world where they can meet and interact with other toons, earnjelly beans to put in the bank, and buy things like a toon house or items for a toon house . There is even a bit of conflict thrown in, in the form of a Cog Invasion that is threatening the city. Disney's ToonTown uses Python in a direct and powerful way. The ToonTown...
Program Structure
All programming languages have some sort of structure or flow to them. Most programs share a structure similar to that in Figure 2.1. Normally there is a statement that establishes the beginning of a program, then variables are declared, and then there are code blocks, which are also called program statements. Figure 2.1 A typical program structure Figure 2.1 A typical program structure Program statements provide the control of a program. They usually act as decision trees, executing different...
Tkinter Events
Events in Tkinter are user events like keyboard presses and mouse movements. Tkinter handles events by creating bindings for specific objects. You can bind events to a widget, to the widget's Toplevel window, to a widget's class, or to an entire application. Once an event has been bound to a widget, you specify a callback, which is a function that is called when the event happens. Let's say you had a function called My_Event Let's say you want My_Event to be called by a widget button called...
Math and Algebraic Functions
When it comes right down to it, your computer is speaking a language of Os and 1s. It's no surprise, then, that math tools, functions, and operators tend to be similar across all languages. You can pretty much bank on functions like add , subtract - , multiply , and divide being available no matter what programming language you are using. Another commonality between Python, Lua, and Ruby is using parentheses to state precedence this comes right out of high school algebra. For instance, the...
Garbage Collection
Lua uses two variables to control its garbage collection cycles. The first keeps track of how many bytes of dynamic memory Lua is using. The second variable is a threshold that, when hit, tells Lua to run the collector. These are accessible and changeable via the C API and through the gcinfo and collectgarbage functions. Lua first counts the amount of memory it is using. If the count reaches the threshold, it runs the garbage collector. After the collection, the count is updated and the...
Figure Vectors in physics combine magnitude and direction
Victors combine magnitude and direction. In this figure, magnitude is represented by length, or the distance between x and y, and direction is represented by which way the arrow poinls. In geometry, vectors consist of a point or a location in space, a direction, and distance. The combination of direction and distance is sometimes called displacement. The vec2 function helps to keep track of vectors using x and y coordinates, as shown in Figure 7.6. The starting coordinates are a .x and a. y,...
Stackless Python
Stackless Python is a development effort led by Christian Tismer, and is a Python variant that doesn't use the C stack. The Python interpreter is written in C, so at some level every Python action is executed via C. Mostly this is good, but sometimes having multiple instances of Python C code running on the stack can cause problems, for example with recursion and with object references that build up on the stack. Stackless has received quite a bit of community support and has been highlighted...
The Event System
In order for Pygame to respond to a player or user event, you normally set up a loop or event queue to handle incoming requests mouse clicks or key presses . This loop is a main while loop that checks and makes sure that the player is still playing the game for event in pygame.event.get if event.type is QUIT The for event line uses pygame. event. get to get input from the user. Pygame understands basic Windows commands, and knows that quit is equivalent to pressing the X at the top right corner...
Table Common Type API Command 1
VALUE rb_str_cat VALUE rb_str_concat VALUE rb_str_new VALUE rb_thread_create VALUE rb_yield void rb ary store void rb bug void rb cvar set void rb cv set void rb define alias void rb define attr void rb define class variable void rb define global const void rb define global function void rb define hooked variable void rb define singleton method void rb define variable
Tuples
Python also has a structure called a tuple. Tuples are similar to lists and are treated similarly, except that they are designated by parentheses instead of brackets You don't actually need parentheses to create a tuple, but it is considered thoughtful to include them You can create an empty tuple by not including anything in parentheses There is also a version of the tuple, called a singleton, that only has one value While lists normally hold sequences of similar data, tuples by convention are...
Python Adventure Writing System
The Python Adventure Writing System PAWS is a text adventure system developed by Roger Plowman. As with many Python-based game tools, PAWS is aimed at the non-programmer and consists of a game engine, a world library, and a play module. PAWS is fairly well documented, and comes with a few sample games and two great explanatory texts, one aimed towards first-time game writers and another, aimed towards code-heads, that explains how the Python sources work. Even the source code itself is well...
Obstacles
The game obstacles are cows and planets. These obstacles must track a number of different things in order to make the game interesting. Obstacles can take damage. Some of the bigger objects will survive collisions with several smaller objects, so they need to track how much damage they can take. Obstacles need to know when they collide with something. Obstacles are drawn to each other by gravity, and so they need to keep track of other nearby obstacles. Obstacles should also occasionally appear...
Sound in Python
Like with graphics, there are a number of available libraries for implementing sound in Python. PythonWare Sound Toolkit. An unfortunately abandoned kit for reading and playing AU, VOC, and WAV files on Windows and Sun OSs. The unfinished tookit is still available from PythonWare at http www.pythonware.com. PythonWare is a copyrighted, but free to use, library. Boodler. An interesting tool for creating soundscapes which uses Python and is created for UNIX operating systems although some work on...
Alice
Alice is a tool for developing three-dimensional graphics, built around the concept of 3D for everyone. Most 3D engines require the programmer to know extensive trigonometry, vector algebra, and other painful math. Alice is designed to provide non-programmers with access to 3D programming and interactive worlds. One of the things that makes Alice powerful is that it has a very straightforward, easy-to-learn GUI shown in Figure 5.4 for placing, sizing, tweaking, and animating three-dimensional...
The Snack Sound Toolkit for Ruby
The Snack Sound Toolkit is a collection of sound- and voice-processing routines and includes tools for speech recognition, formant tracking and synthesis, and other fun sound-and speech-based tools. The toolkit, written by Stephen Legrand, is used to extend scripting languages and enable such tools within them Ruby is its prodigy pilot-child. The original implementation of Snack was inspired by Kare Sjolander and was extended to Tcl Tk. Snack for Ruby leverages the existing Tk graphics and...
Freedom Force
Freedom Force, a popular super-hero multiplayer game from Irrational Games, was nominated for handfuls of PC Gamer's annual 2002 awards, and Irrational is currently working on an expansion of the game. Irrational used NDL's NetImmerse game engine and Freedom Force was co-published by Crave Entertainment and Electronic Arts. Many of the game's functions were exported to the Python side, so that Python could set and move objects and control camera movements. The single-player levels were scripted...
Python Pros and Cons
Python has more extension modules than the other languages. Many online Python tutorials exist. There are also plenty of English books and reference materials, many sample scripts exist online, and there is a wealth of introductory material. The Python.org Website is a good place to start looking for these because it has sections for beginners, tutorials, guides organized by topic, and lists of links and references. Most folks really enjoy the syntax of the Python language because it appears...
Pygame Drawbacks
Pygame is simply a wrapper around SDL, which is a wrapper around operating system graphic calls. Although programming is much easier when using Pygame than when using SDL, Pygame removes you pretty far from the code that actually does the work, and this can be limiting in a number of ways. Probably the most significant drawback to Pygame, however, is the fact that the library needs so many dependencies in order to function. Obviously, Pygame needs Python and SDL to run, but it also needs...
Drawing a Square
Our third function is the code that actually draws the display, so let's call it drawgraphics . This function will actually display everything that goes onto the screen, so it will be doing most of the work in each example. First you glclear to clear the screen to a color, clear the buffer, and then reset with glLoadidentity. glLoadidentity actually moves you to the center of the screen, which is 0,0 on the x- and y-axis. Left and down are negative numbers, and right and up would be positive...
The Pygame Surface
The most important element in Pygame is the surface. The surface is a blank slate, and is the space on which you place lines, images, color, and so on. A surface can be any size, and you can have any number of them. The display surface of the screen is set with You can create surfaces that have images with image. load , surfaces that contain text with font. render , and blank surfaces with surface . There are also many surface functions, the most important being blit , fill , set_at , and...
The Cyclon Online Gaming Engine
The Cyclon Online Gaming Engine COG for short is an open-source computer game-authoring system. The system comes with a development application to facilitate game creation, a fill-in-the-blanks GUI that brings up windows in which you set up the game information, player information, rooms, directions, items, events, and even define action verbs that can be taken in by the text parser. The development application is shown in Figure 5.1. Figure 5.1. The COG development application Figure 5.1. The...
Arkhart
Arkhart is an original fantasy role-playing game that uses a unique engine called the Ark engine. The Ark engine and Arkhart itself are built upon Lua and SDL. Ark provides tools, a 3D client, and Lua scripting facilities to those who want to try their hand at 3D programming Lua-style. The Arkhart home page can be found at http arkhart.nekeme.net en . The Arkhart code was originally built with JavaScript and Mozilla'sjslib, but it grew so large that the authors migrated to the current SDL...
Table Debug Commands
Set breakpoint at specified line or method Set a watchpoint for an expression Set display expression to be printed when program stops Step forward in the program until the next source line Step forward in the program until the next source line. Treat method calls as one instruction Select stack frame that called current stack frame Select stack frame called by current stack frame Execute until selected stack frame returns Turn trace mode on or off Exit debugger Show global variables in current...
The Engine and the Game Loop
A number of actions must happen in the engine and game loop, and these actions should correspond to a codeable function. You must have a function to remove any sprites that aren't being used and add any new ones, a function to render the screen and background, a function that keeps track of time and updates the game state, a function that does the blitting, and a function that listens for player keystrokes render_frame. Updates and redraws. engine_init. Sets screen and video. engine_loop. Main...
Pros and Cons of Ruby
Ruby possesses fairly good advanced debuggers. Ruby is object oriented from the ground up, and programmers who are OOP enthusiasts or who are used to the OOP paradigm will find the language extremely comfortable. Ruby has arguably the simplest syntax, with no real rules exceptions. Especially true for OOP enthusiasts. Lack of English documentation. Fewer existing works and samples for games than with the other languages. Programming is turning more and more into an everyman's tool. Every...
Table Tkinter Widget Methods MethodFunction
cget Returns a string that contains the current configuration value for config Sets the values for one or more options destroy focus focus set focus dispiay focus force focus get focus iastfor getvar grab set grab reiease grab set giobai keys iift tkraise iower mainioop quit setvar update update idietasks ' tk focusNext tk focusPrev wait variabie
A Pygame Game Loop
A Pygame game loop is usually very straightforward. After loading modules and defining variables and functions, youjust need a loop that looks at user input and then updates graphics. This can be done with only a few lines of code. A typical event loop in a game would look something like this for event in pygame.event.get if event.type QUIT exit or quit function goes here return screen.blit MY_Window, 0, 0 pygame.display.flip The pygame . event module looks for user input, and pygame . blit and...
Lixoo
Lixoo is a small, 2D, mouse-driven adventure game engine designed for conversation and character-based computer games. Lixoo consists of both the driving graphics engine and also a number of tools for users to build their games with. The main use of Lua in Lixoo is as an IDE with modules for creating rooms, characters, music, and animation. Currently, Lixoo is under development and works only on OS X and Linux. It was originally written with ZeroForce a small C library but has since moved to C...
ActiveState
ActiveState is a company that focuses on applied open source. It creates development packages for software developers and provides resources for Perl, Python, and PHP development. ActiveState currently has a Python distribution called ActivePython. It also supports creating Python RPM Red Hat Package Managers installers, Windows complete installers, and a Visual Studio .NET IDE plug-in for Python. These services some are free, others not are available at the ActiveState Python Website, at
Severance Blade of Darkness
Severance Blade of Darkness is a fantasy combat game from Codemasters Rebel Act Studios which is now defunct . It is a mature-audience game released in 2001 along with a level editor called LED and a set of tools called RAS for making levels and mods, which are, of course, based on Python and wholly scriptable. A Blade of Darkness level generally includes A .bw file which has the map architecture details, compiled from the LED map editor uncompiled maps are .mp files . .mmp files, which are...
Building a load sound Function
A Pygame load_sound function would look very similar to the load_image function you created at the beginning of this chapter. You start by defining the function, which takes in the name of the sound file The load_sound code should check to see if pygame .mixer the Pygame module that loads up sounds is installed. If pygame .mixer isn't available, Pygame will not be able to load the sound. Pygame has a built-in feature called Nonesound, which, if used, will send a blank sound object if the file...
Chapter HighLevel Language Overview
All programmers are playwrights, and all computers are lousy actors. -Unknown, quoted by Michael Moncur in The Quotations Page Where to start There is much to cover, and we have a very short time together. This is Chapter 1 of Game Programming with Python, Lua, and Ruby. In this chapter I'll discuss the specific pros and cons of programming with these high-level scripting languages after explaining what a high-level scripting language is, of course , delve into their properties and history, and...
Initializing SDL
The init module is used to initiate SDL. A flag that triggers which portion of SDL needs to be initialized is included when initializing SDL INIT_AUDIO. Initialize system audio. SDL INIT_VIDEO. Initialize system video. SDL INIT CDROM. Initialize the CD-ROM. SDL INIT_J0YSTICK. Initialize ajoystick device. The line of code that will initialize video looks like the following A particular game's video mode is set with sdl . set_video_mode , which takes as arguments the width and height of the...
Blender
Blender is a 3D graphics suite with a tumultuous history. Originally, Blender was a rewrite of the Netherlands animation house NeoGeo's 3D toolset. One of the co-founders of NeoGeo, Ton Roosendaal, also founded a spin-off company called Not another Number NaN . This company's model was to further develop and market Blender technology. Initially this company faired very well, raising millions of dollars and gaining thousands of customers, but it was hit with hard economic times. In 2001, the...









