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 main.py 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 main.py and I call my module draw.py.

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

From main.py, you can access draw.py 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 draw.dot(SCREEN) or instantiate the class.
Here's the full code listing:



Image of program showing how main.py calls up the draw function from draw.py.


No comments:

Post a Comment