Skip to content

Commit 73e7439

Browse files
committed
up
1 parent 63ff220 commit 73e7439

File tree

10 files changed

+167
-121
lines changed

10 files changed

+167
-121
lines changed

README.md

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -46,19 +46,12 @@ python ./src/stp.py -c ./../../tests/allblocks.sb3 --run -sl --tree -st
4646
## merge.py
4747
### 描述
4848
- merge.py是一个将两个`.sb3`文件合并为一个文件的脚本。
49-
# 第三方库&软件
50-
库:
51-
- loguru==0.7.2
52-
- cairosvg==2.7.1
53-
- pillow==9.5.0
54-
- pygame-ce==2.5.2
55-
- numpy==1.26.2
56-
- colorama==0.4.6
57-
58-
软件:
59-
- GTK+ 3.24.31
60-
61-
若您还没有安装这些第三方库或已经遇到了`ImportError`,请使用`pip install -r requirements.txt`,以及解压并安装`dependencies`分支下的软件(仅支持Windows x64)。
49+
# 安装依赖
50+
- 在根目录下执行:
51+
```bash
52+
pip install -r requirements.txt
53+
```
54+
- 解压并安装`dependencies`分支下的软件(仅支持Windows x64)。
6255
## 报错解决
6356
- `ImportError`:详见**第三方库&软件**
6457

requirements.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@ cairosvg==2.7.1
33
pillow==9.5.0
44
pygame-ce==2.5.2
55
numpy==1.26.2
6-
colorama==0.4.6
6+
colorama==0.4.6
7+
js2py==0.74

src/__STP/config.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,22 @@
1-
import sys,pathlib
1+
import os,sys,pathlib
2+
from ast import literal_eval as safe_eval
3+
import json
4+
import time
5+
from textwrap import dedent
6+
from typing import Any,Optional,Union,Tuple
7+
from string import digits
8+
29
def repath(path:str):
310
return str(pathlib.Path(path).resolve(strict=True))
411
def init_path():
512
sys.path.append(repath("../.."))
13+
614
from numpy import array,where
715
from loguru import logger as log
16+
#from js2py import translate_js
17+
#import jiphy as jp
818
log.remove()
919

10-
import json
11-
import os,sys,time
12-
from textwrap import dedent
13-
from typing import Any,Optional,Union,Tuple
14-
from string import digits
15-
1620
THISPATH=os.getcwd()
1721
LOCALDATE=time.strftime('%Y-%m-%d_%H:%M',time.localtime(time.time()))
1822
LOGFORMAT="<level>[{time:YYYY-MM-DD HH:mm:ss}] [{level}]: {message}</level>"

src/__STP/core.py

Lines changed: 7 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from .config import USERSET,json,SPRITE_INIT_CODE,GAME_INIT_CODE,HEAD,Any,Union,Tuple,digits,repath,init_path
22
init_path()
33
from .mypath import log,UnPackingScratch3File,PathTool
4-
from .spectype import FuncParser,ID,BlockBuffer,NestParser,VarListParser
4+
from .spectype import FuncParser,ID,BlockBuffer,InputParser,VarListParser
55

