scratch2或scratch3的作品能通过Python编程自动生成吗?答案是肯定的,因为它的作品文件是一个压缩包,你把它解压后,分析它解压后的文件就能得出结论。对于一些简单的作品,如只是切换造型的,那可以通过Python编程读取gif文件,拆帧等操作,形成json文件,最后用zip打包,再改名或者连名都不要改,scratch2或scratch3就能自动加载。以下是一个函数,它能形成.sprite2角色文件!展示的是核心代码,基本原理都清楚了,其它的就要靠你自己了!
def make_scratch2_sprite(path,size):
"""生成scrach2.0角色,它的脚本只是不断地换造型"""
sprite = {} # 代表一个角色,这个角色有名称,声音列表,造型列表
sprite['objName'] = "sprite1"
sprite['scripts'] = [[131, 202, [["whenGreenFlag"], ["gotoX:y:", 0, 0],["doForever", [["wait:elapsed:from:", 0.2], ["nextCostume"]]]]]]
costumes_list = [] # 造型列表
md5_file_list = [] # md5值 图形文件列表
# 形成每个png文件的由md5值文件名
for filename in os.listdir(path):
md5 = GetFileMd5(path + os.sep + filename)
md5_file_list.append(md5 + ".png")
amounts = len(md5_file_list)
# 下面的代码是形成角色的造型列表
for index in range(1,amounts+1):
costume = {} # 一个造型
costume['costumeName'] = "shape" + str(index) # 造型名称
costume['baseLayerID'] = index-1 # 造型编号
costume['baseLayerMD5'] = md5_file_list[index-1]# MD5值文件名
costume['bitmapResolution'] = 2 # 位图 2
costume['rotationCenterX'] = size[0]//2 # x旋转中心
costume['rotationCenterY'] = size[1]//2 # y旋转中心
costumes_list.append(costume) # 添加一个造型到列表
sprite['costumes'] = costumes_list
sprite['currentCostumeIndex'] = 0
sprite['scratchX'] = 0
sprite['scratchY'] = 0
sprite['scale'] = 2
sprite['direction'] = 90
sprite['rotationStyle'] = "normal"
sprite['isDraggable'] = False
sprite['indexInLibrary'] = 100000
sprite['visible'] = True
sprite['spriteInfo'] = {"url":"www.scratch8.net"}
# 把sprite字典转换成json格式,写入文件
json_string = json.dumps(sprite)
f = open(path + os.sep + "sprite.json",mode='w')
f.write(json_string)
f.close()
os.chdir(path)
# 下面开始压缩图片和json档
with zipfile.ZipFile( 'sprite.sprite2', mode='w') as zipf:
for filename in os.listdir():
ext = os.path.splitext(filename)[-1]
if ext != ".sprite2":
zipf.write(filename)
zipf.close()
