Brief History of Structured Programming

In thel960s software development went through a number of growing pains. Development schedules often ran far behind predictions, costs were much higher than projected, and often the end software product was unreliable or buggy. People began to realize that software development was extremely difficult, and some folks began to research development methods of this new field to see what could be improved. Out of this research came the concept of structured programming. Structured programming is a...

About the Author

Thomas Gutschmidt has been professionally involved in the computer industry for the past seven years and currently works for a large software company headquartered in Redmond, Washington. He has been a freelance author and writer for three years and has been involved in several open source game projects and module development projects. He currently lives in the Northwest with his wonderful wife, Susan, their four cats, two rats, several goldfish, and the occasional urban wildlife refugee.

Apocalyx D Engine

Apocalyx is an OpenGL 3D engine that includes Lua scripting support. The engine comes with a built-in console that can be launched and will fire Lua scripts or execute lines of Lua. The following commands are viable on the command-line console h. Reads the complete list of commands. l. Reads a list of the scripts. r. Executes a script. c. Compiles a script. Apocalyx has an entire API with exposed features and classes for Lua to manipulate. These classes are highlighted in Table 8.18, but for...

Chapter Python Lua and Ruby Language Features

The limits of my language means the limits of my world. -Ludwig Wittgenstein This chapter serves as an introduction to common features of Python, Lua, and Ruby. I introduced each language in Chapter 1, and in this chapter I'll be going into more details of the languages. There are two main goals for the chapter. The first is to give you a foundation for learning how to use these languages by covering a few features they have in common. The second objective for this chapter is to start you...

Chapter The Ruby Game Community

The gem cannot be polished without friction, nor man perfected without trials. -Chinese proverb Ruby is probably the least entrenched of the languages within English-speaking gamedevelopment companies. It is found much more often in the scientific and research community than in the game and entertainment industries. This doesn't mean that Ruby can't be found hard at work in the game field, though it's been a part of a number of large-scale projects involving games. This chapter highlights a few...

Conditional Control Statements

Statements that are considered conditional are often referred to as if else statements. The commands if and else determine which lines or blocks of code might or might not run, depending on the flow of the program. Programmers generally use these as branches to initiate actions that are dependent on user input. The if command is the foundation of all conditional statements. if checks a specified condition for truth value. If the condition is true, then if executes a code block that follows. If...

Create main and Set Up Pygame

The main () function is where all of the fun happens. The game needs a number of variables defined, some of which change constantly and others that never change at all (called constants). The first trick is to get all of these straight. First set Constants (all capitalized by convention) Time to wait between frames WAiT_TiME 20 Set the course to be 25 screens long at 480 pixels per screen COURSE_DEPTH 2 5 * 480 Seeds the number of trees on the screen NUMBER_TREES 5 vertical distance traveled...

Creating a Pygame Window

Creating a window in which Pygame can run an application is fairly easy. First you need to start up Pygame with an initialize command Then you can set up a window with a caption by using Pygame's display command My Window pygame.display.set mode((640, 480 This code run by itself (the code is included as the My_window. py example in this chapter's code section on the CD) creates a 640x480-pixel window labeled Pygame Window,just like in Figure 4.2. Of course, the window accomplishes nothing, so...

Cs Hello World

For comparison, let's see what Hello from C would look like. There are many different ways to get C to print a string, but typically the effort looks like the following This program displays the string hello . It first Includes the stdio.h library, then creates a main, then creates a short loop, and then prints the string. The comments are the same as in Python, but besides the comments you can see that the program is very different. First, C doesn't have a built-in print function, so you need...

Do Lua st u return o

The term virtual machine (VM) was coined by Sun Microsystems to describe the runtime environment for their budding Java language. A VM acts as an interface between a compiled binary code and an operating system. Lua has been designed as an extension language but it can be used as a stand-alone language as well. The Lua interpreter (named lua.exe) can be called via command line to execute Lua files (known by their .lua extension) and accepts a number of arguments, as shown in Table 2.7. 2.7. Lua...

Drawing and Updating Necessary Graphics

For drawing, you start by initializing all of your sprites and sprite groups in main () allsprites pygame.sprite.RenderUpdates() snakesprites pygame.sprite.RenderUpdates() block None The code that does all the work lies at the end of the while loop, which clears the sprite groups then updates and redraws each changed rect () allsprites.clear( screen, background) snakesprites.clear(screen, background) allsprites.update() changedRects2 allsprites.draw(screen) changedRects3...

