Introduction to Computer Science
Union College
Spring 2009

Reading a map file

The goal of this project is to read in a file that specifies the position and dimensions of rectangles and to draw these rectangles onto the screen.

Download the map file.

Step 1: function to read and process file

Define a function read_map_file. This function should take a string parameter, which is the name of the file to be read. It should return a list of 4-tuples with each 4-tuple consisting of 4 numbers specifying the coordinates and width and height of a rectangle.

So this function needs to: open the file, read the file line by line, extract the numbers from each line, assemble them into a tuple and add the tuple to a list, close the file once everything is read, and return the list.

To extract the numbers from each line, you need some string methods. Here is a list of all built-in string methods.

Since this function does not depend on any pygame specifics, you can develop and test it in a separate file, and only then, once it works, add it to your pygame program. That makes debugging much easier.

Step 2: call the function

Download, the following program as a starting point: rects_v0.py.

Use the function you write in the previous step to read in the map file and create the list of tuples representing rectangles once before the game loop starts. Print out the list that is being created to check that your function is working right.

Step 3: draw the rectangles

Add code to your game loop that draws each rectangle in the list created by the function call in the previous step.

by Kristina Striegnitz