-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLevelConverter.py
170 lines (143 loc) · 4.67 KB
/
LevelConverter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import sys
from xml.dom.minidom import parse, parseString
def convert_bytes(bytes):
#http://www.5dollarwhitebox.org/drupal/node/84
bytes = float(bytes)
if bytes >= 1099511627776:
terabytes = bytes / 1099511627776
size = '%.2fT' % terabytes
elif bytes >= 1073741824:
gigabytes = bytes / 1073741824
size = '%.2fG' % gigabytes
elif bytes >= 1048576:
megabytes = bytes / 1048576
size = '%.2fM' % megabytes
elif bytes >= 1024:
kilobytes = bytes / 1024
size = '%.2fK' % kilobytes
else:
size = '%.2fb' % bytes
return size
def ConvertLevel(src,dst):
dom = parse(src)
m = dom.getElementsByTagName("layer")
numLayers = len(m)
levelData = None
width,height = None,None
print "Stage 1, sanity check."
if dom.getElementsByTagName("map")[0].getAttribute("orientation")!="orthogonal":
print "Error: Map must be orthogonal."
return False
for layer in m:#sanity check.
layer.__getitem__=layer.getAttribute
w = int(layer["width"])
h = int(layer["height"])
if layer.getElementsByTagName("data")[0].getAttribute("encoding")!="csv":
print "Error, encoding must be CSV"
return False
if width==None:
width = w
height = h
else:
if w!=width or h!=height:
print "Error converting, layers must all be the same dimension"
exit(1)
levelData = [width,height]
print "Stage 2, data extraction and compacting"
layers = [] #(name,[properties],data)
for layer in m:
layer.__getitem__=layer.getAttribute
name = layer["name"]
props = []
for prop in layer.getElementsByTagName("property"):
prop.__getitem__=prop.getAttribute
props.append((prop["name"],prop["value"]))
data = layer.getElementsByTagName("data")[0]
vals = map(int,data.childNodes[0].data.replace("\n","").split(","))
printPos = True
d = []
for r in xrange(h):
for c in xrange(w):
v = vals[r*w+c]
if v:
if printPos:
d.append((r,c))
printPos = False
d.append(v)
else:
printPos = True
print name,len(d)
layers.append((name,props,d))
print "Stage 3, stringification and compression"
data = "{}".format((levelData,layers))
l = len(data)
factor = 1
try:
import zlib
print "Zlib available. Compressing."
data = zlib.compress(data,9)
factor = l*1.0/len(data)
except:
print "Failed to use zlib, defaulting to plain text."
pass
print "Stage 4, Writing"
out = file(dst,"wb")
out.write(data)
print "Filesize:",convert_bytes(len(data))
print "Compression factor: %.2f"%factor
out.close()
print "Stage 5, Testing"
layers2 = None
f = file(dst,"rb")
data = f.read()
try:
import zlib
data = zlib.decompress(data)
except:
print "Failed to decompress with zlib"
pass
try:
levDat,layers2 = eval(data,{"__builtins__":None},{})#little bit of safety
if layers2==layers and levDat == levelData:
print "Passed."
return True
else:
print "Failed."
return False
except:
print "Failed decompression test."
pass
return False
if len(sys.argv) == 1:
print "Auto converting all .tmx files in data directory."
import os
for path, folders, files in os.walk("data"):
for f in files:
if not f.endswith(".tmx"):
continue
print "---%s---"%f
ConvertLevel(os.path.join(path,f),
os.path.join(path,f)[:-3]+"lvl")
else:
print "Usage:"
print "python %s <Tiled file> <output file>"%sys.argv[0]
print ""
print "Tiled must be set to store layers using CSV"
print " To do this goto Edit, Preference, select CSV"
exit(1)
x="""
level = "Level0"
f = file(Utils.LevelData(level))
vals = map(lambda x:x.strip().split(","),f.readlines())
rows = len(vals)
cols = len(vals[0])
ss = pygame.image.load(Utils.ImagePath("town01.png"))
surf = pygame.Surface((cols*32,rows*32))
for row in xrange(rows):
for col in xrange(cols):
v = vals[row][col]
c,r = int(v[0],16),int(v[1:],16)
tmp = ss.subsurface((c*32,r*32,32,32))
surf.blit(tmp,(col*32,row*32))
pygame.image.save(surf,"output.png")
"""