Drawing and Updating within the while Loop

Now you need to set up the while loop that updates all the sprites, keeps track of time, and renders everything. The while loop will be set to run until the course is over Then there are a few things you need to do with timing to make sure the game flows smoothly currentTime pygame.time.get ticks() Wait In case we are moving too fast if currentTime < nextTime pygame.time.delay( nextTime - currentTime ) Update the time nextTime currentTime + WAIT TIME Then check for sprites that are dirty...

Drawing with Pygame

Pygame has great built-in functions for graphics. These functions revolve around the idea of the surface, which is basically an area that can be drawn upon. Let's say you wanted to fill the background in My_window. py with a color. First grab the size of the window My Background pygame.Surface(My Window.get size()) This creates a surface called My_Background that's the exact size of My_Window. Next convert the surface to a pixel format that Pygame can play with My Background My...

Extending Python Lua and Ruby

Extending is one of the super powers Python, Lua, and Ruby have to offer. Extending is basically the ability to combine code from two or more different languages into one running executable or script. Although this adds a layer of complexity to a project, it gives a developer the ability to pick and choose from the existing toolbox. All of these languages are built around being extensible extensibility is one of the features that has made them so prolific. The language documentation that comes...

Figure A sample scene from MAD

0 li CMl type ll ti dell he dji 1 Milling RpEi nTypE llji reblellinlcxedlty - llaglmgj urilh 4 element ilnnr 1.1.1 dinr Hpri(*3y in ie lu njm h UtijCL-l ty ji rKprn4liiii i1c1lni d.l l.n dlDI Kprilr ypr c> qi ggivn , r bLi i _- I i JcjicJUy ii'ij J wilh 1 clcmeni -done liudinLi Surllclyne d nH Hln Vo h i prol.ljall Loading EnritrTvp e Iiu II n , done I adding I j p ril p 1 ypr-Objecttypr ini - Jli- liEiinrd.l Lading SprHcTypclrolsille dant landing HpfHtlype tf nl i li (lu nfc nil iili .l...

Figure An instance of the Monkey Spri te class travels across the screen

You need one more actor, a banana, which the Monkey_sprite objects will throw at and destroy the snake objects with. This means you need methods for the banana to update and move and check for collisions class Banana(pygame.sprite.Sprite) def init (self, rect, game) def update(self) def move(self) def check hit(self) Initializing the banana sprite works much like the other _init_ methods. There will be an incremental value that defines how many pixels the banana...

Figure The LED editor with an open sample file

N *-- -JSIB -t - mom- 3 HJll r jr -. . Hill * t n *-- -JSIB -t - mom- 3 HJll r jr -. . Hill * t In the Python scripts, you'll find that objects (weapons, torches, and so on) are usually defined with a objs.py file, players with a pl.py file, configurations with a cfg.py file, the placement of the sun and its position with a sol.py file, and any water coordinates with a agua.py file. Take a look at a sample agua.py file Water,72 000,398 00,-2 000) pooll.Reflection 0.9 pooll.Color 9 0, 2 0, 2 0...

Figure The Windows Python Installer in action

Vj. lor iff- Fytrjri ft* WndhvS fluche h*(i> < ljWt*lMleiiiO' -com Wik 5chXcns,foi Iht jxd Inslf VH-3SI ei 0 I Hav Hjinmond. WJIkjui irfiott J JI (V fa i) WhOow fl> r ni t. fyhflnfai Wrdort sli be Py hr.n In DOS PjJ iri ZZ 2 h twi twciis > *i4Mi l. 1 ei F the Finirai butfim Ihis TirtAsim LwiirO. b ilk V- rl BfcW. Vj. lor iff- Fytrjri ft* WndhvS fluche h*(i> < ljWt*lMleiiiO' -com Wik 5chXcns,foi Iht jxd Inslf VH-3SI ei 0 I Hav Hjinmond. WJIkjui irfiott J JI...

High Level Languages in the Development Cycle

There are a number of advantages for using a high-level language in a development project. These advantages include Automated garbage collection. High-level features like built-in pattern matching and built-in types. Coding is less time-consuming. Lower costs than using an internally built language. High-level languages are easily embedded, modular, and extensible. Artists, level designers, and even employees with little computer science experience can easily grasp and understand high-level...

Importing Pygame

The first step towards using Pygame after it has been installed is to import the Pygame and other modules needed for development into your code. Do the following Keep in mind that Python code is case-sensitive, so for Python, Pygame and pygame are totally different creatures. Although I capitalize Pygame in this book's text, when importing the module, pygame needs to be in all lowercase letters. First import a few non-Pygame modules. You'll use the os and sys libraries in the next few examples...

Importing the Necessary Libraries

Importing has been covered ad nauseum already, so I will not bore you with the details. Simply start with this code Step 1 - importing the necessary libraries import pygame, os import random These libraries should be familiar to you with the exception of the random module. Python comes equipped with random, and we will be using the random, randrange method to generate random numbers. The random, randrange method generates a random number (an integer) within the range given. For instance, this...

Installing Pygame

This book's CD comes with a copy ofPygame in the PYTHON PYGAME folder. The most recent versions can be found online at The Windows binary installer on the CD has versions for Python 2.3 and 2.2, there is a Mac .sit for older Mac versions and a version for the Mac OSX, and the RPM binary has been included for the Red Hat operating system. Pygame actually comes with the most recent and standard UNIX distributions, and can be automatically built and installed by the ports manager. On Windows, the...

Installing Python

This book's CD-ROM comes with the tar archive and the Windows installer for Python Version 2.2.2 (released in October of 2002) you can find them in the Python folder. You can also download Python installers for a number of other different platforms from the Python.org Website at http www.Python.org download. As of this writing, Python 2.32 alpha is available from Python.org in Windows. The alpha is also included on the CD, but the samples in this book were written with Version 2.22. Simply...

Language Types

Python includes a handful of built-in data types (see Table 3.1) the most commonly used of these data types are numbers, strings, lists, dictionaries, and tuples. Numbers are fairly obvious, although there are several different number types, depending upon the complexity and length of the number that needs to be stored. Strings are simply rows of letters. Lists are groups that are usually comprised of numbers or letters. Dictionaries and tuples are advanced variable types that are similar to...

Letter from the Series Editor

Game development has reached a fever pitch in the past couple of years photorealistic rendering, advanced physics modeling, a million-plus polygon worlds and multiprocessor consoles and PCs are powering the revolution. At the same time, experimentation with scripting languages to help control the high-level aspects of games has gone from a convenience to an absolute necessity. No longer can game programmers think of something as absurd as writing a game in C C++. Game engines may be written in...

Luas Hello World

Lua is quite different than the other two languages presented in this book. Lua is primarily an extension language, and Lua code is usually embedded within a host. You'll find Lua residing inside C, Python, and Ruby scripts, doing what it does best acting as code within code. In-depth coverage of how to program with Lua is covered in Section 2 of this book, and what follows isjust an example to whet one's appetite. With the understanding that a Lua Hello World program would normally exist...

Memory Performance and Speed

Ruby suffers from the same speed impediment as the other languages in this book being interpretive and-high level. Ruby's built-in profiler tool helps quite a bit when gauging performance by examining code snips and routines for slowdowns. The profiler can be called from the command line by adding -r profile, or it can be used inside code by using require, like so The profile library will print a summary of the number of calls to each Ruby method in the given program and the time spent in each...

Other Games

There are dozens of other titles that have used Lua. Criterion Studios is one of the larger companies, located online at http www.criterionstudios.com. Criterion has released several 3D game titles here and in Japan that use Lua as their primary game scripting language. The popular fantasy RPG Pern made extensive use of Lua, so much so that the community spawned several hacks to the engine overriding some of the common Lua files that handled races and classes. Slingshot Game Technologies...

Packaging Python Code

When modules are imported in Python by other modules, Python compiles the relevant code into byte-code, an intermediate, portable, closer-to-low-level binary language form. This byte-code is stored with the .pyc suffix, short for Python compiled, instead of the typical .py. Python's .pyc files correspond roughly to DLLs (dynamically loaded libraries) used in C. Regular .py modules can be used dynamically, too, but the compiled Python code is tighter and Python interprets the code at runtime...

Performance and Speed

If you write Python code to do complex numerical work and then compare the results to those done with C++, you will be disappointed. The plain truth is that Python is a slower language. In Python, every variable reference is a hash table lookup, and so is every function call. This cannot compete with C++, in which the locations of variables and functions are decided at compile time. However, this does not mean that Python is not suitable for game programming itjust means that you have to use it...

Playing a Sound with Pygame

You can play a sound using Python Pygame withjust a few short lines of code. First do the typical pygame import and the os module import so that you can find files on the native operating system SND_PURGE SND_ASYNC SND_NODEFAULT SND_NOSTOP SND NOWAIT After importing the needed libraries, you initialize pygame Pygame's cross-platform music tools for sound effects and music are built through the mixer module, so you use pygame .mixer to load the sound, and the built-in play () method to play it...

Problems with Extending

As I've already mentioned, multilanguage development adds an extra layer of complexity. Particular problems with extending are as follows You must debug in two languages simultaneously. You must develop and maintain glue code that ties the languages together (this might be significantly large amounts of code). Different languages may have different execution models. Object layouts between languages may be completely different. Changes to one side of the code affect the other side, creating...

Purpose Arguments

Connects actors and stones Actor, object, strength, length that are then pulled together with given strength Draws floor alternating between two tiles Creates an object on the map, used internally by other functions Floor name, friction, and mouse factor floorl, floor2, location (x,y), size (height,width), attributes Given stone (optional location in x,y,z coordinates and height + width) Floor name, x and y coordinates and increments, and attributes Item name, x and y coordinates and...

Python Features

Python was developed by Guido van Rossum at the National Research Institute for Mathematics and Computer Science (otherwise known as CWI) in the Netherlands. Python is copyrighted, but the source code is open source and freely available. And yes, the language is named after the TV series Monty Python's Flying Circus. Python's feature highlights include A broad standard library, one of Python's greatest strengths. The bulk of the library is very portable and cross-platform compatible on UNIX,...

Python Graphics

Choosing a graphics toolkit may be the most difficult choice when creating a game. There are hundreds of graphic kits to choose from and each is very different in style and language. This chapter only covers a handful of the graphics libraries available for Python programming, and goes through samples in only a few of the available options mainly the popular kits available for developing cross-platform. Specifically, more coverage of Tkinter is given in this section, as Tkinter comes bundled...

Rotation and Movement

Now that you can color the square, let's try to rotate it. To do so, you need to add a bit to the drawgraphics function. First, make use of the rquad (rquad is short for rotate quad) variable by declaring it a global and then calling the glRotatef () function. Use a variable for rotation so that you have fine-grain control over the movement. glRotatef (angle, x, y, z) produces a rotationof a givenangle indegrees over a given vertices given in x, y, and z coordinates. The command takes four...

Ruby Features

Ruby was created by Yukihiro Matsumoto in 1993. The language is open source, and its use is covered under the GPL artistic license. Matz, as he is affectionately known, knew Python, but he didn't like it because it wasn't pure OOP. He wanted a genuine OOP scripting language that was easy to use and write. Ruby's name, however, is a takeoff on Perl and is named after a colleague's birthstone. Pure OOP. Every bit of data in Ruby is an object, even basic types. There are no Ruby functions, only...

Scripting Languages

Scripting is a term used to denote the scripting of a computer, akin to an actor who follows a script to perform a play. A scripting language is a high-level language used to assemble components into a predefined software architecture. Scripting languages, sometimes called glue-languages, are designed for scripting the operation of a computer. Normal operations that would be considered scripting are administrative tasks such as running automatic backups, text processing, running server-side...

Setting Up Pygame the Window and the Background

You can initialize Pygame using the init () method within main (). Then you use display. set_mode () to configure the game surface to 640x480 pixels, and the game caption to be Monkey Toss. You then use your load_image method to load up the surface background and initialize blitting and flipping screen pygame.display.set mode((640, 480)) pygame.display.set caption('Monkey Toss') background, tmp rect load image('background.png') screen.blit(background, (0, 0)) pygame.display.flip()

Speed

Lua supports coroutines as independent threads of execution. This isn't, however, a true independent multi-threaded system it is a semi-collaborative multithreading system. That means a coroutine only suspends its execution by explicitly calling a yield routine. Lua also offers some support for multiple threads of execution via its C API, so if you have C libraries that offer kicking, then multi-threading Lua can cooperate with them. Although garbage collection can be monitored and controlled,...

Table Additional Math Lua Library Functions

Math.acos math.asin math.atan math.atan2 math.ceil math.cos math.exp math.floor math.frexp math.ldexp math.log math.loglO math.mod math.pi math.pow math.sin math.sqrt math.tan math.random math.randomseed As atan but uses signs of the arguments to compute quadrant of the return value Ceiling, returns smallest integer no less than given argument Returns largest integer no greater than given argument Turns argument number into mantissa and exponent Returns X*(2Aexp) Logarithm Base-10 logarithm...

Table Boolean NOT

Once you understand Boolean logic, comparison operators, and logical structures, you can create very complex decision trees, like this The following line evaluates to Boolean FALSE (((1+2)*5) 11) and ((5*6) (7*6)) The Following line evaluates to Boolean TRUE ((1+1) 5) or ((5*6) 40 and ((5 4) 2*.5)) or ((50 5) 10) Table 2.1. Common Math Functions in Python, Lua, and Ruby Equal (assignment) Equal To Less Than Greater Than Python Command Lua Command Ruby Command

Table Button Properties Function

Displays a given bitmap as the button disabledforeground Sets a foreground color used when button is disabled (grayed Sets an image to display in the widget (precedes bitmap) Defines the button state (as normal, active, or disabled) Indicates whether the Tab key can be used to reach this button Defines the text to display within the button An offset applied on text displayed to identify which character must be underlined Determines distance when text should be wrapped to the next line Buttons...

Table Common Lua Input Output Functions Purpose

Closes the given file Flushes over the default output file Opens the named file in text mode and sets its handle to the default input file Opens the given file name in read mode and returns an iterator function that returns a new line from the file each time it is called Opens a file in the mode specified and returns a new file handler Opens named file in text mode and sets its handle to the default output file Checks if object is a valid file handle Closes file Saves any written data to file...

Table Common Pattern Matching Controls

Using these functions to find patterns and matches is relatively straightforward using string. find. For instance, here is a Lua chunk that searches for the letter o in the given string MySearch string.find('word', 'o') print (MySearch) When this chunk is run in the Lua interpreter, you are given the location of o in the string, which is the second character location, right after 'w' which is first. Let's say that you wanted to find four-letter words that begin with s ina given string. You can...

Table Common Ruby Expressions Expression Description

Exception information message (set by raise) _ Backtrace of the last exception The string matched by the last successful pattern match in this scope N The string preceding whatever was matched by the last successful pattern ' The string following whatever was matched by the last successful pattern The last bracket matched by the last successful search pattern

Table Freedom Force Camera Controls

Angle of pitch around object right vector, in degrees Angle of yaw around object up vector, in degrees Time in seconds it will take to complete the move Set camera snap (cpm_snap, cpm_scrollto, cpm_homing, or cpm_simplepath) Set camera move (ca_move) or tracking (ca_track) Sets a Python script function to call when finished User defined data Not bad for a quick delve into the Freedom Force API and we've reallyjust begun. There are actually a number of other camera commands to set wide-screen,...

Table HZ Engines C Functions for Lua Sprites Function Purpose

C obj setVelocity(objnum,vx,vy) C obj setLayer(objnum,layer number) Main camera will follow this sprite Gets the velocity of a sprite Sets the velocity of a sprite Gets the position (x,y) of a sprite Sets the position (x,y) of a sprite Sets the graphic layer of a sprite These functions take in obj num as their first parameter and x,y coordinates to follow. For instance, here's how to get an object position Co obj setPos(self.objnum, 100, 80) Having the C++ engine do the range checking and math...

Table Lua API Stack Commands

Lua lessthan () lua pushboolean () Concatenates the values at the top of a stack, pops them, and leaves the result at the top Moves the top element to a given index Returns 1 if the object is compatible, otherwise 0 Returns 1 if the object is compatible, otherwise 0 Returns 1 if the object is compatible, otherwise 0 Returns 1 if the object is compatible, otherwise 0 Returns 1 if the object is compatible, otherwise 0 Returns 1 if the object is compatible, otherwise 0 Returns 1 if the object is...

Table Lua System Facilities Purpose

Returns an approximate CPU time, in seconds, used by the program Returns the date and time according to given format Returns the seconds between two given times Passes a command to be executed by the operating system. Equivalent to C's system Calls the C function exit to terminate a program Returns the value of a given environment variable

Table Mixer Methods Method Equivalent To Purpose

AllocateChannels allocate channels Dynamicallychange the number of channels fadelnMusic fadeOutMusic halt N A haltMusic load managed by the mixer Fade in the given music in milliseconds Fade out the given music in milliseconds Halt playing of a particular channel Halt music Load a music file and return the object of Return whether specific channel is playing

Table Pyzzle Modules

Controlling the global game parameters Defining slides. The basic graphics unit The API isn't quite finished as far as documenting goes, butjust opening up the demo game files (check demogame.py) and perusing them can be quite revealing (and, of course, the source code is freely available). Once Pyzzle has been imported, you use parameter methods to set the game parameters like screen size and background color parameters.setScreenSize((800,600)) window size in game...

Table Standard Tkinter Widget Options

Highlightcolor Defines color used to draw the highlight region when widget highlightbackgr und Defines color used to draw the highlight region when widget highlightthickness Defines highlight region width in pixels borderwidth or bd Widthof widget relief border inpixels Contains widget caption text, formatted by foreground and font Sets left, right, or center for text captions Can define font family, font size, and font values like bold, underline, and overstrike Associates a widget with a...

Table Table Functions Purpose

Used to execute a given function over all elements of a table Executes given function over numerical indices (only) of table Returns the size of the table Sorts tables elements in a given order Inserts element at a given position, shifting all other elements Removes element from given position, shifting elements down Updates the size of a table These functions all work in a similar way. For instance, you can use table. getn and table. insert to update a table entry, like so Mytablelength...

Table The gamestate Variables

Last update ticks 0 begin time 0, frames 0, update period update tick active 1, new actors , actors , add actor function(self, a) assert(a) In this table there are a number of variables set to 0 and also a few nested tables. The update_period is the interval in milliseconds between calls to the update tick, and active is a Boolean that says whether the engine is currently active or not. The add_actor function is also defined in this table. The next Lua table is for a sprite cache. This cache...

Table Tkinter Event Callbacks Event

Defines the callback that must be associated to a given event at the application level Defines the callback that must be associated to a given event at the given widget class Widget is resized or moved to a new location Removes bindings for the given event Removes bindings at the application level Removes bindings for the given event at the given widget class Finally, Tkinter has protocols to handle events that communicate between the window manager and the GUI. This allows an application to...

Table Tkinter Widget Components Function

Creates a button that triggers an event when clicked Creates a line that accepts keyboard input Displays text as labels for components Creates a multiple-selection display Creates a pop-up or pull-down style menu Creates a slider that can choose from a range Creates a scrollbar for other components Creates a multiple-line box that accepts user input A widget container like Frame but with its own top-level window TK is a toolkit that handles the creation of windows, GUI events (widgets), and...

Table Toplevel Methods Function

Adds given window to the window group Defines a bitmap for when the window is iconified Defines an icon bitmap for when the window is iconified Defines an icon name for when the window is iconified Defines a suggestion for where the icon goes when the window is iconified Defines the icon window that should be used as an icon Defines the maximum size for the window Defines the minimum size for the window Defines a flag different from 0, and tells the window manager not to add a title or borders...

Table Typical Variable Types Description

A number with a decimal point (floating decimal point) A whole number No value A second example of similarity with variables is that Python and Ruby both use the value method to grab the value of a variable. this code snip uses the value method to return the value of x This line grabs x and prints it in Python print x.value This line grabs x and prints it in Ruby stdout.print(x.value) Many popular languages for instance C, C++, and Perl also use zero (0) as Boolean false. This is not...

Table Useful Group Methods

Makes a copy of the group with all of its members Removes all sprites within the group Returns how many sprites the group contains Removes sprite from the group Returns true if group has any sprites Calls an update method on each sprite within the group Groups of sprites are very useful for tracking game objects. For instance, in an asteroid game, player ships could be one group of sprites, asteroids could be a second group, and enemy starships a third group. Grouping in this way can make it...

The Basic Library

The basic library provides much of Lua's base functionality. The commands involved are listed in Table 6.9. The coroutinefunctions are actually part of a sublibrary of the basic library. Input Output Library Input and output are handled by two file handles. These handles are stored in two global variables _input and _output, the former for reading and the latter for writing. _input and _output are also equivalent to _stdin and _stdout. The common I O functions are listed in Table 6.10.

The Ever Important rect

The most used class in Pygame probably the rect ( ) class, and it is the second most important concept in Pygame. rect () is a class that renders a rectangle rect () comes with utility functions to move, shrink, and inflate itself find a union between itself and other rects and detect collisions. This makes rect () an ideal class for a game object. The position of a rect () is defined by its upper-left corner. The code that rects use to detect overlapping pixels is very optimized, so you will...

The Lua C API

Anything that can be done directly in Lua can also be done in the Lua C API, including manipulating variables and tables, calling functions, controlling the garbage collector, or loading Lua from strings or files. Typically, the Lua C library is compiled into an application or run as a shared library. This is the most common way of accessing Lua in a game program. Altogether, the Lua library is very small, so it is not uncommon to find the entire source tree included with a...

The Lua Environment

The idea behind Lua is that it is to be used as a lightweight configuration language for any program that needs one. It is written in clean C, which means the Lua source code is made up of the most common subset of ANSI C and C++. Since this section is about Lua and this book isn't a book on C, I won't spend a lot of time going over any C code. If you want a primer on the C language, I suggest picking up a book on C there are hundreds to choose from. Lua is implemented as its own library. It's...

The Open Source HAP Debugger

HAP can be found among other open-source Sourceforge projects (http hapdebugger.sourceforge.net ) and is released under the Gnu Lesser General Public Licenses (you can read the license in detail on the CD in the Licenses folder). The HAP debugger can be run remotely, which makes it an ideal tester for a computer game in a lab environment. The game can run on full screen on one machine while a second machine can debug it remotely. The HAP debugger Version 3.0 is included on the CD, under the...

The Pl A Yerrb File

Now the fun stuff the player must be defined with a constructor method (initialize). You need methods to display the player onscreen (w, h, and draw) and move around the screen (act and move lr). But first, the PLAYER.RB file needs help from SYSTEM.RB and STATE.RB require 'system.rb' require 'state.rb' Next, designate the class Playerand define a few player constants class Player INIT_DY -50 DX 2 0 H 32 W 32 G 2 0 These constants initialize the height and width and name of the bitmap image of...

The PyOpenGL Library

PyOpenGL is an OpenGL widget written by a large group of developers, including David Ascher, Mike Hartshorn, Jim Hugunin, and Tom Schwaller. PyOpenGL includes OpenGL bindings for Python created using the Simplified Wrapper and Interface Generator (SWIG) and distributed under open source licenses. It supports OpenGL v1.0, OpenGL v1.1, GLU, GLUT v3.7, GLE 3, WGL 4, and Togl (Tk OpenGL widget). PyOpenGL is also interoperable with Tkinter, wxPython, FxPy, PyGame, and Qt and a large number of other...

The Sta Terb File

There are three classes defined in STATE.RB state, stateinitiaiizer, and stateDriver. Each is used to keep track of the game state, and each is stored within the jt (just in time) module. The state class has two methods, initialize and move_state. state. initialize is probably the most important method inthis script. It first calls the constructor and sets three important instance variables state_hash, state_driver, and state. Using each variable, state. initialize then sets a loop that...

The Systemrb File

The functions set up in the SYSTEM.RB file should look familiar, as they are similar to the functions you used in earlier chapters. The only difference between the first define, setup_bmp, and earlier endeavors to load bitmaps is Ruby's own unique twist graph SDL Surface.loadBMP(filename) graph.setColorKey SDL SRCCOLORKEY, graph 0,0 graph graph.displayFormat end Here sdl Surface. loadBMP is used to grab a .BMP file, the colorkey is set with the setColorKey method, and finally, displayFormat is...

The while Loop

A second common loop is known as the while loop (sometimes known as the do while loop). A while loop is normally used to keep a section of code continually running while a certain condition is true. The flow of this loop is shown in Figure 2.7. Figure 2.7 A flowchart that illustrates a typical while loop Figure 2.7 A flowchart that illustrates a typical while loop The while loop takes on the general structure of Each language, again, has its own nuances, but the while loop looks fairly similar...

Typical High Level Language Tasks Typical Low Level Language Tasks

Call low-level language CPU intensive tasks Game code default Graphics rendering system User interface Tasks with many quick iterations Perhaps the biggest benefit to development is using a scripting language to drive data. Over the years, companies have discovered that it is not a good idea to bury game parameters like movement speed, character strength, and unit hit points for example deep down in executable code. If these attributes are buried, play testing becomes an extremely lengthy...

Whats on the CDROM

The CD that comes with this book is designed to launch automatically when inserted into a machine running the Windows operating system. On the CD is the source code for all of the samples and programs written in the book. These are separated into folders organized by chapter. The CD also contains the software necessary to install Python, Ruby, or Lua on your system. This software is also separated into different folders a Python folder, a Ruby folder, and a Lua folder. Also on the CD are...

Writing a Python Extension

You must write a wrapper in order to access a second language via a Python extension. The wrapper acts as glue between the two languages, converting function arguments from Python into the second language and then returning results to Python in a way that Python can understand. For example, say you have a simple C function called *code that does something useful* A Python wrapper for function looks something like the following PyObject *wrap function(PyObject *self, PyObject *args) if ( PyArg...

Figure Setting alpha values using Adobe Photoshop

Setting Alpha Photoshop

To turn colorkey blitting on, you simply use surface. set_colorkey color . The color fed to surface. set_colorkey is three-digit tuple 0,0,0 with the first number being the red value, the second green, and the third blue that is, rgb . Both colorkey and alpha are techniques for making parts of a graphic transparent when traveling across the screen. In Pygame, most 2D game objects and sprites are rects, and are rectangular in shape. This means you need a way to make part of the rectangle...

Figure The flat plane becomes a full rotating cube

Pyopengl Glrotatef Spin

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 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...

Program Structure

Ruby 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...

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...

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...

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...

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...

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 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...

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...

Chapter High Level 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...

Lua Pros and Cons

Lua is probably the fastest of the three languages and usually uses the least amount of runtime memory. Lau has the smallest memory footprint for bundling. The Lau C API is very well documented and has good examples for integrating with C. The documentation has improved but is still a bit sketchy overall. Of the three languages, Lua it is probably the least documented the API being the exception , with the least amount of code comments. This makes for the largest ramp-up time to learn, and...

Gravity A Lua SDL Game

I first introduced SDL way back in Chapter 4, where you used it with Python to do some pretty amazing stuff. Lua's SDL bindings aren't quite as complete, and unfortunately they are also a little out-of-date. The bindings are still in beta Version 0.3 as of this writing and were put together using the Lua 4 interpreter the binary module has been pre-packaged with the toLua tool . Because of this, all of the necessary Lua scripts are bundled with the game inside the folder so you don't try...

Tryexcept Code Blocks

Being able to fail gracefully is important in programming. Basically, you always need to leave a back door, or way out of a program, for if an error occurs. You'll find that try except or try finally constructs are very common. Python offers a try except else construct that allows developers to trap different types of errors and then execute appropriate exception-handling code. try except actually looksjust like a series of if elif else program flow commands execute this block if errorl is...

Putting It All Together

In this section you'll take a bit from each previous part in the chapter to create a sample game. This sample is called Snowboard .py and can be found along with its data files in this chapters section on the CD. Snowboard has a structure similar to the Monkey_Toss. py sample from earlier, and you'll follow the same general steps during creation 1. Import the necessary libraries. 2. Define any necessary functions, the only one in this case being a Display_Message function for displaying splash...

Installing PyOpen GL

PyOpenGL needs a handful of dependencies in order to access all of its functionality. Luckily, most of these will already be installed if you've been playing with the code in this chapter. PyOpenGL needs Python 2.2 or higher, Tcl Tk, OpenGL, GLU which should come pre-installed on most modern machines and with most modern graphics card , the OpenGL Utility Toolkit or GLUT for short , and Numeric Python. The OpenGL Context may also require a few dependencies, depending on the platform. Those...

PyPlace

PyPlace, by Peter Goode and based on work by Pete Shinners , is a tool for generating isometric maps Place rendering in Python. The power behind PyPlace is a render.py module. This render model takes in a map object, which is basically a three-dimensional array, and uses the map to render an isometric view map with a number of square tiles which are provided in a .png format . Unfortunately, the project has been in alpha for quite a while, and it appears as though development on the project has...