-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGrazeConvert.py
235 lines (235 loc) · 18.2 KB
/
GrazeConvert.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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
import json
import PIL
from PIL import Image
from pathlib import Path
try:
with open('scratchproject/project.json') as whatsinhere:
gamecode = json.load(whatsinhere)
def make_new_event():
global neweventbaby
neweventbaby = "<event eventtype=\""+str(eventtype)+"\" enumb=\""+str(enumb)+"\">\n <action>\n <libid>1</libid>\n <id>603</id>\n <kind>7</kind>\n <userelative>0</userelative>\n <isquestion>0</isquestion>\n <useapplyto>-1</useapplyto>\n <exetype>2</exetype>\n <functionname></functionname>\n <codestring></codestring>\n <whoName>self</whoName>\n <relative>0</relative>\n <isnot>0</isnot>\n <arguments>\n <argument>\n <kind>1</kind>\n <string>"
def add_to_script():
global writingin
if writingin == "whenGreenFlag":
global greenflag
if greenflag == "":
global eventtype
global enumb
eventtype = 7
enumb = 4
make_new_event()
greenflag = neweventbaby
if greenflag != "":
global codetoadd
greenflag += codetoadd
def convert_block():
global codetoadd
global i
global countamount
global codeparse
global writingin
codetoadd = ""
# Change X By
if currentblock == 'changeXposBy':
xchange = int(AllScripts[codeparse+1])
codetoadd = "x += "+str(xchange)+";"
codeparse += 1
i -= 1
add_to_script()
# Change Y By
if currentblock == 'changeYposBy':
ychange = int(AllScripts[codeparse+1])
codetoadd = "y += "+str(ychange)+";"
codeparse += 1
i -= 1
add_to_script()
# Wait ___ Secs
if currentblock == 'waitelapsedfrom':
waitfor = int(AllScripts[codeparse+1])
waitfor = int(30*waitfor)
waitfor = float(format(int(waitfor), '.1f'))
codetoadd = "count_"+str(countamount)+" = 0\nwhile (count_"+str(countamount)+" < "+str(waitfor)+"){\ncount_"+str(countamount)+" += 1\n}"
countamount += 1
codeparse += 1
i -= 1
add_to_script()
# When Green Flag
if currentblock == 'whenGreenFlag':
writingin = "whenGreenFlag"
codetoadd = " "
# Go To X: Y:
if currentblock == 'gotoXy':
daX = AllScripts[codeparse+1]
daX = int(daX)+480
daY = AllScripts[codeparse+2]
daY = int(daY)+352
codetoadd = "x = "+str(daX)+";\ny = "+str(daY)+";\n"
codeparse += 2
i -= 2
add_to_script()
if currentblock == 'stopScripts':
# Stop All
if AllScripts[codeparse+1] == "all":
codetoadd = "game_end();"
i -= 1
codeparse += 1
add_to_script()
if codetoadd == "":
if writingin != "":
writingin = ""
if ("objName" in gamecode):
spritemetadata = "";
soundmetadata = "";
# Import Stage Sounds
if ("sounds" in gamecode):
print("Importing Stage sounds...")
AllSounds = gamecode['sounds']
soundamount = len(AllSounds)
for i in range(soundamount):
thesound = AllSounds[i]
soundname = thesound['soundName']
soundeyedee = thesound['soundID']
soundmetadata += " <sound>sound\snd_"+str(soundname)+"</sound>\n";
with open('FinishedGame.gmx/sound/snd_'+str(soundname)+'.sound.gmx','x') as f:
f.write("<!--This Document is generated by GameMaker, if you edit it by hand then you do so at your own risk!-->\n<sound>\n <kind>3</kind>\n <extension>.wav</extension>\n <origname>sound\\audio\\snd_"+str(soundname)+"</origname>\n <effects>0</effects>\n <volume>\n <volume>1</volume>\n </volume>\n <pan>0</pan>\n <bitRates>\n <bitRate>192</bitRate>\n </bitRates>\n <sampleRates>\n <sampleRate>44100</sampleRate>\n </sampleRates>\n <types>\n <type>0</type>\n </types>\n <bitDepths>\n <bitDepth>16</bitDepth>\n </bitDepths>\n <preload>-1</preload>\n <data>snd_"+str(soundname)+".wav</data>\n <compressed>1</compressed>\n <streamed>0</streamed>\n <uncompressOnLoad>0</uncompressOnLoad>\n <audioGroup>0</audioGroup>\n</sound>")
Path("scratchproject/"+str(soundeyedee)+".wav").rename("FinishedGame.gmx/sound/audio/snd_"+str(soundname)+".wav")
# Import Stage Costumes
if ("costumes" in gamecode):
print("Importing Stage costumes...")
AllCostumes = gamecode['costumes']
costumeamount = len(AllCostumes)
subimage = 0
thecostume = AllCostumes[0]
rotX = thecostume['rotationCenterX']
rotY = thecostume['rotationCenterY']
costumeID = (thecostume['baseLayerID'])
imagez = PIL.Image.open("scratchproject/"+str(costumeID)+".png")
wid, hgt = imagez.size
imagez.close()
spritemetadata += " <sprite>sprites\\spr_stage</sprite>\n";
with open('FinishedGame.gmx/sprites/spr_stage.sprite.gmx','x') as f:
f.write("<!--This Document is generated by GameMaker, if you edit it by hand then you do so at your own risk!-->\n<sprite>\n <type>0</type>\n <xorig>"+str(rotX)+"</xorig>\n <yorigin>"+str(rotY)+"</yorigin>\n <colkind>1</colkind>\n <coltolerance>0</coltolerance>\n <sepmasks>0</sepmasks>\n <bboxmode>0</bboxmode>\n <bbox_left>0</bbox_left>\n <bbox_right>"+str(wid-1)+"</bbox_right>\n <bbox_top>0</bbox_top>\n <bbox_bottom>"+str(hgt-1)+"</bbox_bottom>\n <HTile>0</HTile>\n <VTile>0</VTile>\n <TextureGroups>\n <TextureGroup0>0</TextureGroup0>\n </TextureGroups>\n <For3D>0</For3D>\n <width>960</width>\n <height>720</height>\n <frames>\n")
for i in range(costumeamount):
thecostume = AllCostumes[i]
costumeID = thecostume['baseLayerID']
with open('FinishedGame.gmx/sprites/spr_stage.sprite.gmx','a') as f:
f.write(" <frame index=\""+str(subimage)+"\">images\\spr_stage_"+str(subimage)+".png</frame>\n")
Path("scratchproject/"+str(costumeID)+".png").rename("FinishedGame.gmx/sprites/images/spr_stage_"+str(subimage)+".png")
subimage += 1
with open('FinishedGame.gmx/sprites/spr_stage.sprite.gmx','a') as f:
f.write(" </frames>\n</sprite>")
# Set Global Stage Variables
if ("variables" in gamecode):
print("Setting Stage Variables...")
GlobalVariables = gamecode['variables']
varamount = len(GlobalVariables)
for i in range(varamount):
variable = GlobalVariables[i]
varname = "global.var_"+variable['name']
varvalue = variable['value']
varcode = varname+" = "+str(varvalue)+";\n"
with open('FinishedGame.gmx/scripts/establishVariables.gml','a') as f:
f.write(varcode)
# Other Sprite Time!
allobjmetadata = ""
if ("children" in gamecode):
AllObjects = gamecode['children']
ObjectAmount = len(AllObjects)
for i in range(ObjectAmount):
if 'target' not in AllObjects[i]:#this wont trip up by having a sprite or sound in Scratch be named "target" will it?
CurrentObject = AllObjects[i]
ObjectX = CurrentObject['scratchX']
ObjectY = CurrentObject['scratchY']
# Import Sounds
if ("sounds" in CurrentObject):
print("Importing '"+str(CurrentObject['objName'])+"' sounds...")
AllSounds = CurrentObject['sounds']
soundamount = len(AllSounds)
for i in range(soundamount):
thesound = AllSounds[i]
soundname = thesound['soundName']
soundeyedee = thesound['soundID']
dapath = Path('scratchproject/'+str(soundeyedee)+'.wav')
if not (dapath.exists()):
print (str(soundeyedee)+'.wav already exists, ignoring')
if (dapath.exists()):
soundmetadata += " <sound>sound\snd_"+str(soundname)+"</sound>\n";
with open('FinishedGame.gmx/sound/snd_'+str(soundname)+'.sound.gmx','a') as f:
f.write("<!--This Document is generated by GameMaker, if you edit it by hand then you do so at your own risk!-->\n<sound>\n <kind>3</kind>\n <extension>.wav</extension>\n <origname>sound\\audio\\snd_"+str(soundname)+"</origname>\n <effects>0</effects>\n <volume>\n <volume>1</volume>\n </volume>\n <pan>0</pan>\n <bitRates>\n <bitRate>192</bitRate>\n </bitRates>\n <sampleRates>\n <sampleRate>44100</sampleRate>\n </sampleRates>\n <types>\n <type>0</type>\n </types>\n <bitDepths>\n <bitDepth>16</bitDepth>\n </bitDepths>\n <preload>-1</preload>\n <data>snd_"+str(soundname)+".wav</data>\n <compressed>1</compressed>\n <streamed>0</streamed>\n <uncompressOnLoad>0</uncompressOnLoad>\n <audioGroup>0</audioGroup>\n</sound>")
Path("scratchproject/"+str(soundeyedee)+".wav").rename("FinishedGame.gmx/sound/audio/snd_"+str(soundname)+".wav")
# Import Costumes
if ("costumes" in CurrentObject):
print("Importing '"+str(CurrentObject['objName'])+"' costumes...")
AllCostumes = CurrentObject['costumes']
costumeamount = len(AllCostumes)
subimage = 0
spritemetadata += " <sprite>sprites\\spr_"+str(CurrentObject['objName'])+"</sprite>\n";
for i in range(costumeamount):
thecostume = AllCostumes[i]
rotX = thecostume['rotationCenterX']
rotY = thecostume['rotationCenterY']
costumeID = thecostume['baseLayerID']
dapath = Path('scratchproject/'+str(costumeID)+'.png')
if not (dapath.exists()):
print (str(costumeID)+'.png already exists, ignoring')
if (dapath.exists()):
img = PIL.Image.open("scratchproject/"+str(costumeID)+".png")
wid, hgt = img.size
img.close()
if (subimage == 0):
with open('FinishedGame.gmx/sprites/spr_'+str(CurrentObject['objName'])+'.sprite.gmx','a') as f:
f.write("<!--This Document is generated by GameMaker, if you edit it by hand then you do so at your own risk!-->\n<sprite>\n <type>0</type>\n <xorig>"+str(rotX)+"</xorig>\n <yorigin>"+str(rotY)+"</yorigin>\n <colkind>1</colkind>\n <coltolerance>0</coltolerance>\n <sepmasks>0</sepmasks>\n <bboxmode>0</bboxmode>\n <bbox_left>0</bbox_left>\n <bbox_right>"+str(wid-1)+"</bbox_right>\n <bbox_top>0</bbox_top>\n <bbox_bottom>"+str(hgt-1)+"</bbox_bottom>\n <HTile>0</HTile>\n <VTile>0</VTile>\n <TextureGroups>\n <TextureGroup0>0</TextureGroup0>\n </TextureGroups>\n <For3D>0</For3D>\n <width>"+str(wid)+"</width>\n <height>"+str(hgt)+"</height>\n <frames>\n")
with open('FinishedGame.gmx/sprites/spr_'+str(CurrentObject['objName'])+'.sprite.gmx','a') as f:
f.write(" <frame index=\""+str(subimage)+"\">images\\spr_"+str(CurrentObject['objName'])+"_"+str(subimage)+".png</frame>\n")
Path("scratchproject/"+str(costumeID)+".png").rename("FinishedGame.gmx/sprites/images/spr_"+str(CurrentObject['objName'])+"_"+str(subimage)+".png")
subimage += 1
with open('FinishedGame.gmx/sprites/spr_'+str(CurrentObject['objName'])+'.sprite.gmx','a') as f:
f.write(" </frames>\n</sprite>")
# Start to make Object XML
objectmetadata = "<!--This Document is generated by GameMaker, if you edit it by hand then you do so at your own risk!-->\n<object>\n <spriteName>spr_"+str(CurrentObject['objName'])+"</spriteName>\n <solid>0</solid>\n <visible>-1</visible>\n <depth>0</depth>\n <persistent>0</persistent>\n <parentName><undefined></parentName>\n <maskName><undefined></maskName>\n <events>\n "
# Object Code, Baby
global greenflag
greenflag = ""
if ("scripts" in CurrentObject):
print("Converting '"+str(CurrentObject['objName'])+"' code...")
AllScripts = json.dumps(CurrentObject['scripts'])
badchar = "[],:\""
for character in badchar:
AllScripts = AllScripts.replace(character,"")
AllScripts = AllScripts.split()
global codeparse
global codetoadd
global countamount
countamount = 1
codeparse = 0
global eventtype
global enumb
eventtype = 0
enumb = 0
global writingin
writingin = ""
ScriptAmount = len(AllScripts)
for i in range (ScriptAmount):
currentblock = AllScripts[codeparse]
convert_block()
codeparse += 1
if greenflag != "":
greenflag += "</string>\n </argument>\n </arguments>\n </action>\n </event>\n"
#Write Object Metadata & Write Object Into Room Metadata
objectmetadata += ""+str(greenflag)+" </events>\n <PhysicsObject>0</PhysicsObject>\n <PhysicsObjectSensor>0</PhysicsObjectSensor>\n <PhysicsObjectShape>0</PhysicsObjectShape>\n <PhysicsObjectDensity>0.5</PhysicsObjectDensity>\n <PhysicsObjectRestitution>0.100000001490116</PhysicsObjectRestitution>\n <PhysicsObjectGroup>0</PhysicsObjectGroup>\n <PhysicsObjectLinearDamping>0.100000001490116</PhysicsObjectLinearDamping>\n <PhysicsObjectAngularDamping>0.100000001490116</PhysicsObjectAngularDamping>\n <PhysicsObjectFriction>0.200000002980232</PhysicsObjectFriction>\n <PhysicsObjectAwake>-1</PhysicsObjectAwake>\n <PhysicsObjectKinematic>0</PhysicsObjectKinematic>\n <PhysicsShapePoints/>\n</object>"
allobjmetadata += " <object>objects\obj_"+str(CurrentObject['objName'])+"</object>\n"
with open('FinishedGame.gmx/objects/obj_'+str(CurrentObject['objName'])+'.object.gmx','a') as f:
f.write(str(objectmetadata))
with open('FinishedGame.gmx/rooms/rm_stage.room.gmx','a') as f:
f.write(' <instance objName=\"obj_'+str(CurrentObject['objName'])+'\" x=\"'+str(ObjectX+480)+'\" y=\"'+str(ObjectY+352)+'\" name=\"inst_'+str(CurrentObject['objName'])+'\" locked=\"0\" code=\"\" scaleX=\"1\" scaleY=\"1\" colour=\"4294967295\" rotation=\"0\"/>\n')
#Rewrite Main Game and Room Metadata
with open ('FinishedGame.gmx/FinishedGame.project.gmx','w') as f:
f.write("<!--This Document is generated by GameMaker, if you edit it by hand then you do so at your own risk!-->\n<assets>\n <Configs name=\"configs\">\n <Config>Configs\Default</Config>\n </Configs>\n <NewExtensions/>\n <sounds name=\"sound\">\n"+str(soundmetadata)+" </sounds>\n <sprites name=\"sprites\">\n"+str(spritemetadata)+" </sprites>\n <backgrounds name=\"background\"/>\n <paths name=\"paths\"/>\n <scripts name=\"scripts\">\n <script>scripts\establishVariables.gml</script>\n </scripts>\n <objects name=\"objects\">\n"+str(allobjmetadata)+" </objects>\n <rooms name=\"rooms\">\n <room>rooms\\rm_stage</room>\n </rooms>\n <help>\n <rtf>help.rtf</rtf>\n </help>\n <TutorialState>\n <IsTutorial>0</IsTutorial>\n <TutorialName></TutorialName>\n <TutorialPage>0</TutorialPage>\n </TutorialState>\n</assets>")
with open('FinishedGame.gmx/rooms/rm_stage.room.gmx','a') as f:
f.write(' </instances>\n <tiles/>\n <PhysicsWorld>0</PhysicsWorld>\n <PhysicsWorldTop>0</PhysicsWorldTop>\n <PhysicsWorldLeft>0</PhysicsWorldLeft>\n <PhysicsWorldRight>1024</PhysicsWorldRight>\n <PhysicsWorldBottom>768</PhysicsWorldBottom>\n <PhysicsWorldGravityX>0</PhysicsWorldGravityX>\n <PhysicsWorldGravityY>10</PhysicsWorldGravityY>\n <PhysicsWorldPixToMeters>0.100000001490116</PhysicsWorldPixToMeters>\n</room>')
print("*DING* Done!")
else:
print("ERROR: This Scratch project doesn't have a Stage from what we can tell. Is it a valid .sb2 file?")
except:
print("ERROR: Project .JSON could not be found.")
input("Press Enter to close.")