66
class CodeParser:
77
def __init__(self,last:UnPackingScratch3File):
@@ -15,18 +15,7 @@ def __init__(self,last:UnPackingScratch3File):
1515
self.t=PathTool(self.cdir)
1616
with open(self.t.join((self.cdir,"project.json")),'r',encoding='utf-8') as f: #导入project.json
1717
self.pj=json.load(f)
18-
self.semver=self.pj['meta']['semver']
19-
self.vmver=self.pj['meta']['vm']
20-
self.agent=self.pj['meta']['agent']
21-
self.platform_name=self.pj['meta']['platform']['name']
22-
self.platform_url=self.pj['meta']['platform']['url']
23-
log.debug("="*40)
24-
log.debug(f"Project version: {self.semver}")
25-
log.debug(f"VM version: {self.vmver}")
26-
log.debug(f"Agent: {self.agent if self.agent else 'unknown'}")
27-
log.debug(f'Platform name: {self.platform_name}')
28-
log.debug(f'Platform url: {self.platform_url}')
29-
log.debug("="*40)
18+
self.baseinfo={"semver":self.pj['meta']['semver'],"vm":self.pj['meta']['vm'],"agent":self.pj['meta']['agent'],"platform_name":self.pj['meta']['platform']['name'],"platform_url":self.pj['meta']['platform']['url']}
3019
self.last=last
3120
self.mod={"internal":{"typing":["",["Any"]],"math":["",[]],"random":["",[]],"sys":["",[]],"threading":["",["Thread","Timer"]]},"third-party":{"pygame":["pg",[]]}} #根据情况导入所需要的库
3221
self.var={"public":{},"private":{}} #存储变量
@@ -134,7 +123,7 @@ def fstr(self,string:str|dict="",mode=0,args=()):
134123
mode=4: 游戏基础信息,string为代码,args不填
135124
mode=5: 列表、变量管理,string为代码,args不填
136125
mode=6: 嵌套类型管理,string为代码,args为每个的嵌套深度
137-
mode=7: 两者运算类,args为(inputs开头参数名,运算符)
126+
mode=7: 含参类,args为(inputs开头参数名,运算符)
138127
'''
139128
args=list(str(i) for i in args)
140129
match mode:
@@ -257,10 +246,9 @@ def write_result(self):
257246
self.code.append(f" def {funcname}(self):")
258247
if funcinfo[1]: #有代码
259248
for line,depth in funcinfo[1].items():
260-
if line.startswith('id='):
261-
code=self.buffer.buffer.get(line[3:],[])
262-
if code:
263-
self.code.append(' '*(depth+2)+''.join(code))
249+
if line.startswith('id='): #输入类型占位标识
250+
code=self.buffer.get(line[3:])
251+
self.code.append(' '*(depth+2)+code)
264252
self.code.append(' '*(depth+2)+line)
265253
self.code.append("")
266254
else: #无代码
@@ -288,6 +276,7 @@ def write_result(self):
288276

289277
def code_tree(self):
290278
return {
279+
"project_info": self.baseinfo,
291280
"import_modules": self.mod,
292281
"requirements": self.requirements,
293282
"variables": self.var,

src/__STP/frame/spriteframe.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,17 @@
22
import sys,math,random
33
from threading import Timer,Thread
44

5+
class JSObject:
6+
def __init__(self,obj):
7+
self.obj=obj
8+
def __eq__(self,other):
9+
return str(self.obj)==str(other.obj)
10+
def __ne__(self,other):
11+
return str(self.obj)!=str(other.obj)
12+
def __str__(self):
13+
return str(self.obj)
14+
def __repr__(self):
15+
return str(self.obj)
516
class Sprite(pg.sprite.Sprite,Thread): #角色框架
617
def __init__(self, image_file:tuple[str], initxy:tuple[int,int], direction:int):
718
super().__init__()

src/__STP/spectype.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from .config import Tuple,Union,init_path
1+
from .config import Tuple,Union,init_path,safe_eval
22
init_path()
33
from src.util import is_spcial
44

@@ -12,8 +12,8 @@ def __init__(self):
1212
self.buffer={}
1313
def add(self,id:str,value:tuple):
1414
self.buffer[id]=value
15-
def get(self,id:str):
16-
return self.buffer.get(id)
15+
def get(self,id:str,default=[]):
16+
return ''.join(self.buffer.get(id,default))
1717
def update(self):
1818
b1=self.buffer.copy()
1919
for id,values in b1.items():
@@ -50,12 +50,14 @@ def bigupdate(self,_id="",values=(),recursive=False):
5050
if recursive:
5151
return a
5252

53-
class NestParser:
54-
def __init__(self,blocks:dict,block:dict,baseblock:dict):
53+
class InputParser:
54+
def __init__(self,blocks:dict,buffer:BlockBuffer):
5555
"""
56-
解析嵌套型积木块,生成python代码。
56+
解析含参型积木块,生成python代码。
5757
"""
5858
self.blocks=blocks
59+
self.buffer=buffer
60+
self.code=[]
5961

6062
class VarListParser:
6163
def __init__(self,blocks:dict):
@@ -87,7 +89,7 @@ def __init__(self,blocks:dict,baseblock:dict):
8789
self.funcname='_'+'_'.join(self.name)
8890
def isidentifier(self,s:str):
8991
"""
90-
判断字符串是否为合法的标识符
92+
判断参数字符串是否为合法的标识符
9193
"""
9294
r=True
9395
for i in '!@#$%^&*()/\\+-=[]{}|;:,.<>?':
@@ -100,7 +102,7 @@ def create(self,funccode:dict):
100102
self.funccode=funccode
101103
if self.funcname not in self.funccode: #创建函数
102104
self.funccode[self.funcname]=[{},{}]
103-
for argname,argdefault,argtype in zip(eval(self.funcmuta['argumentnames']),eval(self.funcmuta['argumentdefaults']),self.argtypes):
105+
for argname,argdefault,argtype in zip(safe_eval(self.funcmuta['argumentnames']),safe_eval(self.funcmuta['argumentdefaults']),self.argtypes):
104106
self.funccode[self.funcname][0][argname.replace(' ','_')]=[argdefault,self.type.get(argtype,'Any')] #type: ignore
105107

106108
def addcode(self,free=False,args:Union[str,Tuple[str,...]]="",opcode:str="",depth:int=0):

src/stp.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ def main(fp:str='./tests/work1.sb3',args:ap.Namespace=ap.Namespace()):
1919
parser=CodeParser(info)
2020
parser.write_result()
2121
log.success(f"Converted successfully (in {repath(parser.outpyfile)}) .")
22-
log.debug(f"Time used: {time.time()-start}s") #仅为积木转换时间,不包括解压缩及资源格式转换时间,与积木数量有关
22+
log.success(f"Time used: {time.time()-start}s") #仅为积木转换时间,不包括解压缩及资源格式转换时间,与积木数量有关
2323
if args.tree:
2424
log.debug('Showing the code tree...')
2525
for i,j in parser.code_tree().items():

tests/blocktest.sb3

-10 Bytes
Binary file not shown.

tests/blocktest/output/blocktest.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,7 @@ def __init__(self):
5151
class spr_角色1(Sprite):
5252
def __init__(self):
5353
super().__init__()
54-
id=a
5554

56-
def _1(self):
57-
...
5855

5956

6057
class Game:

0 commit comments

Comments
 (0)