How I do things (Part 2)

I wanted to draw the information for the maps from an external file – one that would be much easier to create and modify that code. So rather than have huge streams of code saying thisimage.draw(here) and thatimage.draw(there) I could just have a text file that said (x, y, image) and a few lines of code would read and draw everything. So, first we have a Reader Class:

class ReadMapFile:

def __init__(self, file):
self.file = file
self.map = Map()

def CreateMap(self):
f = open(self.file)
self.starts = []
self.fins = []
lines = f.readlines()
for i in range(len(lines)):
if lines[i] == “mapstart\n”:
self.starts.append(i)
elif lines[i] == “mapend\n”:
self.fins.append(i)
for j in range(len(self.starts)):
start = self.starts[j]
end = self.fins[j]
self.mapobjectdata = []
for k in range((start + 1), end):
self.mapobjectdata.append(lines[k])
self.newmapobject = MapObject()
self.newmapobject.setData(self.mapobjectdata)
self.map.grids.append(self.newmapobject)
return self.map

Everything happens in the CreateMap function. Here, the code looks through the input file for start and end statements, recording their location. Then it retrieves everything between these statements, fills it into a list and sends this to the Map Class for the function setData (eg x, y, filename) to actually create a Map Object with; these are all then filled into a Map, which is essentially just list of Map Objects, and returned. The result is that this text file:

blah
blahblag
mapstart
50
100
grass1.png
mapend
mapstart
100
200
castle1.png
mapend
blah
mapstart
70
100
grass1.png
mapend
mapstart
300
300
castle1.png
mapend
mapstart
400
400
castle1.png
mapend

Produces this:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: