December 12, 2010

ISSUE 4: What goes up…

Issue 4 already? Time flies! In this one we’re going to do a bit of housekeeping. As a project grows you often need to refactor (rewrite) parts of your code to keep the code scalable and readable. Our approach is what you might consider ‘rapid application development’ (RAD). An alternative approach would have been to sit down and work out the whole game in advance – before writing any code – but the MGF aim is “results, fast” so the more traditional ‘waterfall’ approach is out the window! We want fun while we learn. You’ll also be adding collisions to your game, explosions, gravity, water effects and a bit of camera trickery. As promised in Issue 3 we will also explain and improve the fog, lighting and sky.

1. Imports and Modules

Unlike last time, where we gave you the whole code in advance, we are opting this time to make changes to the code one at a time. Don’t worry – we will give the full code listing at the end of the issue! To begin with, update the start of your code, your ‘imports’ to look like this instead:

from direct.showbase.ShowBase import ShowBase
from direct.task import Task
from direct.interval.LerpInterval import LerpTexOffsetInterval, LerpPosInterval
from pandac.PandaModules import CompassEffect, CollisionTraverser, CollisionNode
from pandac.PandaModules import CollisionSphere, CollisionHandlerQueue, Material
from pandac.PandaModules import VBase4, VBase3, TransparencyAttrib
from panda3d.core import AmbientLight, DirectionalLight, Vec4, Vec3, Fog
from panda3d.core import BitMask32, Texture, TextNode, TextureStage
from panda3d.core import NodePath, PandaNode
from direct.gui.OnscreenText import OnscreenText
import sys

Quite a few additions, but all will be used by the end of the issue! So what exactly are these imports doing? In Python, there a number of ways to import what you need. So let’s start with the simplest. Open up a text editor and enter the following code:

class MGFMaths():
    def __init__(self):
        # nothing to do

    def square(self,number):
        return number*number;

    def cube(self,number):
        return number*number*number

Save the file in a directory somewhere (not the same one as your game, as this is illustrative only). Save it as ‘’. The file name is important! Now, in the same directory, create a ‘’ file containing the following:

import mgfutil

myMath = mgfutil.MGFMaths()
print("Square of 10 is: "+str(myMath.square(10)))
print("Cube of 10 is: "+str(myMath.cube(10)))

Save it. Now run it:


It should run and complete without any errors or warnings. Hopefully this example helps clarify. The “import mgfutil” caused the Python interpreter* to look for and load it. It’s that simple. In our game, you see examples using the dot notation (e.g. import direct.showbase.ShowBase). The dots are used to give directory paths. If you had saved in a sub-directory called “libs” you would have to “import libs.mgfutil”.

The code you saved in is considered in Python to be a ‘module’. A module is simply a collection of Python definitions and statements saved in a ‘.py’ file.

 * Interpreters and Compilers: The Python Interpreter is a computer program, it is the python command you execute from the command line. Its job is to execute the instructions it is given (your code!). Try running Python without specifying a .py file – you will get an interactive prompt where you can enter (and execute) Python code one line at a time! The alternative to an interpreted language such as Python is a compiled language. With compiled languages your code is translated to machine code the computer can directly understand (e.g., an EXE file on Microsoft Windows). This is done via a compiler.

Which is best?

It depends. Compiled languages tend to be faster but platform specific. Interpreted languages tend to be cross platform. Take the Panda3D engine for instance. It is written in a compiled language for speed (C++ in this instance). That’s why, in Issue 1, you had to download the Panda3D version for your operating system. Writing applications using Panda3D is done using Python as we know (though it can also be done in C++). Your Python code will work just fine on Windows, Linux, Mac and more.

There is a third option that is essentially ‘somewhere inbetween’. Java is an example of such a language. The code is compiled to a platform independent ‘bytecode’ instead of machine code. This is then executed via the Java Virtual Machine (JVM). The JVM is the platform specific portion that translates the bytecode to machine code.

But wait – we have all manner of includes in our game code, but not that much in our game directory, so what’s going on? Python uses a path – a set of directories to search in order to find anything you might import. If you enter the code below in a new file, save it as, and execute it, it will print your path out:

import sys
print sys.path

The Panda3D installation you did in Issue 1 will have made sure the engine libraries (modules!) are in the Python path. For example, on our install under Linux, the file ShowBase file is here:


Ok, a more complex example. Notice in your test code that to create an MGFMaths object you had to write:

myMath = mgfutil.MGFMaths()

In Python, and many other languages, a concept exists called the ‘namespace’. Think of it as dividing up code into named blocks! To access MGFMaths we have to grab it from the mgfutil namespace. The code that is in mgfutil is NOT by default accessible in your main program. It is in a different namespace. The concept is important – particularly in large applications using many libraries. What would happen if there was no namespace and you imported two modules – both of which provided an MGFMaths class? Unlikely given what we named our class, but that’s because we like to think about ‘good naming’ when we code. 🙂

This is fine. But suppose now that MGFMaths provided lots of different functionality – 10s of classes. Some we need, some we don’t. Our code would be littered all over the place with “mgfutil.”. Every time we use anything from the mgfutil module we have to prefix the code.

Now update your file to look like this:

from mgfutil import MGFMaths

myMath = MGFMaths()
print("Square of 10 is: "+str(myMath.square(10)))
print("Cube of 10 is: "+str(myMath.cube(10)))

Notice this time the “from” syntax. This is saying “from the mgfutil module import the MGFMaths class into our namespace”. Hence, later in the code, you note we did not have to prefix creating the object (myMath = MGFMaths).

….and that’s what you are seeing in many of our game import statements. Notice later in your game code that the AmbientLight object is simply created (in your createEnvironment method) – no prefixes – because we used a from/import at the start of our code.

Don’t worry too much about this next one for now, but you can also assign an import to a variable:

myMod = __import__('mgfutil.MGFMaths')

There is one more import approach which we’ll cover for completeness but strongly discourage you from using it!

from direct.showbase.ShowBase import *

The asterix means “everything”. In our game we only “import ShowBase” – it’s the only thing we want from the module. Importing “*” would import every all other classes/functions/data the module provided into our current namespace. A bad idea. Remember this: good code comes when we divide and conquer.