Saturday, October 11, 2014

Organizing Pygame Programs Into Separate Files - Getting Started With Basics

Everyone starts off with one long block of code in a file. At some point, we break the program into separate files. In python, the separate file is called a module. Within each module, you can put functions and classes. As soon as you start to break up the program into separate files, everyone wonders how to get the variables from the main while loop in pygame to the module that is drawing something to the screen.  There are many ways to do this.  The easiest is to pass the main screen to your module as a global variable.

In this example, I call my main program and I call my module

craig@ubuntu-desktop:~/Development/dad/screens$  draw.pyc 
Ignore the file, draw.pyc.  It is created automatically when you run the program.

From, you can access using import draw

My draw module just puts two graphics to the screen, one with a function and with with a class.

To access the module from the program, you can either call the function directly with or instantiate the class.
Here's the full code listing:

Image of program showing how calls up the draw function from

No comments:

Post a Comment