diff --git a/magicDemo.py b/magicDemo.py index c8f07f6..61a3e75 100644 --- a/magicDemo.py +++ b/magicDemo.py @@ -4,7 +4,7 @@ # 音·创 开发交流群 861684859 # Email EillesWan2006@163.com W-YI_DoctorYI@outlook.com EillesWan@outlook.com # 版权所有 金羿("Eilles Wan") & 诸葛亮与八卦阵("bgArray") & 鸣凤鸽子("MingFengPigeon") -# 若需转载或借鉴 许可声明请查看仓库目录下的 Lisence.md +# 若需转载或借鉴 许可声明请查看仓库目录下的 License.md """ @@ -13,14 +13,15 @@ Musicreater Package Version : Demo for Midi Conversion Copyright 2023 all the developers of Musicreater -开源相关声明请见 ./Lisence.md -Terms & Conditions: ./Lisence.md +开源相关声明请见 ./License.md +Terms & Conditions: ./Lisense.md """ import datetime import random import os import sys + languages = { "ZH_CN": { "MSCT": "音·创", @@ -64,7 +65,6 @@ languages = { } } - if sys.argv.__len__() > 0: currentLang = sys.argv[0] if currentLang not in languages.keys(): @@ -74,16 +74,16 @@ else: def _(__): - ''' + """ `languages` - ''' + """ return languages[currentLang][__] try: import msctPkgver except ModuleNotFoundError as E: - if input("您需要安装 mido、Brotli 模块才能使用这个样例\n请问是否安装?(y/n):").lower() in ('y', '1'): + if input("您需要安装 mido、Brotli 模块才能使用这个样例\n请问是否安装?(y/n):").lower() in ("y", "1"): os.system("pip install -r requirements.txt") import msctPkgver else: @@ -92,12 +92,13 @@ except ModuleNotFoundError as E: try: from msctPkgver.magicBeing import * import requests + # import zhdate except ModuleNotFoundError as E: if input( - "您需要安装以下模块才能使用这个样例\nrequests==2.28.1\nrich==12.6.0\nzhdate==0.1\n请问是否安装?(y/n):" - ).lower() in ('y', '1'): - open("Demo_Requirements.txt", 'w').write( + "您需要安装以下模块才能使用这个样例\nrequests==2.28.1\nrich==12.6.0\nzhdate==0.1\n请问是否安装?(y/n):" + ).lower() in ("y", "1"): + open("Demo_Requirements.txt", "w").write( "requests==2.28.1\nrich==12.6.0\nzhdate==0.1" ) os.system("pip install -r Demo_Requirements.txt") @@ -115,34 +116,37 @@ MainConsole.print( ) # 显示大标题 +MainConsole.rule(title="[bold #AB70FF]欢迎使用音·创独立转换器", characters="=", style="#26E2FF") MainConsole.rule( - title="[bold #AB70FF]欢迎使用音·创独立转换器", - characters="=", - style="#26E2FF") -MainConsole.rule( - title="[bold #AB70FF]Welcome to Independent Musicreater Convernter", - characters="-") + title="[bold #AB70FF]Welcome to Independent Musicreater Converter", characters="-" +) nowYang = datetime.datetime.now() if nowYang.month == 8 and nowYang.day == 6: # 诸葛八卦生日 - MainConsole.print("[#7DB5F0 on #121110]今天可不是催更的日子!\n诸葛亮与八卦阵{}岁生日快乐!".format( - nowYang.year - 2009), style="#7DB5F0 on #121110", justify="center", ) + MainConsole.print( + "[#7DB5F0 on #121110]今天可不是催更的日子!\n诸葛亮与八卦阵{}岁生日快乐!".format(nowYang.year - 2009), + style="#7DB5F0 on #121110", + justify="center", + ) elif nowYang.month == 4 and nowYang.day == 3: # 金羿生日快乐 - MainConsole.print("[#0089F2 on #F0F2F4]今天就不要催更啦!\n金羿{}岁生日快乐!".format( - nowYang.year - 2006), style="#0089F2 on #F0F2F4", justify="center", ) + MainConsole.print( + "[#0089F2 on #F0F2F4]今天就不要催更啦!\n金羿{}岁生日快乐!".format(nowYang.year - 2006), + style="#0089F2 on #F0F2F4", + justify="center", + ) else: # 显示箴言部分 MainConsole.print( "[#121110 on #F0F2F4]{}".format( random.choice( requests.get( - 'https://gitee.com/EillesWan/Musicreater/raw/master/resources/myWords.txt' + "https://gitee.com/EillesWan/Musicreater/raw/master/resources/myWords.txt" ) - .text.strip('\r\n') - .split('\r\n') + .text.strip("\r\n") + .split("\r\n") ) ), style="#121110 on #F0F2F4", @@ -152,40 +156,40 @@ else: prt(f"{_('LangChd')}{_(':')}{_(currentLang)}") -def formatipt( - notice: str, - fun, - errnote: str = f"{_('ErrEnter')}{_(',')}{_('Re-Enter')}{_('.')}", - *extraArg, +def format_ipt( + notice: str, + fun, + err_note: str = f"{_('ErrEnter')}{_(',')}{_('Re-Enter')}{_('.')}", + *extraArg, ): - '''循环输入,以某种格式 + """循环输入,以某种格式 notice: 输入时的提示 fun: 格式函数 - errnote: 输入不符格式时的提示 - *extraArg: 对于函数的其他参数''' + err_note: 输入不符格式时的提示 + *extraArg: 对于函数的其他参数""" while True: result = ipt(notice) try: - funresult = fun(result, *extraArg) + fun_result = fun(result, *extraArg) break - except BaseException: - prt(errnote) + except BaseError: + prt(err_note) continue - return result, funresult + return result, fun_result # 获取midi列表 while True: - midipath = ipt(f"{_('ChoosePath')}{_(':')}").lower() - if os.path.exists(midipath): - if os.path.isfile(midipath): - midis = (midipath,) - elif os.path.isdir(midipath): + midi_path = ipt(f"{_('ChoosePath')}{_(':')}").lower() + if os.path.exists(midi_path): + if os.path.isfile(midi_path): + midis = (midi_path,) + elif os.path.isdir(midi_path): midis = tuple( ( - os.path.join(midipath, i) - for i in os.listdir(midipath) - if i.lower().endswith('.mid') or i.lower().endswith('.midi') + os.path.join(midi_path, i) + for i in os.listdir(midi_path) + if i.lower().endswith(".mid") or i.lower().endswith(".midi") ) ) else: @@ -197,7 +201,7 @@ while True: break # 获取输出地址 -outpath = formatipt( +out_path = format_ipt( f"{_('ChooseOutPath')}{_(':')}", os.path.exists, f"{_('FileNotFound')}{_(',')}{_('Re-Enter')}{_('.')}", @@ -206,18 +210,18 @@ outpath = formatipt( # 选择输出格式 while True: fileFormat = ipt(f"{_('ChooseFileFormat')}{_(':')}").lower() - if fileFormat in ('0', 'mcpack'): + if fileFormat in ("0", "mcpack"): fileFormat = 0 playerFormat = 1 break - elif fileFormat in ('1', 'bdx'): + elif fileFormat in ("1", "bdx"): fileFormat = 1 while True: playerFormat = ipt(f"{_('ChoosePlayer')}{_(':')}").lower() - if playerFormat in ('0', '延迟', 'delay'): + if playerFormat in ("0", "延迟", "delay"): playerFormat = 0 - elif playerFormat in ('1', '计分板', 'scoreboard'): + elif playerFormat in ("1", "计分板", "scoreboard"): playerFormat = 1 else: prt(f"{_('ErrEnter')}{_(',')}{_('Re-Enter')}{_('.')}") @@ -232,13 +236,13 @@ debug = False # 真假字符串判断 -def boolstr(sth: str) -> bool: +def bool_str(sth: str) -> bool: try: return bool(int(sth)) - except BaseException: - if str(sth).lower() == 'true': + except BaseError: + if str(sth).lower() == "true": return True - elif str(sth).lower() == 'false': + elif str(sth).lower() == "false": return False else: raise "布尔字符串啊?" @@ -247,7 +251,7 @@ def boolstr(sth: str) -> bool: if os.path.exists("./demo_config.json"): import json - prompts = json.load(open("./demo_config.json", 'r', encoding="utf-8")) + prompts = json.load(open("./demo_config.json", "r", encoding="utf-8")) if prompts[-1] == "debug": debug = True prompts = prompts[:-1] @@ -265,7 +269,7 @@ else: ), ( f'{_("WhetherPgb")}{_(":")}', - boolstr, + bool_str, ), ( f'{_("EnterSbName")}{_(":")}', @@ -278,7 +282,7 @@ else: ), ( f'{_("WhetherSbReset")}{_(":")}', - boolstr, + bool_str, ) if playerFormat == 1 else (), @@ -296,14 +300,14 @@ else: else (), ]: if args: - prompts.append(formatipt(*args)[1]) + prompts.append(format_ipt(*args)[1]) conversion = msctPkgver.midiConvert(debug) for singleMidi in midis: - prt("\n"f"{_('Dealing')} {singleMidi} {_(':')}") - conversion.convert(singleMidi, outpath) + prt("\n" f"{_('Dealing')} {singleMidi} {_(':')}") + conversion.convert(singleMidi, out_path) if debug: - with open("./records.json", 'a', encoding="utf-8") as f: + with open("./records.json", "a", encoding="utf-8") as f: json.dump(conversion.toDICT(), f) f.write(5 * "\n") conversion_result = ( @@ -317,8 +321,13 @@ for singleMidi in midis: ) if conversion_result[0]: + c3 = conversion_result[3] + c4 = conversion_result[4] + fF = fileFormat prt( - f" {_('CmdLength')}{_(':')}{conversion_result[1]}{_(',')}{_('MaxDelay')}{_(':')}{conversion_result[2]}{f'''{_(',')}{_('PlaceSize')}{_(':')}{conversion_result[3]}{_(',')}{_('LastPos')}{_(':')}{conversion_result[4]}''' if fileFormat == 1 else ''}" + f" {_('CmdLength')}{_(':')}{conversion_result[1]}{_(',')}{_('MaxDelay')}{_(':')}" + f"{conversion_result[2]}" + f"{f'''{_(',')}{_('PlaceSize')}{_(':')}{c3}{_(',')}{_('LastPos')}{_(':')}{c4}''' if fF == 1 else ''}" ) else: prt(f"{_('Failed')}") @@ -327,7 +336,7 @@ exitSth = ipt(_("PressEnterExit")).lower() if exitSth == "record": import json - with open("./demo_config.json", 'w', encoding="utf-8") as f: + with open("./demo_config.json", "w", encoding="utf-8") as f: json.dump(prompts, f) elif exitSth == "delrec": os.remove("./demo_config.json") diff --git a/msctPkgver/__init__.py b/msctPkgver/__init__.py index 5d79c2a..2f52aa1 100644 --- a/msctPkgver/__init__.py +++ b/msctPkgver/__init__.py @@ -17,12 +17,13 @@ Terms & Conditions: ../License.md # 若需转载或借鉴 许可声明请查看仓库目录下的 License.md from .main import * -__version__ = '0.2.2.1' + +__version__ = "0.2.2.1" __all__ = [] -__author__ = (('金羿', 'Eilles Wan'), ('诸葛亮与八卦阵', 'bgArray'), ('鸣凤鸽子', 'MingFengPigeon')) +__author__ = (("金羿", "Eilles Wan"), ("诸葛亮与八卦阵", "bgArray"), ("鸣凤鸽子", "MingFengPigeon")) -print('此Midi转换功能由音·创开发者开发,版权归参与开发的人员共同所有。') -print('Copyright © 2022 all the developers of Musicreater') +print("此Midi转换功能由音·创开发者开发,版权归参与开发的人员共同所有。") +print("Copyright © 2022 all the developers of Musicreater") print("小贴:不妨试试Mid-BDX转换网页:在线的多功能Midi转换器") print("https://dislink.github.io/midi2bdx/") diff --git a/msctPkgver/bdxRead.py b/msctPkgver/bdxRead.py index 887b7bf..0deb3e7 100644 --- a/msctPkgver/bdxRead.py +++ b/msctPkgver/bdxRead.py @@ -1,3 +1,3 @@ import brotli -input(brotli.decompress(open(input("BDX文件:"), 'rb').read()[3:])) +input(brotli.decompress(open(input("BDX文件:"), "rb").read()[3:])) diff --git a/msctPkgver/exceptions.py b/msctPkgver/exceptions.py index f2e45f2..9549ce1 100644 --- a/msctPkgver/exceptions.py +++ b/msctPkgver/exceptions.py @@ -27,7 +27,9 @@ class MSCTBaseException(Exception): def __init__(self, *args): super().__init__(*args) - def miao(self, ): + def miao( + self, + ): for i in self.args: print(i + "喵!") @@ -37,29 +39,35 @@ class MSCTBaseException(Exception): class CrossNoteError(MSCTBaseException): """同通道下同音符交叉出现所产生的错误""" + pass class NotDefineTempoError(MSCTBaseException): """没有Tempo设定导致时间无法计算的错误""" + pass class MidiDestroyedError(MSCTBaseException): """Midi文件损坏""" + pass class ChannelOverFlowError(MSCTBaseException): """一个midi中含有过多的通道(数量应≤16)""" + pass class NotDefineProgramError(MSCTBaseException): """没有Program设定导致没有乐器可以选择的错误""" + pass class BaseError(BaseException): """专门骗过PEP8的错误""" + pass diff --git a/msctPkgver/magicBeing.py b/msctPkgver/magicBeing.py index dd5ccc9..6d4e319 100644 --- a/msctPkgver/magicBeing.py +++ b/msctPkgver/magicBeing.py @@ -10,20 +10,20 @@ OverflowMethod = Literal["fold", "crop", "ellipsis", "ignore"] # 高级的打印函数 def prt( - *objects: Any, - sep: str = " ", - end: str = "\n", - justify: Optional[JustifyMethod] = None, - overflow: Optional[OverflowMethod] = None, - no_wrap: Optional[bool] = None, - emoji: Optional[bool] = None, - markup: Optional[bool] = None, - highlight: Optional[bool] = None, - width: Optional[int] = None, - height: Optional[int] = None, - crop: bool = True, - soft_wrap: Optional[bool] = None, - new_line_start: bool = False, + *objects: Any, + sep: str = " ", + end: str = "\n", + justify: Optional[JustifyMethod] = None, + overflow: Optional[OverflowMethod] = None, + no_wrap: Optional[bool] = None, + emoji: Optional[bool] = None, + markup: Optional[bool] = None, + highlight: Optional[bool] = None, + width: Optional[int] = None, + height: Optional[int] = None, + crop: bool = True, + soft_wrap: Optional[bool] = None, + new_line_start: bool = False, ) -> None: """打印到控制台。 @@ -64,21 +64,21 @@ def prt( # 高级的输入函数 def ipt( - *objects: Any, - sep: str = " ", - justify: Optional[JustifyMethod] = None, - overflow: Optional[OverflowMethod] = None, - no_wrap: Optional[bool] = None, - emoji: Optional[bool] = None, - markup: Optional[bool] = None, - highlight: Optional[bool] = None, - width: Optional[int] = None, - height: Optional[int] = None, - crop: bool = True, - soft_wrap: Optional[bool] = None, - new_line_start: bool = False, - password: bool = False, - stream: Optional[TextIO] = None, + *objects: Any, + sep: str = " ", + justify: Optional[JustifyMethod] = None, + overflow: Optional[OverflowMethod] = None, + no_wrap: Optional[bool] = None, + emoji: Optional[bool] = None, + markup: Optional[bool] = None, + highlight: Optional[bool] = None, + width: Optional[int] = None, + height: Optional[int] = None, + crop: bool = True, + soft_wrap: Optional[bool] = None, + new_line_start: bool = False, + password: bool = False, + stream: Optional[TextIO] = None, ) -> str: """显示一个提示并等待用户的输入。 @@ -126,10 +126,10 @@ def ipt( def format_ipt( - notice: str, - fun, - err_note: str = "", - *extraArg, + notice: str, + fun, + err_note: str = "", + *extraArg, ): """循环输入,以某种格式 notice: 输入时的提示 diff --git a/msctPkgver/main.py b/msctPkgver/main.py index c70cf60..c1f0007 100644 --- a/msctPkgver/main.py +++ b/msctPkgver/main.py @@ -30,18 +30,14 @@ from .utils import * from .exceptions import * from typing import TypeVar, Union -T = TypeVar('T') # Declare type variable +T = TypeVar("T") # Declare type variable VM = TypeVar("VM", mido.MidiFile, None) # void mido class SingleNote: def __init__( - self, - instrument: int, - pitch: int, - velocity, - startTime: int, - lastTime: int): + self, instrument: int, pitch: int, velocity, startTime: int, lastTime: int + ): """用于存储单个音符的类 :param instrument 乐器编号 :param pitch 音符编号 @@ -50,15 +46,15 @@ class SingleNote: 注:此处的时间是用从乐曲开始到当前的毫秒数 :param lastTime 音符延续时间(ms)""" self.instrument = instrument - '''乐器编号''' + """乐器编号""" self.note = pitch - '''音符编号''' + """音符编号""" self.velocity = velocity - '''力度/响度''' + """力度/响度""" self.startTime = startTime - '''开始之时 ms''' + """开始之时 ms""" self.lastTime = lastTime - '''音符持续时间 ms''' + """音符持续时间 ms""" @property def inst(self): @@ -71,16 +67,13 @@ class SingleNote: return self.note def __str__(self): - return f"Note(inst = {self.inst}, pitch = {self.note}, velocity = {self.velocity}, " \ - f"startTime = {self.startTime}, lastTime = {self.lastTime}, )" + return ( + f"Note(inst = {self.inst}, pitch = {self.note}, velocity = {self.velocity}, " + f"startTime = {self.startTime}, lastTime = {self.lastTime}, )" + ) def __tuple__(self): - return ( - self.inst, - self.note, - self.velocity, - self.startTime, - self.lastTime) + return self.inst, self.note, self.velocity, self.startTime, self.lastTime def __dict__(self): return { @@ -146,11 +139,7 @@ class midiConvert: self.midFileName: str = "" self.exeHead = "" self.methods = MethodList( - [ - self._toCmdList_m1(), - self._toCmdList_m2(), - self._toCmdList_m3() - ] + [self._toCmdList_m1(), self._toCmdList_m2(), self._toCmdList_m3()] ) self.methods_byDelay = MethodList( @@ -166,11 +155,7 @@ class midiConvert: self.prt = prt self.ipt = ipt - def convert( - self, - midiFile: str, - outputPath: str, - oldExeFormat: bool = True): + def convert(self, midiFile: str, outputPath: str, oldExeFormat: bool = True): """转换前需要先运行此函数来获取基本信息""" self.midiFile = midiFile @@ -349,53 +334,53 @@ class midiConvert: try: try: return { - 34: ('note.bd', 7), - 35: ('note.bd', 7), - 36: ('note.hat', 7), - 37: ('note.snare', 7), - 38: ('note.snare', 7), - 39: ('note.snare', 7), - 40: ('note.hat', 7), - 41: ('note.snare', 7), - 42: ('note.hat', 7), - 43: ('note.snare', 7), - 44: ('note.snare', 7), - 45: ('note.bell', 4), - 46: ('note.snare', 7), - 47: ('note.snare', 7), - 48: ('note.bell', 4), - 49: ('note.hat', 7), - 50: ('note.bell', 4), - 51: ('note.bell', 4), - 52: ('note.bell', 4), - 53: ('note.bell', 4), - 54: ('note.bell', 4), - 55: ('note.bell', 4), - 56: ('note.snare', 7), - 57: ('note.hat', 7), - 58: ('note.chime', 4), - 59: ('note.iron_xylophone', 6), - 60: ('note.bd', 7), - 61: ('note.bd', 7), - 62: ('note.xylophone', 4), - 63: ('note.xylophone', 4), - 64: ('note.xylophone', 4), - 65: ('note.hat', 7), - 66: ('note.bell', 4), - 67: ('note.bell', 4), - 68: ('note.hat', 7), - 69: ('note.hat', 7), - 70: ('note.flute', 5), - 71: ('note.flute', 5), - 72: ('note.hat', 7), - 73: ('note.hat', 7), - 74: ('note.xylophone', 4), - 75: ('note.hat', 7), - 76: ('note.hat', 7), - 77: ('note.xylophone', 4), - 78: ('note.xylophone', 4), - 79: ('note.bell', 4), - 80: ('note.bell', 4), + 34: ("note.bd", 7), + 35: ("note.bd", 7), + 36: ("note.hat", 7), + 37: ("note.snare", 7), + 38: ("note.snare", 7), + 39: ("note.snare", 7), + 40: ("note.hat", 7), + 41: ("note.snare", 7), + 42: ("note.hat", 7), + 43: ("note.snare", 7), + 44: ("note.snare", 7), + 45: ("note.bell", 4), + 46: ("note.snare", 7), + 47: ("note.snare", 7), + 48: ("note.bell", 4), + 49: ("note.hat", 7), + 50: ("note.bell", 4), + 51: ("note.bell", 4), + 52: ("note.bell", 4), + 53: ("note.bell", 4), + 54: ("note.bell", 4), + 55: ("note.bell", 4), + 56: ("note.snare", 7), + 57: ("note.hat", 7), + 58: ("note.chime", 4), + 59: ("note.iron_xylophone", 6), + 60: ("note.bd", 7), + 61: ("note.bd", 7), + 62: ("note.xylophone", 4), + 63: ("note.xylophone", 4), + 64: ("note.xylophone", 4), + 65: ("note.hat", 7), + 66: ("note.bell", 4), + 67: ("note.bell", 4), + 68: ("note.hat", 7), + 69: ("note.hat", 7), + 70: ("note.flute", 5), + 71: ("note.flute", 5), + 72: ("note.hat", 7), + 73: ("note.hat", 7), + 74: ("note.xylophone", 4), + 75: ("note.hat", 7), + 76: ("note.hat", 7), + 77: ("note.xylophone", 4), + 78: ("note.xylophone", 4), + 79: ("note.bell", 4), + 80: ("note.bell", 4), }[instrumentID] except BaseError: return "note.bd", 7 @@ -412,17 +397,16 @@ class midiConvert: @staticmethod def __score2time(score: int): - return str(int(int(score / 20) / 60)) + ":" + \ - str(int(int(score / 20) % 60)) + return str(int(int(score / 20) / 60)) + ":" + str(int(int(score / 20) % 60)) def __formProgressBar( - self, - maxscore: int, - scoreboard_name: str, - progressbar: tuple = ( - r"▶ %%N [ %%s/%^s %%% __________ %%t|%^t ]", - ("§e=§r", "§7=§r"), - ), + self, + maxscore: int, + scoreboard_name: str, + progressbar: tuple = ( + r"▶ %%N [ %%s/%^s %%% __________ %%t|%^t ]", + ("§e=§r", "§7=§r"), + ), ) -> list: pgs_style = progressbar[0] @@ -439,7 +423,7 @@ class midiConvert: | `%%%` | 当前进度比率 | | `_` | 用以表示进度条占位| """ - perEach = maxscore / pgs_style.count('_') + perEach = maxscore / pgs_style.count("_") result = [] @@ -451,20 +435,17 @@ class midiConvert: def replaceBar(_i): try: - return pgs_style.replace( - '_', - progressbar[1][0], - _i + - 1).replace( - '_', - progressbar[1][1]) + return pgs_style.replace("_", progressbar[1][0], _i + 1).replace( + "_", progressbar[1][1] + ) except BaseError: - return pgs_style.replace('_', progressbar[1][0], _i + 1) + return pgs_style.replace("_", progressbar[1][0], _i + 1) sbn_pc = scoreboard_name[:2] if r"%%%" in pgs_style: result.append( - "scoreboard objectives add {}PercT dummy \"百分比计算\"".format(sbn_pc)) + 'scoreboard objectives add {}PercT dummy "百分比计算"'.format(sbn_pc) + ) result.append( self.exeHead.format("@a[scores={" + scoreboard_name + "=1..}]") + "scoreboard players set MaxScore {} {}".format( @@ -496,9 +477,11 @@ class midiConvert: if r"%%t" in pgs_style: result.append( - "scoreboard objectives add {}TMinT dummy \"时间计算:分\"".format(sbn_pc)) + 'scoreboard objectives add {}TMinT dummy "时间计算:分"'.format(sbn_pc) + ) result.append( - "scoreboard objectives add {}TSecT dummy \"时间计算:秒\"".format(sbn_pc)) + 'scoreboard objectives add {}TSecT dummy "时间计算:秒"'.format(sbn_pc) + ) result.append( self.exeHead.format("@a[scores={" + scoreboard_name + "=1..}]") + "scoreboard players set n20 {} 20".format(scoreboard_name) @@ -546,7 +529,7 @@ class midiConvert: ) ) - for i in range(pgs_style.count('_')): + for i in range(pgs_style.count("_")): npg_stl = ( replaceBar(i).replace(r"%%N", self.midFileName) if r"%%N" in pgs_style @@ -568,9 +551,12 @@ class midiConvert: ) if r"%%t" in npg_stl: npg_stl = npg_stl.replace( - r"%%t", r'"},{"score":{"name":"*","objective":"{-}TMinT"}},{"text":":"},' + r"%%t", + r'"},{"score":{"name":"*","objective":"{-}TMinT"}},{"text":":"},' r'{"score":{"name":"*","objective":"{-}TSecT"}},{"text":"'.replace( - r"{-}", sbn_pc), ) + r"{-}", sbn_pc + ), + ) result.append( self.exeHead.format( "@a[scores={" @@ -592,10 +578,11 @@ class midiConvert: return result def _toCmdList_m1( - self, - scoreboard_name: str = "mscplay", - MaxVolume: float = 1.0, - speed: float = 1.0) -> list: + self, + scoreboard_name: str = "mscplay", + MaxVolume: float = 1.0, + speed: float = 1.0, + ) -> list: """ 使用Dislink Sforza的转换思路,将midi转换为我的世界命令列表 :param scoreboard_name: 我的世界的计分板名称 @@ -604,8 +591,7 @@ class midiConvert: """ # :param volume: 音量,注意:这里的音量范围为(0,1],如果超出将被处理为正确值,其原理为在距离玩家 (1 / volume -1) 的地方播放音频 tracks = [] - MaxVolume = 1 if MaxVolume > 1 else ( - 0.001 if MaxVolume <= 0 else MaxVolume) + MaxVolume = 1 if MaxVolume > 1 else (0.001 if MaxVolume <= 0 else MaxVolume) commands = 0 maxscore = 0 @@ -639,17 +625,17 @@ class midiConvert: if msg.channel == 9: soundID, _X = self.__bitInst2ID_withX(instrumentID) else: - soundID, _X = self.__Inst2soundID_withX( - instrumentID) + soundID, _X = self.__Inst2soundID_withX(instrumentID) singleTrack.append( - "execute @a[scores={" + - str(scoreboard_name) + - "=" + - str(nowscore) + - "}" + - f"] ~ ~ ~ playsound {soundID} @s ^ ^ ^{1 / MaxVolume - 1} {msg.velocity / 128} " - f"{2 ** ((msg.note - 60 - _X) / 12)}") + "execute @a[scores={" + + str(scoreboard_name) + + "=" + + str(nowscore) + + "}" + + f"] ~ ~ ~ playsound {soundID} @s ^ ^ ^{1 / MaxVolume - 1} {msg.velocity / 128} " + f"{2 ** ((msg.note - 60 - _X) / 12)}" + ) commands += 1 if len(singleTrack) != 0: tracks.append(singleTrack) @@ -658,10 +644,10 @@ class midiConvert: # 原本这个算法的转换效果应该和上面的算法相似的 def _toCmdList_m2( - self, - scoreboard_name: str = "mscplay", - MaxVolume: float = 1.0, - speed: float = 1.0, + self, + scoreboard_name: str = "mscplay", + MaxVolume: float = 1.0, + speed: float = 1.0, ) -> list: """ 使用金羿的转换思路,将midi转换为我的世界命令列表 @@ -671,8 +657,7 @@ class midiConvert: :return: tuple(命令列表, 命令个数, 计分板最大值) """ - MaxVolume = 1 if MaxVolume > 1 else ( - 0.001 if MaxVolume <= 0 else MaxVolume) + MaxVolume = 1 if MaxVolume > 1 else (0.001 if MaxVolume <= 0 else MaxVolume) # 一个midi中仅有16个通道 我们通过通道来识别而不是音轨 channels = { @@ -724,14 +709,12 @@ class midiConvert: if self.debugMode: try: if msg.channel > 15: - raise ChannelOverFlowError( - f"当前消息 {msg} 的通道超限(≤15)") + raise ChannelOverFlowError(f"当前消息 {msg} 的通道超限(≤15)") except BaseError: pass if msg.type == "program_change": - channels[msg.channel].append( - ("PgmC", msg.program, microseconds)) + channels[msg.channel].append(("PgmC", msg.program, microseconds)) elif msg.type == "note_on" and msg.velocity != 0: channels[msg.channel].append( @@ -739,10 +722,9 @@ class midiConvert: ) elif (msg.type == "note_on" and msg.velocity == 0) or ( - msg.type == "note_off" + msg.type == "note_off" ): - channels[msg.channel].append( - ("NoteE", msg.note, microseconds)) + channels[msg.channel].append(("NoteE", msg.note, microseconds)) """整合后的音乐通道格式 每个通道包括若干消息元素其中逃不过这三种: @@ -802,15 +784,13 @@ class midiConvert: nowTrack.append( self.exeHead.format( - "@a[scores=({}={})]".format( - scoreboard_name, - score_now).replace( - '(', - r"{").replace( - ")", - r"}")) + - f"playsound {soundID} @s ^ ^ ^{1 / MaxVolume - 1} {msg[2] / 128} " - f"{2 ** ((msg[1] - 60 - _X) / 12)}") + "@a[scores=({}={})]".format(scoreboard_name, score_now) + .replace("(", r"{") + .replace(")", r"}") + ) + + f"playsound {soundID} @s ^ ^ ^{1 / MaxVolume - 1} {msg[2] / 128} " + f"{2 ** ((msg[1] - 60 - _X) / 12)}" + ) cmdAmount += 1 @@ -820,10 +800,10 @@ class midiConvert: # 简单的单音填充 def _toCmdList_m3( - self, - scoreboard_name: str = "mscplay", - MaxVolume: float = 1.0, - speed: float = 1.0, + self, + scoreboard_name: str = "mscplay", + MaxVolume: float = 1.0, + speed: float = 1.0, ) -> list: """ 使用金羿的转换思路,将midi转换为我的世界命令列表,并使用完全填充算法优化音感 @@ -839,8 +819,7 @@ class midiConvert: MaxVolume = 0.001 # 一个midi中仅有16个通道 我们通过通道来识别而不是音轨 - channels = [[], [], [], [], [], [], [], - [], [], [], [], [], [], [], [], []] + channels = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []] # 我们来用通道统计音乐信息 for i, track in enumerate(self.midi.tracks): @@ -867,8 +846,7 @@ class midiConvert: channelMsg = False if channelMsg: if msg.channel > 15: - raise ChannelOverFlowError( - f"当前消息 {msg} 的通道超限(≤15)") + raise ChannelOverFlowError(f"当前消息 {msg} 的通道超限(≤15)") if msg.type == "program_change": channels[msg.channel].append( @@ -881,10 +859,9 @@ class midiConvert: ) elif (msg.type == "note_on" and msg.velocity == 0) or ( - msg.type == "note_off" + msg.type == "note_off" ): - channels[msg.channel].append( - ("NoteE", msg.note, microseconds)) + channels[msg.channel].append(("NoteE", msg.note, microseconds)) """整合后的音乐通道格式 每个通道包括若干消息元素其中逃不过这三种: @@ -901,8 +878,7 @@ class midiConvert: ("NoteS", 结束的音符ID, 距离演奏开始的毫秒)""" - note_channels = [[], [], [], [], [], [], - [], [], [], [], [], [], [], [], [], []] + note_channels = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []] # 此处 我们把通道视为音轨 for i in range(len(channels)): @@ -995,13 +971,14 @@ class midiConvert: maxScore = max(maxScore, score_now) nowTrack.append( - "execute @a[scores={" + - str(scoreboard_name) + - "=" + - str(score_now) + - "}" + - f"] ~ ~ ~ playsound {soundID} @s ~ ~{1 / every_note[4] - 1} ~ " - f"{note.velocity * (0.7 if CheckFirstChannel else 0.9)} {2 ** ((note.pitch - 60 - _X) / 12)}") + "execute @a[scores={" + + str(scoreboard_name) + + "=" + + str(score_now) + + "}" + + f"] ~ ~ ~ playsound {soundID} @s ~ ~{1 / every_note[4] - 1} ~ " + f"{note.velocity * (0.7 if CheckFirstChannel else 0.9)} {2 ** ((note.pitch - 60 - _X) / 12)}" + ) cmdAmount += 1 tracks.append(nowTrack) @@ -1009,10 +986,10 @@ class midiConvert: return [tracks, cmdAmount, maxScore] def _toCmdList_withDelay_m1( - self, - MaxVolume: float = 1.0, - speed: float = 1.0, - player: str = "@a", + self, + MaxVolume: float = 1.0, + speed: float = 1.0, + player: str = "@a", ) -> list: """ 使用Dislink Sforza的转换思路,将midi转换为我的世界命令列表,并输出每个音符之后的延迟 @@ -1023,8 +1000,7 @@ class midiConvert: # :param volume: 音量,注意:这里的音量范围为(0,1],如果超出将被处理为正确值,其原理为在距离玩家 (1 / volume -1) 的地方播放音频 tracks = {} - MaxVolume = 1 if MaxVolume > 1 else ( - 0.001 if MaxVolume <= 0 else MaxVolume) + MaxVolume = 1 if MaxVolume > 1 else (0.001 if MaxVolume <= 0 else MaxVolume) for i, track in enumerate(self.midi.tracks): @@ -1047,14 +1023,16 @@ class midiConvert: soundID, _X = self.__Inst2soundID_withX(instrumentID) try: tracks[now_tick].append( - self.exeHead.format(player) + - f"playsound {soundID} @s ^ ^ ^{1 / MaxVolume - 1} {msg.velocity / 128} " - f"{2 ** ((msg.note - 60 - _X) / 12)}") + self.exeHead.format(player) + + f"playsound {soundID} @s ^ ^ ^{1 / MaxVolume - 1} {msg.velocity / 128} " + f"{2 ** ((msg.note - 60 - _X) / 12)}" + ) except BaseError: tracks[now_tick] = [ - self.exeHead.format(player) + - f"playsound {soundID} @s ^ ^ ^{1 / MaxVolume - 1} {msg.velocity / 128} " - f"{2 ** ((msg.note - 60 - _X) / 12)}"] + self.exeHead.format(player) + + f"playsound {soundID} @s ^ ^ ^{1 / MaxVolume - 1} {msg.velocity / 128} " + f"{2 ** ((msg.note - 60 - _X) / 12)}" + ] results = [] @@ -1076,10 +1054,10 @@ class midiConvert: return [results, max(all_ticks)] def _toCmdList_withDelay_m2( - self, - MaxVolume: float = 1.0, - speed: float = 1.0, - player: str = "@a", + self, + MaxVolume: float = 1.0, + speed: float = 1.0, + player: str = "@a", ) -> list: """ 使用金羿的转换思路,将midi转换为我的世界命令列表,并输出每个音符之后的延迟 @@ -1090,8 +1068,7 @@ class midiConvert: # :param volume: 音量,注意:这里的音量范围为(0,1],如果超出将被处理为正确值,其原理为在距离玩家 (1 / volume -1) 的地方播放音频 tracks = {} - MaxVolume = 1 if MaxVolume > 1 else ( - 0.001 if MaxVolume <= 0 else MaxVolume) + MaxVolume = 1 if MaxVolume > 1 else (0.001 if MaxVolume <= 0 else MaxVolume) # 一个midi中仅有16个通道 我们通过通道来识别而不是音轨 channels = { @@ -1143,14 +1120,12 @@ class midiConvert: if self.debugMode: try: if msg.channel > 15: - raise ChannelOverFlowError( - f"当前消息 {msg} 的通道超限(≤15)") + raise ChannelOverFlowError(f"当前消息 {msg} 的通道超限(≤15)") except BaseError: pass if msg.type == "program_change": - channels[msg.channel].append( - ("PgmC", msg.program, microseconds)) + channels[msg.channel].append(("PgmC", msg.program, microseconds)) elif msg.type == "note_on" and msg.velocity != 0: channels[msg.channel].append( @@ -1158,10 +1133,9 @@ class midiConvert: ) elif (msg.type == "note_on" and msg.velocity == 0) or ( - msg.type == "note_off" + msg.type == "note_off" ): - channels[msg.channel].append( - ("NoteE", msg.note, microseconds)) + channels[msg.channel].append(("NoteE", msg.note, microseconds)) """整合后的音乐通道格式 每个通道包括若干消息元素其中逃不过这三种: @@ -1212,14 +1186,16 @@ class midiConvert: try: tracks[score_now].append( - self.exeHead.format(player) + - f"playsound {soundID} @s ^ ^ ^{1 / MaxVolume - 1} {msg[2] / 128} " - f"{2 ** ((msg[1] - 60 - _X) / 12)}") + self.exeHead.format(player) + + f"playsound {soundID} @s ^ ^ ^{1 / MaxVolume - 1} {msg[2] / 128} " + f"{2 ** ((msg[1] - 60 - _X) / 12)}" + ) except BaseError: tracks[score_now] = [ - self.exeHead.format(player) + - f"playsound {soundID} @s ^ ^ ^{1 / MaxVolume - 1} {msg[2] / 128} " - f"{2 ** ((msg[1] - 60 - _X) / 12)}"] + self.exeHead.format(player) + + f"playsound {soundID} @s ^ ^ ^{1 / MaxVolume - 1} {msg[2] / 128} " + f"{2 ** ((msg[1] - 60 - _X) / 12)}" + ] all_ticks = list(tracks.keys()) if self.debugMode: @@ -1227,19 +1203,31 @@ class midiConvert: for i in range(len(all_ticks)): for j in range(len(tracks[all_ticks[i]])): - results.append((tracks[all_ticks[i]][j], (0 if j != 0 else ( - all_ticks[i] - all_ticks[i - 1] if i != 0 else all_ticks[i])))) + results.append( + ( + tracks[all_ticks[i]][j], + ( + 0 + if j != 0 + else ( + all_ticks[i] - all_ticks[i - 1] + if i != 0 + else all_ticks[i] + ) + ), + ) + ) return [results, max(all_ticks)] def to_mcpack( - self, - method: int = 1, - volume: float = 1.0, - speed: float = 1.0, - progressbar=None, - scoreboard_name: str = "mscplay", - isAutoReset: bool = False, + self, + method: int = 1, + volume: float = 1.0, + speed: float = 1.0, + progressbar=None, + scoreboard_name: str = "mscplay", + isAutoReset: bool = False, ) -> tuple: """ 使用method指定的转换算法,将midi转换为我的世界mcpack格式的包 @@ -1253,8 +1241,9 @@ class midiConvert: """ # try: - cmdlist, maxlen, maxscore = self.methods[method - - 1](scoreboard_name, volume, speed) + cmdlist, maxlen, maxscore = self.methods[method - 1]( + scoreboard_name, volume, speed + ) # except: # return (False, f"无法找到算法ID{method}对应的转换算法") @@ -1266,22 +1255,24 @@ class midiConvert: # 写入manifest.json if not os.path.exists(f"{self.outputPath}/temp/manifest.json"): with open( - f"{self.outputPath}/temp/manifest.json", "w", encoding="utf-8" + f"{self.outputPath}/temp/manifest.json", "w", encoding="utf-8" ) as f: - f.write('{\n "format_version": 1,\n "header": {\n "description": "' + - self.midFileName + - ' Pack : behavior pack",\n "version": [ 0, 0, 1 ],\n "name": "' + - self.midFileName + - 'Pack",\n "uuid": "' + - str(uuid.uuid4()) + - '"\n },\n "modules": [\n {\n "description": "' + - f"the Player of the Music {self.midFileName}" + - '",\n "type": "data",\n "version": [ 0, 0, 1 ],\n "uuid": "' + - str(uuid.uuid4()) + - '"\n }\n ]\n}') + f.write( + '{\n "format_version": 1,\n "header": {\n "description": "' + + self.midFileName + + ' Pack : behavior pack",\n "version": [ 0, 0, 1 ],\n "name": "' + + self.midFileName + + 'Pack",\n "uuid": "' + + str(uuid.uuid4()) + + '"\n },\n "modules": [\n {\n "description": "' + + f"the Player of the Music {self.midFileName}" + + '",\n "type": "data",\n "version": [ 0, 0, 1 ],\n "uuid": "' + + str(uuid.uuid4()) + + '"\n }\n ]\n}' + ) else: with open( - f"{self.outputPath}/temp/manifest.json", "r", encoding="utf-8" + f"{self.outputPath}/temp/manifest.json", "r", encoding="utf-8" ) as manifest: data = json.loads(manifest.read()) data["header"][ @@ -1292,22 +1283,22 @@ class midiConvert: data["modules"][0]["description"] = "None" data["modules"][0]["uuid"] = str(uuid.uuid4()) manifest.close() - open(f"{self.outputPath}/temp/manifest.json", "w", - encoding="utf-8").write(json.dumps(data)) + open(f"{self.outputPath}/temp/manifest.json", "w", encoding="utf-8").write( + json.dumps(data) + ) # 将命令列表写入文件 index_file = open( - f"{self.outputPath}/temp/functions/index.mcfunction", - "w", - encoding="utf-8") + f"{self.outputPath}/temp/functions/index.mcfunction", "w", encoding="utf-8" + ) for track in cmdlist: index_file.write( "function mscplay/track" + str(cmdlist.index(track) + 1) + "\n" ) with open( - f"{self.outputPath}/temp/functions/mscplay/track{cmdlist.index(track) + 1}.mcfunction", - "w", - encoding="utf-8", + f"{self.outputPath}/temp/functions/mscplay/track{cmdlist.index(track) + 1}.mcfunction", + "w", + encoding="utf-8", ) as f: f.write("\n".join(track)) index_file.writelines( @@ -1334,20 +1325,18 @@ class midiConvert: if progressbar: if progressbar: with open( - f"{self.outputPath}/temp/functions/mscplay/progressShow.mcfunction", - "w", - encoding="utf-8", + f"{self.outputPath}/temp/functions/mscplay/progressShow.mcfunction", + "w", + encoding="utf-8", ) as f: f.writelines( - "\n".join( - self.__formProgressBar( - maxscore, - scoreboard_name))) + "\n".join(self.__formProgressBar(maxscore, scoreboard_name)) + ) else: with open( - f"{self.outputPath}/temp/functions/mscplay/progressShow.mcfunction", - "w", - encoding="utf-8", + f"{self.outputPath}/temp/functions/mscplay/progressShow.mcfunction", + "w", + encoding="utf-8", ) as f: f.writelines( "\n".join( @@ -1361,23 +1350,24 @@ class midiConvert: if os.path.exists(f"{self.outputPath}/{self.midFileName}.mcpack"): os.remove(f"{self.outputPath}/{self.midFileName}.mcpack") - makeZip(f"{self.outputPath}/temp/", - f"{self.outputPath}/{self.midFileName}.mcpack") + makeZip( + f"{self.outputPath}/temp/", f"{self.outputPath}/{self.midFileName}.mcpack" + ) shutil.rmtree(f"{self.outputPath}/temp/") return True, maxlen, maxscore def toBDXfile( - self, - method: int = 1, - volume: float = 1.0, - speed: float = 1.0, - progressbar: Union[bool, tuple] = False, - scoreboard_name: str = "mscplay", - isAutoReset: bool = False, - author: str = "Eilles", - max_height: int = 64, + self, + method: int = 1, + volume: float = 1.0, + speed: float = 1.0, + progressbar: Union[bool, tuple] = False, + scoreboard_name: str = "mscplay", + isAutoReset: bool = False, + author: str = "Eilles", + max_height: int = 64, ): """ 使用method指定的转换算法,将midi转换为BDX结构文件 @@ -1402,8 +1392,8 @@ class midiConvert: os.makedirs(self.outputPath) with open( - os.path.abspath(os.path.join(self.outputPath, f"{self.midFileName}.bdx")), - "w+", + os.path.abspath(os.path.join(self.outputPath, f"{self.midFileName}.bdx")), + "w+", ) as f: f.write("BD@") @@ -1429,7 +1419,8 @@ class midiConvert: ) cmdBytes, size, finalPos = toBDX_bytes( - [(i, 0) for i in commands], max_height - 1) + [(i, 0) for i in commands], max_height - 1 + ) # 此处是对于仅有 True 的参数和自定义参数的判断 if progressbar: pgbBytes, pgbSize, pgbNowPos = toBDX_bytes( @@ -1457,22 +1448,22 @@ class midiConvert: _bytes += cmdBytes with open( - os.path.abspath(os.path.join(self.outputPath, f"{self.midFileName}.bdx")), - "ab+", + os.path.abspath(os.path.join(self.outputPath, f"{self.midFileName}.bdx")), + "ab+", ) as f: f.write(brotli.compress(_bytes + b"XE")) return True, total_count, maxScore, size, finalPos def toBDXfile_withDelay( - self, - method: int = 1, - volume: float = 1.0, - speed: float = 1.0, - progressbar=False, - player: str = "@a", - author: str = "Eilles", - max_height: int = 64, + self, + method: int = 1, + volume: float = 1.0, + speed: float = 1.0, + progressbar=False, + player: str = "@a", + author: str = "Eilles", + max_height: int = 64, ): """ 使用method指定的转换算法,将midi转换为BDX结构文件 @@ -1499,8 +1490,8 @@ class midiConvert: os.makedirs(self.outputPath) with open( - os.path.abspath(os.path.join(self.outputPath, f"{self.midFileName}.bdx")), - "w+", + os.path.abspath(os.path.join(self.outputPath, f"{self.midFileName}.bdx")), + "w+", ) as f: f.write("BD@") @@ -1522,8 +1513,10 @@ class midiConvert: if progressbar: scb_name = self.midFileName[:5] + "Pgb" _bytes += formCMD_blk( - r"scoreboard objectives add {} dummy {}播放用".replace( - r"{}", scb_name), 1, customName="初始化进度条", ) + r"scoreboard objectives add {} dummy {}播放用".replace(r"{}", scb_name), + 1, + customName="初始化进度条", + ) _bytes += move(z, 2) _bytes += formCMD_blk( r"scoreboard players add {} {} 1".format(player, scb_name), @@ -1557,15 +1550,15 @@ class midiConvert: _bytes += cmdBytes with open( - os.path.abspath(os.path.join(self.outputPath, f"{self.midFileName}.bdx")), - "ab+", + os.path.abspath(os.path.join(self.outputPath, f"{self.midFileName}.bdx")), + "ab+", ) as f: f.write(brotli.compress(_bytes + b"XE")) return True, len(cmdlist), max_delay, size, finalPos def toDICT( - self, + self, ) -> dict: """ 使用金羿的转换思路,将midi转换为字典 @@ -1596,8 +1589,7 @@ class midiConvert: else: if msg.type == "program_change": - channels[msg.channel].append( - ("PgmC", msg.program, microseconds)) + channels[msg.channel].append(("PgmC", msg.program, microseconds)) elif msg.type == "note_on" and msg.velocity != 0: channels[msg.channel].append( @@ -1605,10 +1597,9 @@ class midiConvert: ) elif (msg.type == "note_on" and msg.velocity == 0) or ( - msg.type == "note_off" + msg.type == "note_off" ): - channels[msg.channel].append( - ("NoteE", msg.note, microseconds)) + channels[msg.channel].append(("NoteE", msg.note, microseconds)) """整合后的音乐通道格式 每个通道包括若干消息元素其中逃不过这三种: diff --git a/msctPkgver/utils.py b/msctPkgver/utils.py index 851649b..0995d06 100644 --- a/msctPkgver/utils.py +++ b/msctPkgver/utils.py @@ -16,7 +16,7 @@ z = "z" def move(axis: str, value: int): if value == 0: - return b'' + return b"" if abs(value) == 1: return key[axis][0 if value == -1 else 1] @@ -32,8 +32,7 @@ def move(axis: str, value: int): ] ) - return key[axis][pointer] + \ - value.to_bytes(2 ** (pointer - 2), 'big', signed=True) + return key[axis][pointer] + value.to_bytes(2 ** (pointer - 2), "big", signed=True) def makeZip(sourceDir, outFilename, compression=8, exceptFile=None): @@ -59,15 +58,15 @@ def makeZip(sourceDir, outFilename, compression=8, exceptFile=None): def formCMD_blk( - command: str, - particularValue: int, - impluse: int = 0, - condition: bool = False, - needRedstone: bool = True, - tickDelay: int = 0, - customName: str = "", - executeOnFirstTick: bool = False, - trackOutput: bool = True, + command: str, + particularValue: int, + impluse: int = 0, + condition: bool = False, + needRedstone: bool = True, + tickDelay: int = 0, + customName: str = "", + executeOnFirstTick: bool = False, + trackOutput: bool = True, ): """ 使用指定项目返回指定的指令方块放置指令项 @@ -113,8 +112,7 @@ def formCMD_blk( :return:str """ - block = b"\x24" + \ - particularValue.to_bytes(2, byteorder="big", signed=False) + block = b"\x24" + particularValue.to_bytes(2, byteorder="big", signed=False) for i in [ impluse.to_bytes(4, byteorder="big", signed=False), @@ -140,8 +138,8 @@ def __fillSquareSideLength(total: int, maxHeight: int): def toBDX_bytes( - commands: list, - max_height: int = 64, + commands: list, + max_height: int = 64, ): """ :param commands: 指令列表(指令, 延迟) @@ -150,7 +148,7 @@ def toBDX_bytes( """ _sideLength = __fillSquareSideLength(len(commands), max_height) - _bytes = b'' + _bytes = b"" y_forward = True z_forward = True @@ -191,8 +189,7 @@ def toBDX_bytes( now_y += 1 if y_forward else -1 - if ((now_y >= max_height) and y_forward) or ( - (now_y < 0) and (not y_forward)): + if ((now_y >= max_height) and y_forward) or ((now_y < 0) and (not y_forward)): now_y -= 1 if y_forward else -1 y_forward = not y_forward @@ -200,7 +197,8 @@ def toBDX_bytes( now_z += 1 if z_forward else -1 if ((now_z > _sideLength) and z_forward) or ( - (now_z < 0) and (not z_forward)): + (now_z < 0) and (not z_forward) + ): now_z -= 1 if z_forward else -1 z_forward = not z_forward _bytes += key[x][1] @@ -215,6 +213,10 @@ def toBDX_bytes( return ( _bytes, - [now_x + 1, max_height if now_x or now_z else now_y, _sideLength if now_x else now_z], + [ + now_x + 1, + max_height if now_x or now_z else now_y, + _sideLength if now_x else now_z, + ], [now_x, now_y, now_z], ) diff --git a/msctPkgver/utils_future.py b/msctPkgver/utils_future.py index b6eebad..61b7875 100644 --- a/msctPkgver/utils_future.py +++ b/msctPkgver/utils_future.py @@ -18,7 +18,7 @@ z = "z" def move(axis: str, value: int): if value == 0: - return b'' + return b"" if abs(value) == 1: return key[axis][0 if value == -1 else 1] @@ -34,8 +34,7 @@ def move(axis: str, value: int): ] ) - return key[axis][pointer] + \ - value.to_bytes(2 ** (pointer - 2), 'big', signed=True) + return key[axis][pointer] + value.to_bytes(2 ** (pointer - 2), "big", signed=True) def makeZip(sourceDir, outFilename, compression=8, exceptFile=None): @@ -61,15 +60,15 @@ def makeZip(sourceDir, outFilename, compression=8, exceptFile=None): def formCMD_blk( - command: str, - particularValue: int, - impluse: int = 0, - condition: bool = False, - needRedstone: bool = True, - tickDelay: int = 0, - customName: str = "", - executeOnFirstTick: bool = False, - trackOutput: bool = True, + command: str, + particularValue: int, + impluse: int = 0, + condition: bool = False, + needRedstone: bool = True, + tickDelay: int = 0, + customName: str = "", + executeOnFirstTick: bool = False, + trackOutput: bool = True, ): """ 使用指定项目返回指定的指令方块放置指令项 @@ -115,8 +114,7 @@ def formCMD_blk( :return:str """ - block = b"\x24" + \ - particularValue.to_bytes(2, byteorder="big", signed=False) + block = b"\x24" + particularValue.to_bytes(2, byteorder="big", signed=False) for i in [ impluse.to_bytes(4, byteorder="big", signed=False), @@ -158,11 +156,11 @@ axisParticularValue = { def toLineBDX_bytes( - commands: list, - axis: str, - forward: bool, + commands: list, + axis: str, + forward: bool, ): - _bytes = b'' + _bytes = b"" impluse = 2 needRedstone = False customName = "" @@ -183,8 +181,8 @@ def toLineBDX_bytes( def toBDX_bytes( - commands: list, - max_height: int = 64, + commands: list, + max_height: int = 64, ): """ :param commands: 指令列表(指令, 条件) @@ -193,7 +191,7 @@ def toBDX_bytes( """ _sideLength = __fillSquareSideLength(len(commands), max_height) - _bytes = b'' + _bytes = b"" y_forward = True z_forward = True @@ -234,8 +232,7 @@ def toBDX_bytes( now_y += 1 if y_forward else -1 - if ((now_y >= max_height) and y_forward) or ( - (now_y < 0) and (not y_forward)): + if ((now_y >= max_height) and y_forward) or ((now_y < 0) and (not y_forward)): now_y -= 1 if y_forward else -1 y_forward = not y_forward @@ -243,7 +240,8 @@ def toBDX_bytes( now_z += 1 if z_forward else -1 if ((now_z > _sideLength) and z_forward) or ( - (now_z < 0) and (not z_forward)): + (now_z < 0) and (not z_forward) + ): now_z -= 1 if z_forward else -1 z_forward = not z_forward _bytes += key[x][1] @@ -258,16 +256,20 @@ def toBDX_bytes( return ( _bytes, - [now_x + 1, max_height if now_x or now_z else now_y, _sideLength if now_x else now_z], + [ + now_x + 1, + max_height if now_x or now_z else now_y, + _sideLength if now_x else now_z, + ], [now_x, now_y, now_z], ) def toBDXfile( - funcList: list, - author: str = "Eilles", - max_height: int = 64, - outfile: str = "./test.bdx", + funcList: list, + author: str = "Eilles", + max_height: int = 64, + outfile: str = "./test.bdx", ): """ :param funcList: 指令集列表: 指令系统[ 指令集[ 单个指令( str指令, bool条件性 ), ], ] @@ -281,7 +283,7 @@ def toBDXfile( f.write("BD@") _bytes = ( - b"BDX\x00" + author.encode("utf-8") + b" & Musicreater\x00\x01command_block\x00" + b"BDX\x00" + author.encode("utf-8") + b" & Musicreater\x00\x01command_block\x00" ) totalSize = {x: 0, y: 0, z: 0} totalLen = 0 @@ -297,8 +299,8 @@ def toBDXfile( totalSize[z] = max(totalSize[z], size[2]) with open( - os.path.abspath(outfile), - "ab+", + os.path.abspath(outfile), + "ab+", ) as f: f.write(brotli.compress(_bytes + b"XE")) @@ -306,11 +308,11 @@ def toBDXfile( def toLineBDXfile( - funcList: list, - axis_: str, - forward_: bool, - author: str = "Eilles", - outfile: str = "./test.bdx", + funcList: list, + axis_: str, + forward_: bool, + author: str = "Eilles", + outfile: str = "./test.bdx", ): """ :param funcList: 指令集列表: 指令系统[ 指令集[ 单个指令( str指令, bool条件性 ), ], ] @@ -325,7 +327,7 @@ def toLineBDXfile( f.write("BD@") _bytes = ( - b"BDX\x00" + author.encode("utf-8") + b" & Musicreater\x00\x01command_block\x00" + b"BDX\x00" + author.encode("utf-8") + b" & Musicreater\x00\x01command_block\x00" ) totalSize = {x: 0, y: 0, z: 0} totalLen = 0 @@ -338,8 +340,8 @@ def toLineBDXfile( totalSize[axis_] = max(totalSize[axis_], len(func)) with open( - os.path.abspath(outfile), - "ab+", + os.path.abspath(outfile), + "ab+", ) as f: f.write(brotli.compress(_bytes + b"XE")) diff --git a/requirements.txt b/requirements.txt index 24259ee..0920e16 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,5 @@ Brotli==1.0.9 mido==1.2.10 rich==13.2.0 +zhdate==0.1 +requests==2.27.1 \ No newline at end of file