pyscreeps-arena 0.3.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,851 @@
1
+ import os.path
2
+
3
+ from pyscreeps_arena.core import *
4
+ from pyscreeps_arena.localization import *
5
+
6
+ import re
7
+ import shutil
8
+ import chardet
9
+ import subprocess
10
+ import pyperclip
11
+ from colorama import Fore
12
+
13
+ WAIT = Fore.YELLOW + ">>>" + Fore.RESET
14
+ GREEN = Fore.GREEN + "{}" + Fore.RESET
15
+ python_version_info = sys.version_info
16
+ python_version_info = f"{python_version_info.major}.{python_version_info.minor}.{python_version_info.micro}"
17
+
18
+
19
+ # def InsertPragmaBefore(content:str) -> str:
20
+ # """
21
+ # 在content的开头插入__pragma__('noalias', 'undefined')等内容 |
22
+ # Insert __pragma__('noalias', 'undefined') at the beginning of content
23
+ # :param content: str
24
+ # :return: str
25
+ # """
26
+ # return PYFILE_PRAGMA_INSERTS + "\n" + content
27
+ class Compiler_Const:
28
+ PROTO_DEFINES_DIRS = ["builtin", "library"]
29
+ FILE_STRONG_REPLACE = {
30
+ "std": {
31
+ "==": "===",
32
+ "!=": "!==",
33
+ }
34
+ }
35
+ PYFILE_IGNORE_CHECK_FNAMES = ['builtin/const.py', 'builtin/proto.py', 'builtin/utils.py']
36
+
37
+ PYFILE_PRAGMA_INSERTS = """
38
+ # __pragma__('noalias', 'undefined')
39
+ # __pragma__('noalias', 'Infinity')
40
+ # __pragma__('noalias', 'clear')
41
+ # __pragma__('noalias', 'get')
42
+ """
43
+
44
+ TOTAL_INSERT_AT_HEAD = """
45
+ import { createConstructionSite, findClosestByPath, findClosestByRange, findInRange, findPath, getCpuTime, getDirection, getHeapStatistics, getObjectById, getObjects, getObjectsByPrototype, getRange, getTerrainAt, getTicks,} from 'game/utils';
46
+ import { ConstructionSite, Creep, GameObject, OwnedStructure, Resource, Source, Structure, StructureContainer, StructureExtension, StructureRampart, StructureRoad, StructureSpawn, StructureWall, StructureTower} from 'game/prototypes';
47
+ import { ATTACK, ATTACK_POWER, BODYPART_COST, BODYPART_HITS, BOTTOM, BOTTOM_LEFT, BOTTOM_RIGHT, BUILD_POWER, CARRY, CARRY_CAPACITY, CONSTRUCTION_COST, CONSTRUCTION_COST_ROAD_SWAMP_RATIO, CONSTRUCTION_COST_ROAD_WALL_RATIO, CONTAINER_CAPACITY, CONTAINER_HITS, CREEP_SPAWN_TIME, DISMANTLE_COST, DISMANTLE_POWER, ERR_BUSY, ERR_FULL, ERR_INVALID_ARGS, ERR_INVALID_TARGET, ERR_NAME_EXISTS, ERR_NOT_ENOUGH_ENERGY, ERR_NOT_ENOUGH_EXTENSIONS, ERR_NOT_ENOUGH_RESOURCES, ERR_NOT_FOUND, ERR_NOT_IN_RANGE, ERR_NOT_OWNER, ERR_NO_BODYPART, ERR_NO_PATH, ERR_TIRED, EXTENSION_ENERGY_CAPACITY, EXTENSION_HITS, HARVEST_POWER, HEAL, HEAL_POWER, LEFT, MAX_CONSTRUCTION_SITES, MAX_CREEP_SIZE, MOVE, OBSTACLE_OBJECT_TYPES, OK, RAMPART_HITS, RAMPART_HITS_MAX, RANGED_ATTACK, RANGED_ATTACK_DISTANCE_RATE, RANGED_ATTACK_POWER, RANGED_HEAL_POWER, REPAIR_COST, REPAIR_POWER, RESOURCES_ALL, RESOURCE_DECAY, RESOURCE_ENERGY, RIGHT, ROAD_HITS, ROAD_WEAROUT, SOURCE_ENERGY_REGEN, SPAWN_ENERGY_CAPACITY, SPAWN_HITS, STRUCTURE_PROTOTYPES, TERRAIN_PLAIN, TERRAIN_SWAMP, TERRAIN_WALL, TOP, TOP_LEFT, TOP_RIGHT, TOUGH, TOWER_CAPACITY, TOWER_COOLDOWN, TOWER_ENERGY_COST, TOWER_FALLOFF, TOWER_FALLOFF_RANGE, TOWER_HITS, TOWER_OPTIMAL_RANGE, TOWER_POWER_ATTACK, TOWER_POWER_HEAL, TOWER_POWER_REPAIR, TOWER_RANGE, WALL_HITS, WALL_HITS_MAX, WORK} from 'game/constants';
48
+
49
+ import {arenaInfo} from "game";
50
+ import {Visual} from "game/visual"
51
+ import {searchPath} from "game/path-finder"
52
+ """
53
+
54
+ TOTAL_INSERT_BEFORE_MAIN = """
55
+ """
56
+
57
+ TOTAL_APPEND_ATEND = """
58
+ export var sch = Scheduler();
59
+
60
+ know.now = 0;
61
+ export var loop = function () {
62
+ know.now = get.ticks ();
63
+ if (know.now === 1) {
64
+ init (know);
65
+ }
66
+
67
+ know.update_(know);
68
+ step (know);
69
+ sch.handle();
70
+ std.show_usage ();
71
+ };
72
+ """
73
+
74
+ TOTAL_SIMPLE_REPLACE_WITH = {
75
+ }
76
+
77
+ PYFILE_WORD_WARNING_CHECK = {
78
+ r"\.\s*get\s*\(": LOC_PYFILE_WORD_WARNING_CHECK_GET,
79
+ r"import\s+math\s*": LOC_PYFILE_WORD_WARNING_CHECK_MATH,
80
+ r"\.\s*clear\s*\(": LOC_PYFILE_WORD_WARNING_CHECK_CLEAR,
81
+ r"\[\s*-\s*1\s*\]": LOC_PYFILE_WORD_WARNING_INDEX_MINUS_ONE,
82
+ }
83
+
84
+ PYFILE_EXIST_WARNING_CHECK = {
85
+ r"__pragma__\s*\(\s*['\"]noalias['\"]\s*,\s*['\"]undefined['\"]\s*\)": "Strongly suggest to add '__pragma__('noalias', 'undefined')'.",
86
+ r"__pragma__\s*\(\s*['\"]noalias['\"]\s*,\s*['\"]Infinity['\"]\s*\)": "Strongly suggest to add '__pragma__('noalias', 'Infinity')'.",
87
+ r"__pragma__\s*\(\s*['\"]noalias['\"]\s*,\s*['\"]clear['\"]\s*\)": "Strongly suggest to add '__pragma__('noalias', 'clear')'.",
88
+ r"__pragma__\s*\(\s*['\"]noalias['\"]\s*,\s*['\"]get['\"]\s*\)": "Strongly suggest to add '__pragma__('noalias', 'get')'.",
89
+ }
90
+
91
+ JS_VM = "org.transcrypt.__runtime__.js"
92
+
93
+ BUILTIN_TRANS = ["engine.js"]
94
+ OTHER_IGNORE_WITH = "./builtin"
95
+
96
+ JS_IMPORT_PAT = re.compile(r'from\s+[\'\"]([^\']+)[\'\"]')
97
+ JS_EXPORT_PAT = re.compile(r'export\s+{([^}]+)}')
98
+ PY_IMPORT_PAT = re.compile(r'from\s+(.+)(?=\s+import)\s+import\s+\*')
99
+ INSERT_PAT = re.compile(r'#\s*insert\s+([^\n]*)') # 因为被判定的string为单line,所以不需要考虑多行的情况
100
+
101
+ TRANSCRYPT_ERROR_REPLACE = {
102
+ # 由于transcrypt的问题,导致编译后的js代码中存在一些错误,需要进行替换
103
+ r"new\s+set\s*\(": r"set(",
104
+ }
105
+
106
+ ARENA_IMPORTS_GETTER = {
107
+ const.ARENA_GREEN: lambda: f"""
108
+ """,
109
+ const.ARENA_BLUE: lambda: f"""
110
+ import {{ Flag }} from 'arena/season_{config.season}/capture_the_flag/basic';
111
+ """,
112
+ const.ARENA_RED: lambda: f"""
113
+ import {{ RESOURCE_SCORE, ScoreCollector, AreaEffect, EFFECT_DAMAGE, EFFECT_FREEZE }} from 'arena/season_{config.season}/collect_and_control/basic';
114
+
115
+ import ("arena/season_{config.season}/collect_and_control/basic")
116
+ .then((module) => {{ const RESOURCE_SCORE_X = module.RESOURCE_SCORE_X; const RESOURCE_SCORE_Y = module.RESOURCE_SCORE_Y; const RESOURCE_SCORE_Z = module.RESOURCE_SCORE_Z; }})
117
+ .catch((error) => {{ }});
118
+ """,
119
+ const.ARENA_GRAY: lambda: f"""
120
+ // import {{ Flag }} from 'game/prototypes'
121
+ import("game/prototypes")
122
+ .then((module) => {{ const Flag = module.Flag; }})
123
+ .catch((error) => {{ }});
124
+ """,
125
+ }
126
+ ARENA_IMPORTS_NOT_BLUE = ""
127
+ ARENA_IMPORTS_NOT_BLUE1 = """
128
+ import { StructureTower } from 'game/prototypes'
129
+ """
130
+
131
+
132
+ class Compiler_Utils(Compiler_Const):
133
+ last_output = False # 一个小标志位,我只想输出一次此类告警信息
134
+
135
+ @staticmethod
136
+ def auto_read(fpath: str) -> str:
137
+ """
138
+ 读取文件内容,自动应用编码
139
+ :param fpath: str 文件路径
140
+ """
141
+ if not os.path.exists(fpath):
142
+ if not Compiler_Utils.last_output:
143
+ Compiler_Utils.last_output = True
144
+ print()
145
+ core.warn('Compiler_Utils.auto_read', core.lformat(LOC_FILE_NOT_EXISTS, [fpath]), end='', head='\n', ln=config.language)
146
+ return ""
147
+
148
+ try:
149
+ with open(fpath, 'r', encoding='utf-8') as f:
150
+ return f.read()
151
+ except UnicodeDecodeError:
152
+ try:
153
+ with open(fpath, 'r', encoding='gbk') as f:
154
+ return f.read()
155
+ except UnicodeDecodeError:
156
+ # 如果使用检测到的编码读取失败,尝试使用chardet检测编码
157
+ with open(fpath, 'rb') as f: # 以二进制模式打开文件
158
+ raw_data = f.read() # 读取文件的原始数据
159
+ result = chardet.detect(raw_data) # 使用chardet检测编码
160
+ encoding = result['encoding'] # 获取检测到的编码
161
+ with open(fpath, 'r', encoding=encoding) as f: # 使用检测到的编码打开文件
162
+ return f.read()
163
+
164
+ def copy_to(self) -> list:
165
+ """
166
+ 复制src到build目录 | copy all files in src to build
167
+ * 注意到src下的文件应当全部为py文件 | all files in src should be py files
168
+ """
169
+ # copy to build dir
170
+ # print(Fore.YELLOW + '>>> ' + Fore.RESET + ' copying to build dir: %s ...' % self.build_dir, end='')
171
+ # LOC_COPYING_TO_BUILD_DIR
172
+
173
+ core.lprint(WAIT, core.lformat(LOC_COPYING_TO_BUILD_DIR, [self.build_dir]), end="", ln=config.language)
174
+
175
+ if os.path.exists(self.build_dir):
176
+ shutil.rmtree(self.build_dir)
177
+ shutil.copytree(self.src_dir, self.build_dir)
178
+ shutil.copytree(self.src_dir, os.path.join(self.build_dir, "src"))
179
+ srcs = [] # src下所有python文件的路径 | paths of all python files under src
180
+ for root, dirs, files in os.walk(self.build_dir):
181
+ for file in files:
182
+ if file.endswith('.py'):
183
+ srcs.append(os.path.join(root, file))
184
+ # add libs
185
+ for lib in self.PROTO_DEFINES_DIRS:
186
+ shutil.copytree(lib, os.path.join(self.build_dir, lib))
187
+
188
+ # overwrite last to [Done]
189
+ # print(Fore.GREEN + '\r[1/6][Done]' + Fore.RESET + ' copying to build dir: %s' % self.build_dir)
190
+
191
+ core.lprint(GREEN.format('[1/6]'), LOC_DONE, " ", core.lformat(LOC_COPYING_TO_BUILD_DIR_FINISH, [self.build_dir]), sep="", head="\r", ln=config.language)
192
+ return srcs
193
+
194
+ @staticmethod
195
+ def potential_check(fpath: str, fname: str) -> bool:
196
+ """
197
+ 检查某个py文件内是否有潜在问题 | check if there are potential problems in a py file
198
+
199
+ 如果有的话,输出[Warn][{file_name}/{line_io}]{detail} | if there are, output [Warn][{file_name}/{line_io}]{detail}
200
+
201
+ Returns:
202
+ bool: 是否有警告
203
+ """
204
+ # 文件路径检查
205
+ # if fpath.endswith('__init__.py') and fpath.find("builtin") == -1:
206
+ # core.error("potential_check", LOC_NOT_SUPPORT_PYFILE_INIT, ln=config.language, ecode=-1, head='\n')
207
+ if fname in Compiler.PYFILE_IGNORE_CHECK_FNAMES:
208
+ return False
209
+
210
+ # # 文件内容检查
211
+ content = Compiler.auto_read(fpath)
212
+ warn_flag = False
213
+ # # 内容关键字检查
214
+ for pat, detail in Compiler.PYFILE_WORD_WARNING_CHECK.items():
215
+ for i, line in enumerate(content.split('\n')):
216
+ m = re.search(pat, line)
217
+ if m:
218
+ # 检查m前面同一行内是否有#,如果有则忽略
219
+ comment = re.search(r'#', line[:m.start()])
220
+
221
+ # 检查m后面同一行内是否有#\s*ignore;,如果有则忽略
222
+ ignore = re.search(r'#\s*>\s*ignore', line[m.end():])
223
+
224
+ if not comment and not ignore:
225
+ warn_flag = True
226
+ core.warn('Compiler.potential_check', f'[{os.path.basename(os.path.dirname(fpath))}/{fname} line:{i + 1}]:', detail, end='', head='\n', ln=config.language)
227
+ return warn_flag
228
+
229
+ @staticmethod
230
+ def preprocess_if_block(source_code: str, variables: dict[str, object]) -> str:
231
+ """
232
+ 预处理if块,将 # > if, # > elif, # > else, # > endif 替换为实际的程序内容 |
233
+ pre-process if blocks by replacing # > if, # > elif, # > else, # > endif with actual code.
234
+ """
235
+ lines = source_code.split('\n') # 按行分割源代码 | split source code into lines
236
+ stack = [] # 初始化一个栈,用于跟踪if条件 | initialize a stack to track if conditions
237
+ result = [] # 初始化一个列表,用于存储处理后的代码行 | initialize a list to store processed code lines
238
+
239
+ for i, line in enumerate(lines): # 遍历源代码的每一行 | iterate over each line of source code
240
+ striped = line.strip() # 去掉行首尾的空格和换行符 | strip leading and trailing whitespace
241
+ # 使用正则表达式匹配不同的条件语句 | use regex to match different conditional statements
242
+ if_match = re.match(r'#\s*>\s*if\s+([^:.]*)$', striped) # 匹配 '# > if' 语句 | match '# > if' statement
243
+ elif_match = re.match(r'#\s*>\s*elif\s+([^:.]*)$', striped) # 匹配 '# > elif' 语句 | match '# > elif' statement
244
+ else_match = re.match(r'#\s*>\s*else$', striped) # 匹配 '# > else' 语句 | match '# > else' statement
245
+ endif_match = re.match(r'#\s*>\s*endif$', striped) # 匹配 '# > endif' 语句 | match '# > endif' statement
246
+
247
+ if if_match: # 如果当前行是 '# > if' 语句 | if it's a '# > if' statement
248
+ condition = if_match.group(1) # 提取条件表达式 | extract the condition expression
249
+ stack.append(eval(condition, variables)) # 评估条件表达式并将其结果压入栈中 | evaluate condition and push result onto stack
250
+ elif elif_match and stack: # 如果当前行是 '# > elif' 语句,并且栈不为空 | if it's a '# > elif' and stack isn't empty
251
+ condition = elif_match.group(1) # 提取条件表达式 | extract the condition expression
252
+ stack[-1] = eval(condition, variables) # 评估条件表达式并更新栈顶 | evaluate condition and update the top of the stack
253
+ elif else_match and stack: # 如果当前行是 '# > else' 语句,并且栈不为空 | if it's a '# > else' and stack isn't empty
254
+ stack[-1] = not stack[-1] # 将栈顶元素取反 | negate the top of the stack
255
+ elif endif_match: # 如果当前行是 '# > endif' 语句 | if it's a '# > endif' statement
256
+ stack.pop() # 弹出栈顶元素 | pop the top of the stack
257
+ else: # 如果当前行不是条件语句 | if it's not a conditional statement
258
+ if not stack or all(stack): # 如果栈为空,或者栈中所有元素均为真 | if stack is empty or all elements are True
259
+ result.append(line) # 将当前行加入结果列表中 | add the current line to the result
260
+
261
+ return '\n'.join(result) # 将处理后的所有代码行连接成一个字符串,并返回最终结果 | join all processed lines into a string and return
262
+
263
+ def find_chain_import(self, fpath: str, search_dirs: list[str], project_path: str = None, records: dict[str, None] = None) -> list[str]:
264
+ """
265
+ 查找文件中的所有import语句,并返回所有import的文件路径 | find all import statements in a file and return the paths of all imported files
266
+ PY_IMPORT_PAT: re.compile(r'\s+from\s+(.+)(?=\s+import)\s+import\s+\*')
267
+ :param fpath: str 目标文件路径 | target file path
268
+ :param search_dirs: list[str] 搜索目录 | search directories
269
+ :param project_path=None: str python项目中的概念,指根文件所在的目录。如果不指定,默认使用第一次调用时给定的fpath,并且稍后的递归会全部使用此路径 |
270
+ concept in python-project, refers to the directory where the root file is located. If not specified, the fpath given at the first call is used by default, and all subsequent recursions will use this path
271
+ :param records=None: dict[str, None] 记录已经查找过的文件路径,避免重复查找 | record the file paths that have been searched to avoid duplicate searches
272
+ """
273
+ if records is None:
274
+ records = {}
275
+ if not os.path.exists(fpath):
276
+ core.error('Compiler.find_chain_import', core.lformat(LOC_FILE_NOT_EXISTS, [fpath]), head='\n', ln=config.language)
277
+ imps = []
278
+ content = self.auto_read(fpath)
279
+ project_path = project_path or os.path.dirname(fpath)
280
+ for no, line in enumerate(content.split('\n')):
281
+ m = self.PY_IMPORT_PAT.match(line)
282
+ if m:
283
+ target = m.group(1)
284
+ target_path = project_path
285
+
286
+ ## 向前定位 | locate forward
287
+ if target.startswith('.'):
288
+ target_path = os.path.dirname(fpath) # 因为使用了相对路径,所以需要先定位到当前文件所在的目录 |
289
+ # because relative path is used, need to locate the directory where the current file is located first
290
+ count = 0
291
+ for c in target:
292
+ if c == '.':
293
+ count += 1
294
+ else:
295
+ break
296
+ if count > 1:
297
+ for _ in range(count - 1):
298
+ target_path = os.path.dirname(target_path)
299
+
300
+ ## 向后定位 | locate backward
301
+ while (_idx := target.find('.')) != -1:
302
+ first_name = target[:_idx]
303
+ target_path = os.path.join(target_path, first_name)
304
+ target = target[_idx + 1:]
305
+
306
+ ## 检查是否存在 | check if exists
307
+ this_path = os.path.join(target_path, target)
308
+ if os.path.isdir(this_path):
309
+ this_path = os.path.join(this_path, '__init__.py')
310
+ else:
311
+ this_path += '.py'
312
+
313
+ if not os.path.exists(this_path):
314
+ core.error('Compiler.find_chain_import', core.lformat(LOC_CHAIN_FILE_NOT_EXISTS, [fpath, no + 1, this_path]), head='\n', ln=config.language)
315
+ if this_path not in records:
316
+ records[this_path] = None
317
+ tmp = self.find_chain_import(this_path, search_dirs, project_path, records) + [this_path]
318
+ imps.extend(tmp)
319
+
320
+ return imps
321
+
322
+ @staticmethod
323
+ def relist_pyimports_to_jsimports(base_dir:str, pyimps:list[str]) -> list[str]:
324
+ """
325
+ 将python的imports路径列表转换为js的imports路径列表 | convert a list of python imports paths to a list of js imports paths
326
+ """
327
+ jsimps = []
328
+ for pyimp in pyimps:
329
+ rel_path_nodes:list[str] = os.path.relpath(pyimp, base_dir).replace('\\', '/').split('/')
330
+ if rel_path_nodes[-1] == '__init__.py':
331
+ rel_path_nodes.pop()
332
+ else:
333
+ rel_path_nodes[-1] = rel_path_nodes[-1][:-3]
334
+ jsimps.append('./' + '.'.join(rel_path_nodes) + '.js')
335
+ return jsimps
336
+
337
+
338
+ class CompilerBase(Compiler_Utils):
339
+
340
+ def __init__(self, src_dir, build_dir):
341
+ # check
342
+ if not os.path.exists(src_dir):
343
+ core.error('Compiler.__init__', core.lformat(LOC_FILE_NOT_EXISTS, ['src', src_dir]), head='\n', ln=config.language)
344
+
345
+ src_dir = os.path.abspath(src_dir)
346
+ build_dir = os.path.abspath(build_dir)
347
+ base_dir = os.path.dirname(src_dir)
348
+ lib_dir = os.path.join(base_dir, 'library')
349
+ built_dir = os.path.join(base_dir, 'builtin')
350
+
351
+ # 在builtin文件下搜索需要跳过的文件,计入到PYFILE_IGNORE_CHECK_FNAMES中
352
+ for fname in os.listdir(os.path.join(base_dir, "builtin")):
353
+ if fname.endswith('.py') and fname not in ['const.py', 'proto.py', 'utils.py']:
354
+ self.PYFILE_IGNORE_CHECK_FNAMES.append(f'builtin/{fname}')
355
+
356
+ self.src_dir = os.path.abspath(src_dir)
357
+ self.lib_dir = os.path.abspath(lib_dir)
358
+ self.build_dir = os.path.abspath(build_dir)
359
+ self.built_dir = os.path.abspath(built_dir)
360
+ self.target_dir = os.path.join(self.build_dir, '__target__')
361
+ self.build_name = os.path.basename(self.build_dir)
362
+
363
+ @property
364
+ def builtin_py(self) -> str:
365
+ """
366
+ 返回builtin目录下的__init__.py的路径 | return the path of __init__.py in builtin
367
+ """
368
+ return os.path.join(self.built_dir, '__init__.py')
369
+
370
+ @property
371
+ def target_py(self) -> str:
372
+ """
373
+ 返回build下的main.py的路径 | return the path of main.py in build
374
+ """
375
+ return os.path.join(self.build_dir, 'main.py')
376
+
377
+ @property
378
+ def target_js(self):
379
+ """
380
+ 返回build下的main.js的路径 | return the path of main.js in build
381
+ """
382
+ return os.path.join(self.target_dir, 'main.js')
383
+
384
+
385
+ class Compiler(CompilerBase):
386
+ def pre_compile(self):
387
+ """
388
+ 预编译 | Precompile
389
+ """
390
+ src_paths: list[str] = self.copy_to() # 复制src到build目录 | copy all files in src to build
391
+ # 获取src目录下的所有.py文件的路径 | get the paths of all .py files under src
392
+
393
+ core.lprint(WAIT, LOC_PREPROCESSING, end="", ln=config.language)
394
+ py_fpath, py_names, warn_flag = [], [], False
395
+ for root, dirs, files in os.walk(self.build_dir):
396
+ for file in files:
397
+ if file.endswith('.py'):
398
+ fpath: str = str(os.path.join(root, file))
399
+
400
+ # 将PYFILE_PRAGMA_INSERTS.replace("\t", "").replace(" ", "")插入到文件开头
401
+ content = self.auto_read(fpath)
402
+ content = self.PYFILE_PRAGMA_INSERTS.replace("\t", "").replace(" ", "") + content
403
+
404
+ with open(fpath, 'w', encoding='utf-8') as f: # 注意,这里修改的是build目录下的文件,不是源文件 | Note that the file under the build directory is modified here, not the source file
405
+ f.write(content)
406
+
407
+ # 得到src目录后面的内容
408
+ rel_name = os.path.relpath(fpath, self.build_dir).replace('\\', '/')
409
+ py_names.append(rel_name.replace('/', '.'))
410
+ py_fpath.append(fpath)
411
+ warn_flag |= self.potential_check(fpath, rel_name)
412
+ if warn_flag:
413
+ print() # 换行
414
+
415
+ _usubs_ = [] # update_subclass
416
+ _pre_import_, _pre_imp_detail_ = [], {} # > import
417
+ _imports = [] # chain import
418
+ _pre_sort_ = {} # > sort
419
+ _pre_define_ = {} # > define
420
+ _js_replace_, _insert_id_ = {}, 0 # > insert
421
+
422
+ # -------------------------------- ONLY IMPORT * -------------------------------- #
423
+ # 只允许from xxx import *的情况 | only allow from xxx import *
424
+ for i, fpath in enumerate(py_fpath):
425
+ content = self.auto_read(fpath)
426
+ for line in content.split('\n'):
427
+ # 1. 检查 import xxx的情况 | check import xxx
428
+ m = re.match(r'\s*import\s+([^\s]+)', line)
429
+ if m:
430
+ core.error('Compiler.pre_compile', core.lformat(LOC_IMPORT_STAR_ERROR, [m.group(1), m.group(1)]), head='\n', ln=config.language)
431
+ # 2. 检查 from xxx import yyys的情况(yyys不能是*) | check from xxx import yyys(yyys can't be *)
432
+ m = re.match(r'\n\s*from\s+([^\s]+)\s+import\s+([^\s]+)', line)
433
+ if m and (not m.group(2) or m.group(2)[0] != '*'):
434
+ core.error('Compiler.pre_compile', core.lformat(LOC_IMPORT_STAR2_ERROR, [m.group(1), m.group(2), m.group(1)]), head='\n', ln=config.language)
435
+
436
+ # -------------------------------- EXPAND IMPORT * -------------------------------- #
437
+ _imports = self.find_chain_import(self.target_py, [os.path.dirname(self.src_dir), self.src_dir])
438
+ _js_imports = self.relist_pyimports_to_jsimports(self.build_dir, _imports)
439
+
440
+ # ----------------------------------- REMOVE ----------------------------------- #
441
+ # 移除所有# > remove所在行的内容
442
+ # | remove all # > remove in .py files
443
+ for fpath in py_fpath:
444
+ content = self.auto_read(fpath)
445
+ new_content = ""
446
+ for line in content.split('\n'):
447
+ if not re.search(r'#\s*>\s*remove', line):
448
+ new_content += line + '\n'
449
+
450
+ with open(fpath, 'w', encoding='utf-8') as f:
451
+ f.write(new_content)
452
+
453
+ # ------------------------------------ SORT ------------------------------------ #
454
+ # 获取所有.py文件中的所有# > sort的内容,并记录下来(不存在则默认为65535)
455
+ # | get all # > sort in .py files, and record them (default 65535 if not exists)
456
+ for i, fpath in enumerate(py_fpath):
457
+ fname = py_names[i]
458
+ if fname.endswith('__init__.py'):
459
+ fname = fname[:-12] + '.js'
460
+ else:
461
+ fname = fname[:-3] + '.js'
462
+ content = self.auto_read(fpath)
463
+ m = re.search(r'#\s*>\s*sort\s+(\d+)', content)
464
+ if m:
465
+ try:
466
+ sort_num = int(m.group(1))
467
+ except ValueError:
468
+ core.warn('Compiler.pre_compile', core.lformat(LOC_SORT_NUMBER_ERROR, [m.group(1)]), end='', head='\n', ln=config.language)
469
+ sort_num = 65535
470
+ _pre_sort_[fname] = sort_num
471
+ else:
472
+ _pre_sort_[fname] = 65535
473
+
474
+ # ------------------------------------ DEFINE ------------------------------------ #
475
+ # 扫描所有# > define的内容,然后在.py中移除这些行,并记录下来
476
+ # | get all # > define in .py files, and record them
477
+ for fpath in py_fpath:
478
+ content = self.auto_read(fpath)
479
+ new_content = ""
480
+ for line in content.split('\n'):
481
+ # re.compile(r'#\s*define\s+([^\s]+)\s+([^\n]*)')
482
+ m = re.search(r'#\s*>\s*define\s+([^\s]+)\s+([^\n]*)', line)
483
+ if m:
484
+ _pre_define_[m.group(1)] = m.group(2)
485
+ new_content += '\n'
486
+ else:
487
+ new_content += line + '\n'
488
+
489
+ with open(fpath, 'w', encoding='utf-8') as f:
490
+ f.write(new_content)
491
+
492
+ # 按照keys的顺序,先用前面的key对应的内容去依次替换后面的key对应的value中
493
+ # | replace the value of the key with the content of the previous key in order
494
+ _def_keys = list(_pre_define_.keys())
495
+ _keys_len = len(_def_keys)
496
+ for i in range(_keys_len - 1):
497
+ for j in range(i + 1, _keys_len):
498
+ _pre_define_[_def_keys[j]] = _pre_define_[_def_keys[j]].replace(_def_keys[i], _pre_define_[_def_keys[i]])
499
+
500
+ # ------------------------------------ DEFINE:REPLACE ------------------------------------ #
501
+ # 将刚才记录的define替换到.py中(注意优先替换更长的串)(因此先排序)
502
+ # | replace the defined content to .py files (replace the longer string first)
503
+ _def_keys.sort(key=lambda x: len(x), reverse=True)
504
+ for fpath in py_fpath:
505
+ content = self.auto_read(fpath)
506
+
507
+ for key in _def_keys:
508
+ content = re.sub(r'[^_A-Za-z0-9]' + key, self._kfc_wrapper(_pre_define_[key]), content)
509
+
510
+ with open(fpath, 'w', encoding='utf-8') as f:
511
+ f.write(content)
512
+
513
+ # ------------------------------------ IF BLOCK ------------------------------------ #
514
+ # 预处理if块,将 # > if, # > elif, # > else, # > endif 替换为实际的程序内容
515
+ # | preprocess if block, replace # > if, # > elif, # > else, # > endif to actual code
516
+ for fpath in py_fpath:
517
+ content = self.auto_read(fpath)
518
+
519
+ content = self.preprocess_if_block(content, _pre_define_)
520
+
521
+ with open(fpath, 'w', encoding='utf-8') as f:
522
+ f.write(content)
523
+
524
+ # ------------------------------------ INSERT ------------------------------------ #
525
+ # 扫描所有# > insert的内容,然后在.py中将整行替换为# __pragma__("js", __JS_INSERT_{id})
526
+ # | get all # > insert in .py files, and replace the whole line with # __pragma__("js", __JS_INSERT_{id})
527
+ for fpath in py_fpath:
528
+ content = self.auto_read(fpath)
529
+ new_content = ""
530
+ for line in content.split('\n'):
531
+ # re.compile(r'#\s*insert\s*([^\n]*)')
532
+ # '# > insert if(obj && obj.body) for(var p of obj.body) if (p.type == MOVE) return true;'
533
+ m = re.search(r'#\s*>\s*insert\s+([^\n]*)', line)
534
+ if m:
535
+ _sign_index_ = line.find('#') # 必然存在
536
+ _js_key_ = f"__JS_INSERT_{_insert_id_:08d}"
537
+ _js_replace_[_js_key_] = m.group(1)
538
+
539
+ new_content += line[:_sign_index_] + f'# __pragma__("js", "{_js_key_}")\n'
540
+ _insert_id_ += 1
541
+ else:
542
+ new_content += line + '\n'
543
+
544
+ with open(fpath, 'w', encoding='utf-8') as f:
545
+ f.write(new_content)
546
+
547
+ core.lprint(GREEN.format('[2/6]'), LOC_DONE, " ", LOC_PREPROCESSING_FINISH, sep="", head="\r", ln=config.language)
548
+ return _imports, _js_imports, _pre_sort_, _pre_define_, _js_replace_
549
+
550
+ def transcrypt_cmd(self):
551
+ # 执行cmd命令: transcrypt -b -m -n -s -e 6 target | execute cmd: transcrypt -b -m -n -s -e 6 target
552
+ # 并获取cmd得到的输出 | and get the output of the cmd
553
+ cmd = 'transcrypt -b -m -n -s -e 6 %s' % self.target_py
554
+ core.lprint(WAIT, core.lformat(LOC_TRANSCRYPTING, [cmd]), end="", ln=config.language)
555
+ p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
556
+ stdout, stderr = p.communicate()
557
+ if 'Error while compiling' in stdout.decode():
558
+ print('\r' + stdout.decode())
559
+ core.error('Compiler.transcrypt_cmd', LOC_TRANSCRYPTING_ERROR, indent=1, head='\n', ln=config.language)
560
+ core.lprint(GREEN.format('[3/6]'), LOC_DONE, " ", LOC_TRANSCRYPTING_FINISH, sep="", head="\r", ln=config.language)
561
+
562
+ @staticmethod
563
+ def _keep_lbracket(matched) -> str:
564
+ """
565
+ 如果第一个字符是{, 则返回'{',否则返回'' | if the first char is {, return '{', else return ''
566
+ :param matched:
567
+ :return:
568
+ """
569
+ return '{' if matched.group(0)[0] == '{' else ''
570
+
571
+ @staticmethod
572
+ def _keep_first_char(matched: re.Match) -> str:
573
+ """
574
+ 保留第一个字符 | keep the first char
575
+ :param matched: re.match object | re.match对象
576
+ :return:
577
+ """
578
+ return matched.group(0)[0]
579
+
580
+ @staticmethod
581
+ def _kfc_wrapper(replace: str) -> callable:
582
+ """
583
+ 获取一个保留第一个字符的函数 | get a function to keep the first char
584
+ :param replace: str
585
+ :return: function
586
+ """
587
+
588
+ def _kfc(matched) -> str:
589
+ return matched.group(0)[0] + replace
590
+
591
+ return _kfc
592
+
593
+ def analyze_rebuild_main_js(self, defs: dict[str, object], modules=None) -> tuple[str, list[str]]:
594
+ """
595
+ 分析main.js中导入的模块名称和先后顺序, 并重新生成main.js | analyze the module names and order imported in main.js, and rebuild main.js
596
+ * 主要移除非SYSTEM_MODULES_IGNORE中的模块导入语句 | mainly remove the module import statements that are not in SYSTEM_MODULES_IGNORE
597
+ :param defs: dict{define: value} 定义的变量 | defined variables
598
+ :return: imports : str, modules (names: str)
599
+ imports是一段用于放在js主体开头的import语句 | imports is a string of import statements to be placed at the beginning of the js body
600
+ modules是一个list,包含了所有的模块名称 | modules is a list containing all module names
601
+ 其中的内容可能是这样的: ['./game.utils.js', './game.proto.js', './game.const.js', ...]
602
+ """
603
+
604
+ # create undefined
605
+ imports = ""
606
+
607
+ # if defs.get('USE_TUTORIAL_FLAG', '0') == '0' and defs.get('USE_ARENA_FLAG', '0') == '0':
608
+ # imports += 'var Flag = undefined;\n'
609
+ # if defs.get('USE_SCORE_COLLECTOR', '0') == '0':
610
+ # imports += 'var ScoreController = undefined;\nvar RESOURCE_SCORE = undefined;\n'
611
+ # imports += '\n'
612
+
613
+ core.lprint(WAIT, LOC_ANALYZING_AND_REBUILDING_MAIN_JS, end="", ln=config.language)
614
+
615
+ content = self.auto_read(self.target_js)
616
+ if modules is None: modules = []
617
+ new_modules, new_content = [],""
618
+ for line in content.split('\n'):
619
+ m = re.search(self.JS_IMPORT_PAT, line)
620
+ if not m:
621
+ new_content += line + '\n'
622
+ continue
623
+ # remove ignore if in SYSTEM_MODULES_IGNORE
624
+ module = m.group(1)
625
+
626
+ _ignore = False
627
+ if module in modules: _ignore = True
628
+ if module in new_modules: _ignore = True
629
+ if not _ignore: new_modules.append(module)
630
+
631
+ # conbine modules
632
+ modules = new_modules + modules
633
+ new_modules = []
634
+ for module in modules:
635
+ _ignore = False
636
+ if not _ignore and module.startswith(self.OTHER_IGNORE_WITH): _ignore = True
637
+ for keeps in self.BUILTIN_TRANS:
638
+ if module.endswith(keeps): _ignore = False
639
+ if not _ignore: new_modules.append(module)
640
+ modules = new_modules
641
+
642
+ # save raw main.js
643
+ with open(self.target_js[:-3] + ".raw.js", 'w', encoding='utf-8') as f:
644
+ f.write(content)
645
+
646
+ # write rebuild main.js
647
+ with open(self.target_js, 'w', encoding='utf-8') as f:
648
+ f.write(new_content)
649
+
650
+ core.lprint(GREEN.format('[4/6]'), LOC_DONE, " ", LOC_ANALYZING_AND_REBUILDING_MAIN_JS_FINISH, sep="", head="\r", ln=config.language)
651
+
652
+ return imports, modules
653
+
654
+ @staticmethod
655
+ def remove_js_import(raw) -> str:
656
+ """
657
+ 移除js中的import行
658
+ :param raw:
659
+ :return:
660
+ """
661
+ return re.sub(r'import[^\n]*\n', '', raw)
662
+
663
+ def generate_total_js(self, usr_modules, t_imps: list[str], f_sorts, f_replaces, g_replaces) -> str:
664
+ """
665
+ 生成总的main.js
666
+ 按照如下顺序组合:
667
+ ./org.transcrypt.__runtime__.js
668
+ ./game.const.js # IGNORE
669
+ ./game.proto.js # IGNORE
670
+ ./game.utils.js # IGNORE
671
+ {usr_modules}
672
+ :param usr_modules: list[str] # js vm + 用户自定义模块
673
+ :param t_imps: list[str] # main前需要导入的模块
674
+ :param f_sorts: dict{module_name: sort_priority}
675
+ :param f_replaces: dict{module_name: dict{old: new}}
676
+ :param g_replaces: dict{old: new}
677
+ :return: str
678
+ """
679
+ arena_name = const.ARENA_NAMES.get(config.arena, const.ARENA_NAMES['green']) # like green -> spawn_and_swamp
680
+ self.TOTAL_INSERT_AT_HEAD += self.ARENA_IMPORTS_GETTER[arena_name]() # add arena imports
681
+ if config.arena != "blue":
682
+ self.TOTAL_INSERT_AT_HEAD += self.ARENA_IMPORTS_NOT_BLUE
683
+ total_js = f"const __VERSION__ = '{const.VERSION}';\nconst __PYTHON_VERSION__ = '{python_version_info}';" + self.TOTAL_INSERT_AT_HEAD + f"\nexport var LANGUAGE = '{config.language}';\n"
684
+
685
+ core.lprint(WAIT, LOC_GENERATING_TOTAL_MAIN_JS, end="", ln=config.language)
686
+
687
+ # TODO: IMPS donot work
688
+
689
+ # resort modules
690
+ f_sorts[self.JS_VM] = -1
691
+
692
+ for i in range(len(usr_modules)):
693
+ for j in range(i + 1, len(usr_modules)):
694
+ if f_sorts[usr_modules[i][2:]] > f_sorts[usr_modules[j][2:]]:
695
+ usr_modules[i], usr_modules[j] = usr_modules[j], usr_modules[i]
696
+
697
+ # write modules
698
+ for module in usr_modules:
699
+ content = self.auto_read(os.path.join(self.target_dir, module))
700
+ content = self.remove_js_import(content)
701
+ for old, new in f_replaces.get(module, {}).items():
702
+ content = re.sub(old, new, content)
703
+ for old, new in self.TRANSCRYPT_ERROR_REPLACE.items():
704
+ content = re.sub(old, new, content)
705
+ total_js += f"\n// ---------------------------------------- Module:{module} "
706
+ total_js += "----------------------------------------\n\n"
707
+ total_js += content + '\n'
708
+
709
+ total_js += self.TOTAL_INSERT_BEFORE_MAIN
710
+
711
+ # write main.js
712
+ content = self.auto_read(self.target_js)
713
+ for old, new in self.TRANSCRYPT_ERROR_REPLACE.items():
714
+ content = re.sub(old, new, content)
715
+ total_js += content
716
+
717
+ # TOTAL_APPEND_ATEND
718
+ total_js += self.TOTAL_APPEND_ATEND
719
+
720
+ # replace export-pat
721
+ total_js = re.sub(self.JS_EXPORT_PAT, "", total_js)
722
+
723
+ # global replace
724
+ for old, new in g_replaces.items():
725
+ total_js = re.sub(old, new, total_js)
726
+
727
+ core.lprint(GREEN.format('[5/6]'), LOC_DONE, " ", LOC_GENERATING_TOTAL_MAIN_JS_FINISH, sep="", head="\r", ln=config.language)
728
+
729
+ # REPACE
730
+ for old, new in self.TOTAL_SIMPLE_REPLACE_WITH.items():
731
+ total_js = total_js.replace(old, new)
732
+
733
+ return total_js
734
+
735
+ def __parse_js_file_sort(self, fpath):
736
+ """
737
+ 解析js文件中的sort
738
+ :param fpath:
739
+ :return:
740
+ """
741
+ content = self.auto_read(fpath)
742
+ m = re.search(r'//\s*>\s*sort\s+(\d+)', content)
743
+ if m:
744
+ return int(m.group(1))
745
+ return 65535
746
+
747
+ def find_add_pure_js_files(self, sorts, modules):
748
+ """
749
+ 找到所有的纯js文件,并添加到modules中
750
+ :param sorts:
751
+ :param modules:
752
+ :return:
753
+ """
754
+ for root, dirs, files in os.walk(self.lib_dir):
755
+ for file in files:
756
+ if file.endswith('.js') and file not in modules:
757
+ fpath = str(os.path.join(root, file))
758
+ fname = file.replace('\\', '/')
759
+ # copy file to target
760
+ shutil.copy(fpath, os.path.join(self.target_dir, fname))
761
+ sorts[fname] = self.__parse_js_file_sort(fpath)
762
+ modules.append("./" + fname)
763
+
764
+ def compile(self, paste=False):
765
+ """
766
+ 编译
767
+ :param paste: 是否复制到剪贴板
768
+ :return:
769
+ """
770
+ imps, jimps, sorts, defs, reps = self.pre_compile()
771
+ self.transcrypt_cmd()
772
+ imports, modules = self.analyze_rebuild_main_js(defs, jimps)
773
+ self.find_add_pure_js_files(sorts, modules)
774
+ total_js = imports + "\n" + self.generate_total_js(modules, imps, sorts, self.FILE_STRONG_REPLACE, reps)
775
+
776
+ core.lprint(WAIT, LOC_EXPORTING_TOTAL_MAIN_JS, end="", ln=config.language)
777
+
778
+ # ensure exported main.mjs path
779
+ build_main_mjs = os.path.join(self.build_dir, 'main.mjs')
780
+
781
+ mjs_path = config.target if config.target is not None else config.TARGET_GETTER()
782
+ if not mjs_path.endswith('js'):
783
+ mjs_path = os.path.join(mjs_path, 'main.mjs')
784
+
785
+ # write main.mjs
786
+ with open(build_main_mjs, 'w', encoding='utf-8') as f:
787
+ f.write(total_js)
788
+
789
+ # export main.mjs
790
+ dir_path = os.path.dirname(mjs_path)
791
+ if not os.path.exists(dir_path):
792
+ core.error('Compiler.compile', core.lformat(LOC_EXPORT_DIR_PATH_NOT_EXISTS, [dir_path]), head='\n', ln=config.language)
793
+ with open(mjs_path, 'w', encoding='utf-8') as f:
794
+ f.write(total_js)
795
+
796
+ core.lprint(GREEN.format('[6/6]'), LOC_DONE, " ", LOC_EXPORTING_TOTAL_MAIN_JS_FINISH, sep="", head="\r", ln=config.language)
797
+
798
+ if mjs_path != build_main_mjs:
799
+ core.lprint(Fore.LIGHTBLUE_EX + '[Info] ' + Fore.RESET, core.lformat(LOC_USR_EXPORT_INFO, [mjs_path]), ln=config.language)
800
+
801
+ # copy to clipboard
802
+ if paste:
803
+ pyperclip.copy(total_js)
804
+ core.lprint(LOC_DONE, " ", LOC_COPY_TO_CLIPBOARD, ln=config.language)
805
+
806
+ def clean(self):
807
+ """
808
+ 清除build目录下除了main.mjs之外的所有文件和目录
809
+ * 先复制main.mjs到src目录下,然后删除build目录,再将main.mjs剪切回build目录
810
+ :return:
811
+ """
812
+ core.lprint(WAIT, LOC_CLEAN_BUILD_DIR, end="", ln=config.language)
813
+ if not os.path.exists(self.build_dir):
814
+ core.error('Compiler.clean', LOC_BUILD_DIR_NOT_EXISTS, indent=1, head='\n', ln=config.language)
815
+
816
+ if not os.path.exists(os.path.join(self.build_dir, 'main.mjs')):
817
+ core.error('Compiler.clean', LOC_MAIN_MJS_NOT_EXISTS, indent=1, head='\n', ln=config.language)
818
+
819
+ # copy main.mjs to src
820
+ shutil.copy(os.path.join(self.build_dir, 'main.mjs'), os.path.join(self.src_dir, 'main.mjs'))
821
+
822
+ # remove build dir
823
+ shutil.rmtree(self.build_dir)
824
+
825
+ # create build dir
826
+ os.makedirs(self.build_dir)
827
+
828
+ # move main.mjs to build dir
829
+ shutil.move(os.path.join(self.src_dir, 'main.mjs'), os.path.join(self.build_dir, 'main.mjs'))
830
+
831
+ core.lprint(GREEN.format('[Done]'), LOC_CLEAN_BUILD_DIR_FINISH, head="\r", ln=config.language)
832
+
833
+ def clear(self):
834
+ """
835
+ 清除build目录下所有文件和目录
836
+ :return:
837
+ """
838
+ core.lprint(WAIT, LOC_CLEAN_BUILD_DIR, end="", ln=config.language)
839
+ if not os.path.exists(self.build_dir):
840
+ core.lprint(LOC_BUILD_DIR_NOT_EXISTS, ln=config.language)
841
+
842
+ shutil.rmtree(self.build_dir)
843
+ os.makedirs(self.build_dir)
844
+
845
+ core.lprint(GREEN.format('[Done]'), LOC_CLEAN_BUILD_DIR_FINISH, head="\r", ln=config.language)
846
+
847
+
848
+ if __name__ == '__main__':
849
+ compiler = Compiler('src', 'library', 'build')
850
+ compiler.compile()
851
+ compiler.clean()