import xml.etree.ElementTree as tree
tree=tree.parse("depth.svg")#basic level modeling done in inkscape.
pygameTemplate="template.py"#basic pygame file that will be edited by this script.
savefile="test.py"#final pygame playable file
root=tree.getroot()#required for xml parsing
roomheight=640 #int(root.attrib["height"])
roomwidht=480 #int(root.attrib["width"])
#makes the bottom most object be a refernce point for where true zero is, becaus Inkscape likes to shift where 0,0 is.
y1=round(float(root[3][0].attrib["y"]),6)
offby=y1-roomheight
#convert colors from svg to pygame
def HTMLColorToRGB(colorstring):
""" convert #RRGGBB to an (R, G, B) tuple """
colorstring = colorstring.strip()
if colorstring[0] == '#': colorstring = colorstring[1:]
if len(colorstring) != 6:
raise ValueError, "input #%s is not in #RRGGBB format" % colorstring
r, g, b = colorstring[:2], colorstring[2:4], colorstring[4:]
r, g, b = [int(n, 16) for n in (r, g, b)]
return (r, g, b)
# make a bunch of lines that can appear in the terminal when converting.
line="-"*30+"\n"
print line
print str("COUNT OBJECTS IN FILE:"+str(len(root[3]))).center(30)
print line
print str("COUNT OBJECTS IN FILE:"+str(len(root[3]))).center(30)
#Open a basic pygame file to edit.
p=open(pygameTemplate)
template=p.read()
p.close()
p=open("test.py","w")
boxes=str()
images=str()
job=range(len(root[3]))#make a list ranging from zero to the number of objects
for i in job:
x=round(float(root[3][i].attrib["x"]),6)
y=round(float(root[3][i].attrib["y"])-offby-roomheight,6)
w=round(float(root[3][i].attrib["width"]),6)
h=round(float(root[3][i].attrib["height"]),6)
objID=str(root[3][i].attrib["id"])
if "style" in root[3][i].attrib:
color=HTMLColorToRGB(root[3][i].attrib["style"].split(":")[1].split(";")[0])
if "image" in str(root[3][i]):
href=root[3][i].attrib["{http://www.w3.org/1999/xlink}href"][7:]
newimage='{name}=pygame.image.load("{location}")\n'
images+=newimage.format(name=objID,location=href)
if "image" in str(root[3][i]):
newbox="screen.blit({name},{position})\n\t"
boxes+=newbox.format( name=objID, position=str([x,y]) )
if "rect" in str(root[3][i]):
newbox="pygame.draw.rect(screen, {color},{boxinfo})\n\t"
boxes+=newbox.format( color=color, boxinfo=str([x,y,w,h]))
i+=1
final=template.format( loadboxes=boxes, loadimages=images )
p.write(final)
#print final