update 2023/1/27 formatting and fixing bugs

This commit is contained in:
bgArray
2023-01-27 23:25:28 +08:00
parent 352807cba0
commit 49c4cfcbe2
11 changed files with 719 additions and 646 deletions

View File

@ -6,13 +6,13 @@ from msctPkgver.main import *
convertion = midiConvert() convertion = midiConvert()
convertion.convert(input("请输入midi文件路径"), input("请输入输出路径:")) convertion.convert(input("请输入midi文件路径"), input("请输入输出路径:"))
print( print(
convertion.tomcpack( convertion.to_mcpack(
3, 3,
bool(int(input("是否自动重置计分板(1|0)"))), bool(int(input("是否自动重置计分板(1|0)"))),
bool(int(input("是否开启进度条(1|0)"))), bool(int(input("是否开启进度条(1|0)"))),
input("请输入计分板名称:"), input("请输入计分板名称:"),
float(input("请输入音量0-1")), str(input("请输入音量0-1")),
float(input("请输入速度倍率:")), bool(input("请输入速度倍率:")),
) )
) )

View File

@ -17,6 +17,10 @@ Copyright 2023 all the developers of Musicreater
Terms & Conditions: ./Lisence.md Terms & Conditions: ./Lisence.md
""" """
import datetime
import random
import os
import sys
languages = { languages = {
"ZH_CN": { "ZH_CN": {
"MSCT": "音·创", "MSCT": "音·创",
@ -61,11 +65,9 @@ languages = {
} }
import sys
if sys.argv.__len__() > 0: if sys.argv.__len__() > 0:
currentLang = sys.argv[0] currentLang = sys.argv[0]
if not currentLang in languages.keys(): if currentLang not in languages.keys():
currentLang = "ZH_CN" currentLang = "ZH_CN"
else: else:
currentLang = "ZH_CN" currentLang = "ZH_CN"
@ -78,10 +80,6 @@ def _(__):
return languages[currentLang][__] return languages[currentLang][__]
import os
import random
import datetime
try: try:
import msctPkgver import msctPkgver
except ModuleNotFoundError as E: except ModuleNotFoundError as E:
@ -97,7 +95,7 @@ try:
# import zhdate # import zhdate
except ModuleNotFoundError as E: except ModuleNotFoundError as E:
if input( if input(
"您需要安装以下模块才能使用这个样例\nrequests==2.28.1\nrich==12.6.0\nzhdate==0.1\n请问是否安装?(y/n)" "您需要安装以下模块才能使用这个样例\nrequests==2.28.1\nrich==12.6.0\nzhdate==0.1\n请问是否安装?(y/n)"
).lower() in ('y', '1'): ).lower() in ('y', '1'):
open("Demo_Requirements.txt", 'w').write( open("Demo_Requirements.txt", 'w').write(
"requests==2.28.1\nrich==12.6.0\nzhdate==0.1" "requests==2.28.1\nrich==12.6.0\nzhdate==0.1"
@ -110,37 +108,31 @@ except ModuleNotFoundError as E:
else: else:
raise E raise E
MainConsole.print( MainConsole.print(
"[#121110 on #F0F2F4] ", "[#121110 on #F0F2F4] ",
style="#121110 on #F0F2F4", style="#121110 on #F0F2F4",
justify="center", justify="center",
) )
# 显示大标题 # 显示大标题
MainConsole.rule(title="[bold #AB70FF]欢迎使用音·创独立转换器", characters="=", style="#26E2FF")
MainConsole.rule( MainConsole.rule(
title="[bold #AB70FF]Welcome to Independent Musicreater Convernter", characters="-" title="[bold #AB70FF]欢迎使用音·创独立转换器",
) characters="=",
style="#26E2FF")
MainConsole.rule(
title="[bold #AB70FF]Welcome to Independent Musicreater Convernter",
characters="-")
nowYang = datetime.datetime.now() nowYang = datetime.datetime.now()
if nowYang.month == 8 and nowYang.day == 6: if nowYang.month == 8 and nowYang.day == 6:
# 诸葛八卦生日 # 诸葛八卦生日
MainConsole.print( MainConsole.print("[#7DB5F0 on #121110]今天可不是催更的日子!\n诸葛亮与八卦阵{}岁生日快乐!".format(
"[#7DB5F0 on #121110]今天可不是催更的日子!\n诸葛亮与八卦阵{}岁生日快乐!".format(nowYang.year - 2009), nowYang.year - 2009), style="#7DB5F0 on #121110", justify="center", )
style="#7DB5F0 on #121110",
justify="center",
)
elif nowYang.month == 4 and nowYang.day == 3: elif nowYang.month == 4 and nowYang.day == 3:
# 金羿生日快乐 # 金羿生日快乐
MainConsole.print( MainConsole.print("[#0089F2 on #F0F2F4]今天就不要催更啦!\n金羿{}岁生日快乐!".format(
"[#0089F2 on #F0F2F4]今天就不要催更啦!\n金羿{}岁生日快乐!".format(nowYang.year - 2006), nowYang.year - 2006), style="#0089F2 on #F0F2F4", justify="center", )
style="#0089F2 on #F0F2F4",
justify="center",
)
else: else:
# 显示箴言部分 # 显示箴言部分
MainConsole.print( MainConsole.print(
@ -159,11 +151,12 @@ else:
prt(f"{_('LangChd')}{_(':')}{_(currentLang)}") prt(f"{_('LangChd')}{_(':')}{_(currentLang)}")
def formatipt( def formatipt(
notice: str, notice: str,
fun, fun,
errnote: str = f"{_('ErrEnter')}{_(',')}{_('Re-Enter')}{_('.')}", errnote: str = f"{_('ErrEnter')}{_(',')}{_('Re-Enter')}{_('.')}",
*extraArg, *extraArg,
): ):
'''循环输入,以某种格式 '''循环输入,以某种格式
notice: 输入时的提示 notice: 输入时的提示
@ -175,11 +168,11 @@ def formatipt(
try: try:
funresult = fun(result, *extraArg) funresult = fun(result, *extraArg)
break break
except: except BaseException:
prt(errnote) prt(errnote)
continue continue
return result, funresult return result, funresult
# 获取midi列表 # 获取midi列表
while True: while True:
@ -210,7 +203,6 @@ outpath = formatipt(
f"{_('FileNotFound')}{_(',')}{_('Re-Enter')}{_('.')}", f"{_('FileNotFound')}{_(',')}{_('Re-Enter')}{_('.')}",
)[0].lower() )[0].lower()
# 选择输出格式 # 选择输出格式
while True: while True:
fileFormat = ipt(f"{_('ChooseFileFormat')}{_(':')}").lower() fileFormat = ipt(f"{_('ChooseFileFormat')}{_(':')}").lower()
@ -237,11 +229,13 @@ while True:
break break
debug = False debug = False
# 真假字符串判断 # 真假字符串判断
def boolstr(sth: str) -> bool: def boolstr(sth: str) -> bool:
try: try:
return bool(int(sth)) return bool(int(sth))
except: except BaseException:
if str(sth).lower() == 'true': if str(sth).lower() == 'true':
return True return True
elif str(sth).lower() == 'false': elif str(sth).lower() == 'false':
@ -249,9 +243,11 @@ def boolstr(sth: str) -> bool:
else: else:
raise "布尔字符串啊?" raise "布尔字符串啊?"
if os.path.exists("./demo_config.json"): if os.path.exists("./demo_config.json"):
import 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": if prompts[-1] == "debug":
debug = True debug = True
prompts = prompts[:-1] prompts = prompts[:-1]
@ -302,21 +298,16 @@ else:
if args: if args:
prompts.append(formatipt(*args)[1]) prompts.append(formatipt(*args)[1])
conversion = msctPkgver.midiConvert(debug) conversion = msctPkgver.midiConvert(debug)
for singleMidi in midis: for singleMidi in midis:
prt("\n"f"{_('Dealing')} {singleMidi} {_(':')}") prt("\n"f"{_('Dealing')} {singleMidi} {_(':')}")
conversion.convert(singleMidi, outpath) conversion.convert(singleMidi, outpath)
if debug: 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) json.dump(conversion.toDICT(), f)
f.write(5*"\n") f.write(5 * "\n")
conversion_result = ( conversion_result = (
conversion.tomcpack(2, *prompts) conversion.to_mcpack(2, *prompts)
if fileFormat == 0 if fileFormat == 0
else ( else (
conversion.toBDXfile(2, *prompts) conversion.toBDXfile(2, *prompts)
@ -324,7 +315,7 @@ for singleMidi in midis:
else conversion.toBDXfile_withDelay(2, *prompts) else conversion.toBDXfile_withDelay(2, *prompts)
) )
) )
if conversion_result[0]: if conversion_result[0]:
prt( 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')}{_(':')}{conversion_result[2]}{f'''{_(',')}{_('PlaceSize')}{_(':')}{conversion_result[3]}{_(',')}{_('LastPos')}{_(':')}{conversion_result[4]}''' if fileFormat == 1 else ''}"
@ -332,11 +323,11 @@ for singleMidi in midis:
else: else:
prt(f"{_('Failed')}") prt(f"{_('Failed')}")
exitSth = ipt(_("PressEnterExit")).lower() exitSth = ipt(_("PressEnterExit")).lower()
if exitSth == "record": if exitSth == "record":
import json import json
with open("./demo_config.json",'w',encoding="utf-8") as f:
json.dump(prompts,f) with open("./demo_config.json", 'w', encoding="utf-8") as f:
json.dump(prompts, f)
elif exitSth == "delrec": elif exitSth == "delrec":
os.remove("./demo_config.json") os.remove("./demo_config.json")

View File

@ -1,17 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""一个简单的我的世界音频转换库""" """一个简单的我的世界音频转换库
# 音·创 开发交流群 861684859
# Email EillesWan2006@163.com W-YI_DoctorYI@outlook.com EillesWan@outlook.com
# 版权所有 金羿("Eilles Wan") & 诸葛亮与八卦阵("bgArray") & 鸣凤鸽子("MingFengPigeon")
# 若需转载或借鉴 许可声明请查看仓库目录下的 Lisence.md
__version__ = '0.2.2.1'
__all__ = []
__author__ = (('金羿', 'Eilles Wan'), ('诸葛亮与八卦阵', 'bgArray'), ('鸣凤鸽子', 'MingFengPigeon'))
"""
音·创 库版 (Musicreater Package Version) 音·创 库版 (Musicreater Package Version)
是一款免费开源的针对《我的世界基岩版》的midi音乐转换库 是一款免费开源的针对《我的世界基岩版》的midi音乐转换库
Musicreater pkgver (Package Version 音·创 库版) Musicreater pkgver (Package Version 音·创 库版)
@ -19,16 +7,22 @@ A free open source library used for convert midi file into formats that is suita
Copyright 2023 all the developers of Musicreater Copyright 2023 all the developers of Musicreater
开源相关声明请见 ../Lisence.md 开源相关声明请见 ../License.md
Terms & Conditions: ../Lisence.md Terms & Conditions: ../License.md
""" """
# 音·创 开发交流群 861684859
# Email EillesWan2006@163.com W-YI_DoctorYI@outlook.com EillesWan@outlook.com
# 版权所有 金羿("Eilles Wan") & 诸葛亮与八卦阵("bgArray") & 鸣凤鸽子("MingFengPigeon")
# 若需转载或借鉴 许可声明请查看仓库目录下的 License.md
from .main import * from .main import *
__version__ = '0.2.2.1'
__all__ = []
__author__ = (('金羿', 'Eilles Wan'), ('诸葛亮与八卦阵', 'bgArray'), ('鸣凤鸽子', 'MingFengPigeon'))
print('此Midi转换功能由音·创开发者开发版权归参与开发的人员共同所有。') print('此Midi转换功能由音·创开发者开发版权归参与开发的人员共同所有。')
print('Copyright © 2022 all the developers of Musicreater') print('Copyright © 2022 all the developers of Musicreater')
print("小贴不妨试试Mid-BDX转换网页在线的多功能Midi转换器") print("小贴不妨试试Mid-BDX转换网页在线的多功能Midi转换器")
print("https://dislink.github.io/midi2bdx/") print("https://dislink.github.io/midi2bdx/")

View File

@ -1,4 +1,3 @@
import brotli import brotli
input(brotli.decompress(open(input("BDX文件"),'rb').read()[3:])) input(brotli.decompress(open(input("BDX文件"), 'rb').read()[3:]))

View File

@ -4,7 +4,7 @@
# 音·创 开发交流群 861684859 # 音·创 开发交流群 861684859
# Email EillesWan2006@163.com W-YI_DoctorYI@outlook.com EillesWan@outlook.com # Email EillesWan2006@163.com W-YI_DoctorYI@outlook.com EillesWan@outlook.com
# 版权所有 金羿("Eilles Wan") & 诸葛亮与八卦阵("bgArray") & 鸣凤鸽子("MingFengPigeon") # 版权所有 金羿("Eilles Wan") & 诸葛亮与八卦阵("bgArray") & 鸣凤鸽子("MingFengPigeon")
# 若需转载或借鉴 许可声明请查看仓库目录下的 Lisence.md # 若需转载或借鉴 许可声明请查看仓库目录下的 License.md
""" """
@ -16,46 +16,50 @@ A free open source library used for convert midi file into formats that is suita
版权所有 © 2023 音·创 开发者 版权所有 © 2023 音·创 开发者
Copyright © 2023 all the developers of Musicreater Copyright © 2023 all the developers of Musicreater
开源相关声明请见 ../Lisence.md 开源相关声明请见 ../License.md
Terms & Conditions: ../Lisence.md Terms & Conditions: ../License.md
""" """
class MSCTBaseException(Exception): class MSCTBaseException(Exception):
"""音·创库版本的所有错误均继承于此""" """音·创库版本的所有错误均继承于此"""
def __init__(self, *args): def __init__(self, *args):
super().__init__(*args) super().__init__(*args)
def (self,): def miao(self, ):
for i in self.args: for i in self.args:
print(i+"喵!") print(i + "喵!")
def crash_it(self): def crash_it(self):
raise self raise self
class CrossNoteError(MSCTBaseException): class CrossNoteError(MSCTBaseException):
'''同通道下同音符交叉出现所产生的错误''' """同通道下同音符交叉出现所产生的错误"""
pass pass
class NotDefineTempoError(MSCTBaseException): class NotDefineTempoError(MSCTBaseException):
'''没有Tempo设定导致时间无法计算的错误''' """没有Tempo设定导致时间无法计算的错误"""
pass pass
class MidiDestroyedError(MSCTBaseException): class MidiDestroyedError(MSCTBaseException):
'''Midi文件损坏''' """Midi文件损坏"""
pass pass
class ChannelOverFlowError(MSCTBaseException): class ChannelOverFlowError(MSCTBaseException):
'''一个midi中含有过多的通道数量应≤16''' """一个midi中含有过多的通道数量应≤16"""
pass pass
class NotDefineProgramError(MSCTBaseException): class NotDefineProgramError(MSCTBaseException):
'''没有Program设定导致没有乐器可以选择的错误''' """没有Program设定导致没有乐器可以选择的错误"""
pass pass
class BaseError(BaseException):
"""专门骗过PEP8的错误"""
pass

View File

@ -1,30 +1,29 @@
from rich.console import Console from rich.console import Console
from exceptions import *
from typing import Any, Literal, Optional, TextIO
MainConsole = Console() MainConsole = Console()
from typing import Any, Literal, Optional, TextIO
JustifyMethod = Literal["default", "left", "center", "right", "full"] JustifyMethod = Literal["default", "left", "center", "right", "full"]
OverflowMethod = Literal["fold", "crop", "ellipsis", "ignore"] OverflowMethod = Literal["fold", "crop", "ellipsis", "ignore"]
# 高级的打印函数 # 高级的打印函数
def prt( def prt(
*objects: Any, *objects: Any,
sep: str = " ", sep: str = " ",
end: str = "\n", end: str = "\n",
justify: Optional[JustifyMethod] = None, justify: Optional[JustifyMethod] = None,
overflow: Optional[OverflowMethod] = None, overflow: Optional[OverflowMethod] = None,
no_wrap: Optional[bool] = None, no_wrap: Optional[bool] = None,
emoji: Optional[bool] = None, emoji: Optional[bool] = None,
markup: Optional[bool] = None, markup: Optional[bool] = None,
highlight: Optional[bool] = None, highlight: Optional[bool] = None,
width: Optional[int] = None, width: Optional[int] = None,
height: Optional[int] = None, height: Optional[int] = None,
crop: bool = True, crop: bool = True,
soft_wrap: Optional[bool] = None, soft_wrap: Optional[bool] = None,
new_line_start: bool = False, new_line_start: bool = False,
) -> None: ) -> None:
"""打印到控制台。 """打印到控制台。
@ -32,7 +31,6 @@ def prt(
objects (位置性的args): 要记录到终端的对象。 objects (位置性的args): 要记录到终端的对象。
sep (str, 可选): 要在打印数据之间写入的字符串。默认为"" sep (str, 可选): 要在打印数据之间写入的字符串。默认为""
end (str, optio可选nal): 在打印数据结束时写入的字符串。默认值为"\\\\n" end (str, optio可选nal): 在打印数据结束时写入的字符串。默认值为"\\\\n"
style (Union[str, Style], 可选): 应用于输出的样式。默认为`None`。
justify (str, 可选): 校正位置,可为"default", "left", "right", "center""full". 默认为`None`。 justify (str, 可选): 校正位置,可为"default", "left", "right", "center""full". 默认为`None`。
overflow (str, 可选): 控制溢出:"ignore"忽略, "crop"裁剪, "fold"折叠, "ellipsis"省略号。默认为`None`。 overflow (str, 可选): 控制溢出:"ignore"忽略, "crop"裁剪, "fold"折叠, "ellipsis"省略号。默认为`None`。
no_wrap (Optional[bool], 可选): 禁用文字包装。默认为`None`。 no_wrap (Optional[bool], 可选): 禁用文字包装。默认为`None`。
@ -40,6 +38,7 @@ def prt(
markup (Optional[bool], 可选): 启用标记,或`None`使用控制台默认值。默认为`None`。 markup (Optional[bool], 可选): 启用标记,或`None`使用控制台默认值。默认为`None`。
highlight (Optional[bool], 可选): 启用自动高亮,或`None`使用控制台默认值。默认为`None`。 highlight (Optional[bool], 可选): 启用自动高亮,或`None`使用控制台默认值。默认为`None`。
width (Optional[int], 可选): 输出的宽度,或`None`自动检测。默认为`None`。 width (Optional[int], 可选): 输出的宽度,或`None`自动检测。默认为`None`。
height
crop (Optional[bool], 可选): 裁剪输出到终端的宽度。默认为`True`。 crop (Optional[bool], 可选): 裁剪输出到终端的宽度。默认为`True`。
soft_wrap (bool, 可选): 启用软包装模式,禁止文字包装和裁剪,或`None``用于 控制台默认值。默认为`None`。 soft_wrap (bool, 可选): 启用软包装模式,禁止文字包装和裁剪,或`None``用于 控制台默认值。默认为`None`。
new_line_start (bool, False): 如果输出包含多行,在开始时插入一个新行。默认值为`False`。 new_line_start (bool, False): 如果输出包含多行,在开始时插入一个新行。默认值为`False`。
@ -63,24 +62,23 @@ def prt(
) )
# 高级的输入函数 # 高级的输入函数
def ipt( def ipt(
*objects: Any, *objects: Any,
sep: str = " ", sep: str = " ",
justify: Optional[JustifyMethod] = None, justify: Optional[JustifyMethod] = None,
overflow: Optional[OverflowMethod] = None, overflow: Optional[OverflowMethod] = None,
no_wrap: Optional[bool] = None, no_wrap: Optional[bool] = None,
emoji: Optional[bool] = None, emoji: Optional[bool] = None,
markup: Optional[bool] = None, markup: Optional[bool] = None,
highlight: Optional[bool] = None, highlight: Optional[bool] = None,
width: Optional[int] = None, width: Optional[int] = None,
height: Optional[int] = None, height: Optional[int] = None,
crop: bool = True, crop: bool = True,
soft_wrap: Optional[bool] = None, soft_wrap: Optional[bool] = None,
new_line_start: bool = False, new_line_start: bool = False,
password: bool = False, password: bool = False,
stream: Optional[TextIO] = None, stream: Optional[TextIO] = None,
) -> str: ) -> str:
"""显示一个提示并等待用户的输入。 """显示一个提示并等待用户的输入。
@ -89,8 +87,6 @@ def ipt(
Args: Args:
objects (位置性的args): 要记录到终端的对象。 objects (位置性的args): 要记录到终端的对象。
sep (str, 可选): 要在打印数据之间写入的字符串。默认为"" sep (str, 可选): 要在打印数据之间写入的字符串。默认为""
end (str, optio可选nal): 在打印数据结束时写入的字符串。默认值为"\\\\n"
style (Union[str, Style], 可选): 应用于输出的样式。默认为`None`。
justify (str, 可选): 校正位置,可为"default", "left", "right", "center""full". 默认为`None`。 justify (str, 可选): 校正位置,可为"default", "left", "right", "center""full". 默认为`None`。
overflow (str, 可选): 控制溢出:"ignore"忽略, "crop"裁剪, "fold"折叠, "ellipsis"省略号。默认为`None`。 overflow (str, 可选): 控制溢出:"ignore"忽略, "crop"裁剪, "fold"折叠, "ellipsis"省略号。默认为`None`。
no_wrap (Optional[bool], 可选): 禁用文字包装。默认为`None`。 no_wrap (Optional[bool], 可选): 禁用文字包装。默认为`None`。
@ -99,6 +95,7 @@ def ipt(
highlight (Optional[bool], 可选): 启用自动高亮,或`None`使用控制台默认值。默认为`None`。 highlight (Optional[bool], 可选): 启用自动高亮,或`None`使用控制台默认值。默认为`None`。
width (Optional[int], 可选): 输出的宽度,或`None`自动检测。默认为`None`。 width (Optional[int], 可选): 输出的宽度,或`None`自动检测。默认为`None`。
crop (Optional[bool], 可选): 裁剪输出到终端的宽度。默认为`True`。 crop (Optional[bool], 可选): 裁剪输出到终端的宽度。默认为`True`。
height
soft_wrap (bool, 可选): 启用软包装模式,禁止文字包装和裁剪,或`None``用于 控制台默认值。默认为`None`。 soft_wrap (bool, 可选): 启用软包装模式,禁止文字包装和裁剪,或`None``用于 控制台默认值。默认为`None`。
new_line_start (bool, False): 如果输出包含多行,在开始时插入一个新行。默认值为`False`。 new_line_start (bool, False): 如果输出包含多行,在开始时插入一个新行。默认值为`False`。
password (bool, 可选): 隐藏已经输入的文案,默认值为`False`。 password (bool, 可选): 隐藏已经输入的文案,默认值为`False`。
@ -125,26 +122,26 @@ def ipt(
new_line_start=new_line_start, new_line_start=new_line_start,
) )
return MainConsole.input("", password=password, stream=stream) return MainConsole.input(password=password, stream=stream)
def formatipt( def format_ipt(
notice: str, notice: str,
fun, fun,
errnote: str = "", err_note: str = "",
*extraArg, *extraArg,
): ):
'''循环输入,以某种格式 """循环输入,以某种格式
notice: 输入时的提示 notice: 输入时的提示
fun: 格式函数 fun: 格式函数
errnote: 输入不符格式时的提示 err_note: 输入不符格式时的提示
*extraArg: 对于函数的其他参数''' *extraArg: 对于函数的其他参数"""
while True: while True:
result = ipt(notice) result = ipt(notice)
try: try:
funresult = fun(result, *extraArg) fun_result = fun(result, *extraArg)
break break
except: except BaseError:
prt(errnote) prt(err_note)
continue continue
return result, funresult return result, fun_result

View File

@ -73,7 +73,7 @@ def _toCmdList_m1(
/ ((self.midi.ticks_per_beat * float(speed)) * 50000) / ((self.midi.ticks_per_beat * float(speed)) * 50000)
) )
maxscore = max(maxscore, nowscore) maxscore = max(maxscore, nowscore)
soundID, _X = self.__Inst2soundIDwithX(instrumentID) soundID, _X = self.__Inst2soundID_withX(instrumentID)
singleTrack.append( singleTrack.append(
"execute @a[scores={" + "execute @a[scores={" +
str(scoreboardname) + str(scoreboardname) +

File diff suppressed because it is too large Load Diff

View File

@ -32,7 +32,8 @@ 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): def makeZip(sourceDir, outFilename, compression=8, exceptFile=None):
@ -52,21 +53,21 @@ def makeZip(sourceDir, outFilename, compression=8, exceptFile=None):
if filename == exceptFile: if filename == exceptFile:
continue continue
pathfile = os.path.join(parent, filename) pathfile = os.path.join(parent, filename)
arcname = pathfile[pre_len:].strip(os.path.sep) # 相对路径 arc_name = pathfile[pre_len:].strip(os.path.sep) # 相对路径
zipf.write(pathfile, arcname) zipf.write(pathfile, arc_name)
zipf.close() zipf.close()
def formCMDblk( def formCMD_blk(
command: str, command: str,
particularValue: int, particularValue: int,
impluse: int = 0, impluse: int = 0,
condition: bool = False, condition: bool = False,
needRedstone: bool = True, needRedstone: bool = True,
tickDelay: int = 0, tickDelay: int = 0,
customName: str = "", customName: str = "",
executeOnFirstTick: bool = False, executeOnFirstTick: bool = False,
trackOutput: bool = True, trackOutput: bool = True,
): ):
""" """
使用指定项目返回指定的指令方块放置指令项 使用指定项目返回指定的指令方块放置指令项
@ -112,7 +113,8 @@ def formCMDblk(
:return:str :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 [ for i in [
impluse.to_bytes(4, byteorder="big", signed=False), impluse.to_bytes(4, byteorder="big", signed=False),
@ -137,73 +139,82 @@ def __fillSquareSideLength(total: int, maxHeight: int):
return math.ceil(math.sqrt(math.ceil(total / maxHeight))) return math.ceil(math.sqrt(math.ceil(total / maxHeight)))
def toBDXbytes( def toBDX_bytes(
commands: list, commands: list,
maxheight: int = 64, max_height: int = 64,
): ):
""" """
:param commands: 指令列表(指令, 延迟) :param commands: 指令列表(指令, 延迟)
:param maxheight: 生成结构最大高度 :param max_height: 生成结构最大高度
:return 成功与否,成功返回(True,未经过压缩的源,结构占用大小),失败返回(False,str失败原因) :return 成功与否,成功返回(True,未经过压缩的源,结构占用大小),失败返回(False,str失败原因)
""" """
_sideLength = __fillSquareSideLength(len(commands), maxheight) _sideLength = __fillSquareSideLength(len(commands), max_height)
_bytes = b'' _bytes = b''
yforward = True y_forward = True
zforward = True z_forward = True
nowy = 0 now_y = 0
nowz = 0 now_z = 0
nowx = 0 now_x = 0
for cmd, delay in commands: for cmd, delay in commands:
_bytes += formCMDblk( impluse = 2
condition = False
needRedstone = False
tickDelay = delay
customName = ""
executeOnFirstTick = False
trackOutput = True
_bytes += formCMD_blk(
cmd, cmd,
(1 if yforward else 0) (1 if y_forward else 0)
if ( if (
((nowy != 0) and (not yforward)) ((now_y != 0) and (not y_forward))
or ((yforward) and (nowy != (maxheight - 1))) or (y_forward and (now_y != (max_height - 1)))
) )
else (3 if zforward else 2) else (3 if z_forward else 2)
if ( if (
((nowz != 0) and (not zforward)) ((now_z != 0) and (not z_forward))
or ((zforward) and (nowz != _sideLength)) or (z_forward and (now_z != _sideLength))
) )
else 5, else 5,
impluse=2, impluse=impluse,
condition=False, condition=condition,
needRedstone=False, needRedstone=needRedstone,
tickDelay=delay, tickDelay=tickDelay,
customName="", customName=customName,
executeOnFirstTick=False, executeOnFirstTick=executeOnFirstTick,
trackOutput=True, trackOutput=trackOutput,
) )
nowy += 1 if yforward else -1 now_y += 1 if y_forward else -1
if ((nowy >= maxheight) and (yforward)) or ((nowy < 0) and (not yforward)): if ((now_y >= max_height) and y_forward) or (
nowy -= 1 if yforward else -1 (now_y < 0) and (not y_forward)):
now_y -= 1 if y_forward else -1
yforward = not yforward y_forward = not y_forward
nowz += 1 if zforward else -1 now_z += 1 if z_forward else -1
if ((nowz > _sideLength) and (zforward)) or ((nowz < 0) and (not zforward)): if ((now_z > _sideLength) and z_forward) or (
nowz -= 1 if zforward else -1 (now_z < 0) and (not z_forward)):
zforward = not zforward now_z -= 1 if z_forward else -1
z_forward = not z_forward
_bytes += key[x][1] _bytes += key[x][1]
nowx += 1 now_x += 1
else: else:
_bytes += key[z][int(zforward)] _bytes += key[z][int(z_forward)]
else: else:
_bytes += key[y][int(yforward)] _bytes += key[y][int(y_forward)]
return ( return (
_bytes, _bytes,
[nowx + 1, maxheight if nowx or nowz else nowy, _sideLength if nowx else nowz], [now_x + 1, max_height if now_x or now_z else now_y, _sideLength if now_x else now_z],
[nowx, nowy, nowz], [now_x, now_y, now_z],
) )

View File

@ -1,6 +1,7 @@
import math import math
import os import os
import brotli import brotli
from exceptions import *
key = { key = {
"x": [b"\x0f", b"\x0e", b"\x1c", b"\x14", b"\x15"], "x": [b"\x0f", b"\x0e", b"\x1c", b"\x14", b"\x15"],
@ -33,7 +34,8 @@ 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): def makeZip(sourceDir, outFilename, compression=8, exceptFile=None):
@ -53,21 +55,21 @@ def makeZip(sourceDir, outFilename, compression=8, exceptFile=None):
if filename == exceptFile: if filename == exceptFile:
continue continue
pathfile = os.path.join(parent, filename) pathfile = os.path.join(parent, filename)
arcname = pathfile[pre_len:].strip(os.path.sep) # 相对路径 arc_name = pathfile[pre_len:].strip(os.path.sep) # 相对路径
zipf.write(pathfile, arcname) zipf.write(pathfile, arc_name)
zipf.close() zipf.close()
def formCMDblk( def formCMD_blk(
command: str, command: str,
particularValue: int, particularValue: int,
impluse: int = 0, impluse: int = 0,
condition: bool = False, condition: bool = False,
needRedstone: bool = True, needRedstone: bool = True,
tickDelay: int = 0, tickDelay: int = 0,
customName: str = "", customName: str = "",
executeOnFirstTick: bool = False, executeOnFirstTick: bool = False,
trackOutput: bool = True, trackOutput: bool = True,
): ):
""" """
使用指定项目返回指定的指令方块放置指令项 使用指定项目返回指定的指令方块放置指令项
@ -113,7 +115,8 @@ def formCMDblk(
:return:str :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 [ for i in [
impluse.to_bytes(4, byteorder="big", signed=False), impluse.to_bytes(4, byteorder="big", signed=False),
@ -130,12 +133,12 @@ def formCMDblk(
return block return block
def __fillSquareSideLength(total: int, maxHeight: int): def __fillSquareSideLength(total: int, max_height: int):
"""给定总方块数量和最大高度,返回所构成的图形外切正方形的边长 """给定总方块数量和最大高度,返回所构成的图形外切正方形的边长
:param total: 总方块数量 :param total: 总方块数量
:param maxHeight: 最大高度 :param max_height: 最大高度
:return: 外切正方形的边长 int""" :return: 外切正方形的边长 int"""
return math.ceil(math.sqrt(math.ceil(total / maxHeight))) return math.ceil(math.sqrt(math.ceil(total / max_height)))
axisParticularValue = { axisParticularValue = {
@ -154,112 +157,123 @@ axisParticularValue = {
} }
def toLineBDXbytes( def toLineBDX_bytes(
commands: list, commands: list,
axis: str, axis: str,
forward: bool, forward: bool,
): ):
_bytes = b'' _bytes = b''
impluse = 2
needRedstone = False
customName = ""
executeOnFirstTick = False
trackOutput = True
for cmd, condition in commands: for cmd, condition in commands:
_bytes += formCMDblk( _bytes += formCMD_blk(
cmd, cmd,
axisParticularValue[axis][forward], axisParticularValue[axis][forward],
impluse=2, impluse=impluse,
condition=condition, condition=condition,
needRedstone=False, needRedstone=needRedstone,
tickDelay=0, customName=customName,
customName="", executeOnFirstTick=executeOnFirstTick,
executeOnFirstTick=False, trackOutput=trackOutput,
trackOutput=True,
) + move(axis, 1 if forward else -1) ) + move(axis, 1 if forward else -1)
return _bytes return _bytes
def toBDXbytes( def toBDX_bytes(
commands: list, commands: list,
maxheight: int = 64, max_height: int = 64,
): ):
""" """
:param commands: 指令列表(指令, 条件) :param commands: 指令列表(指令, 条件)
:param maxheight: 生成结构最大高度 :param max_height: 生成结构最大高度
:return 成功与否,成功返回(True,未经过压缩的源,结构占用大小),失败返回(False,str失败原因) :return 成功与否,成功返回(True,未经过压缩的源,结构占用大小),失败返回(False,str失败原因)
""" """
_sideLength = __fillSquareSideLength(len(commands), maxheight) _sideLength = __fillSquareSideLength(len(commands), max_height)
_bytes = b'' _bytes = b''
yforward = True y_forward = True
zforward = True z_forward = True
nowy = 0 now_y = 0
nowz = 0 now_z = 0
nowx = 0 now_x = 0
for cmd, condition in commands: for cmd, delay in commands:
_bytes += formCMDblk( impluse = 2
condition = False
needRedstone = False
tickDelay = delay
customName = ""
executeOnFirstTick = False
trackOutput = True
_bytes += formCMD_blk(
cmd, cmd,
(1 if yforward else 0) (1 if y_forward else 0)
if ( if (
((nowy != 0) and (not yforward)) ((now_y != 0) and (not y_forward))
or ((yforward) and (nowy != (maxheight - 1))) or (y_forward and (now_y != (max_height - 1)))
) )
else (3 if zforward else 2) else (3 if z_forward else 2)
if ( if (
((nowz != 0) and (not zforward)) ((now_z != 0) and (not z_forward))
or ((zforward) and (nowz != _sideLength)) or (z_forward and (now_z != _sideLength))
) )
else 5, else 5,
impluse=2, impluse=impluse,
condition=condition, condition=condition,
needRedstone=False, needRedstone=needRedstone,
tickDelay=0, tickDelay=tickDelay,
customName="", customName=customName,
executeOnFirstTick=False, executeOnFirstTick=executeOnFirstTick,
trackOutput=True, trackOutput=trackOutput,
) )
nowy += 1 if yforward else -1 now_y += 1 if y_forward else -1
if ((nowy >= maxheight) and (yforward)) or ((nowy < 0) and (not yforward)): if ((now_y >= max_height) and y_forward) or (
nowy -= 1 if yforward else -1 (now_y < 0) and (not y_forward)):
now_y -= 1 if y_forward else -1
yforward = not yforward y_forward = not y_forward
nowz += 1 if zforward else -1 now_z += 1 if z_forward else -1
if ((nowz > _sideLength) and (zforward)) or ((nowz < 0) and (not zforward)): if ((now_z > _sideLength) and z_forward) or (
nowz -= 1 if zforward else -1 (now_z < 0) and (not z_forward)):
zforward = not zforward now_z -= 1 if z_forward else -1
z_forward = not z_forward
_bytes += key[x][1] _bytes += key[x][1]
nowx += 1 now_x += 1
else: else:
_bytes += key[z][int(zforward)] _bytes += key[z][int(z_forward)]
else: else:
_bytes += key[y][int(yforward)] _bytes += key[y][int(y_forward)]
return ( return (
_bytes, _bytes,
[nowx + 1, maxheight if nowx or nowz else nowy, _sideLength if nowx else nowz], [now_x + 1, max_height if now_x or now_z else now_y, _sideLength if now_x else now_z],
[nowx, nowy, nowz], [now_x, now_y, now_z],
) )
def toBDXfile( def toBDXfile(
funcList: list, funcList: list,
author: str = "Eilles", author: str = "Eilles",
maxheight: int = 64, max_height: int = 64,
outfile: str = "./test.bdx", outfile: str = "./test.bdx",
): ):
""" """
:funcList list: 指令集列表: 指令系统[ 指令集[ 单个指令( str指令, bool条件性 ), ], ] :param funcList: 指令集列表: 指令系统[ 指令集[ 单个指令( str指令, bool条件性 ), ], ]
:param author: 作者名称 :param author: 作者名称
:param maxheight: 生成结构最大高度 :param max_height: 生成结构最大高度
:outfile: str 输出文件 :param outfile: str 输出文件
:return 成功与否,指令总长度,指令总延迟,指令结构总大小,画笔最终坐标 :return 成功与否,指令总长度,指令总延迟,指令结构总大小,画笔最终坐标
""" """
@ -267,13 +281,13 @@ def toBDXfile(
f.write("BD@") f.write("BD@")
_bytes = ( _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} totalSize = {x: 0, y: 0, z: 0}
totalLen = 0 totalLen = 0
for func in funcList: for func in funcList:
totalLen += len(func) totalLen += len(func)
cmdBytes, size, finalPos = toBDXbytes(func, maxheight) cmdBytes, size, finalPos = toBDX_bytes(func, max_height)
_bytes += cmdBytes _bytes += cmdBytes
_bytes += move(x, 2) _bytes += move(x, 2)
_bytes += move(y, -finalPos[1]) _bytes += move(y, -finalPos[1])
@ -283,27 +297,27 @@ def toBDXfile(
totalSize[z] = max(totalSize[z], size[2]) totalSize[z] = max(totalSize[z], size[2])
with open( with open(
os.path.abspath(outfile), os.path.abspath(outfile),
"ab+", "ab+",
) as f: ) as f:
f.write(brotli.compress(_bytes + b"XE")) f.write(brotli.compress(_bytes + b"XE"))
return (True, totalLen, 0, list(totalSize.values()), finalPos) return True, totalLen, 0, list(totalSize.values()), finalPos
def toLineBDXfile( def toLineBDXfile(
funcList: list, funcList: list,
axis_: str, axis_: str,
forward_: bool, forward_: bool,
author: str = "Eilles", author: str = "Eilles",
outfile: str = "./test.bdx", outfile: str = "./test.bdx",
): ):
""" """
:funcList list: 指令集列表: 指令系统[ 指令集[ 单个指令( str指令, bool条件性 ), ], ] :param funcList: 指令集列表: 指令系统[ 指令集[ 单个指令( str指令, bool条件性 ), ], ]
:param axis_:
:param forward_:
:param author: 作者名称 :param author: 作者名称
:param maxheight: 生成结构最大高度 :param outfile: str 输出文件
:outfile: str 输出文件
:return 成功与否,指令总长度,指令总延迟,指令结构总大小,画笔最终坐标 :return 成功与否,指令总长度,指令总延迟,指令结构总大小,画笔最终坐标
""" """
@ -311,38 +325,39 @@ def toLineBDXfile(
f.write("BD@") f.write("BD@")
_bytes = ( _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} totalSize = {x: 0, y: 0, z: 0}
totalLen = 0 totalLen = 0
for func in funcList: for func in funcList:
totalLen += len(func) totalLen += len(func)
_bytes += toLineBDXbytes(func, axis_, forward_) _bytes += toLineBDX_bytes(func, axis_, forward_)
_bytes += move(z if axis_ == x else x, 2) _bytes += move(z if axis_ == x else x, 2)
totalSize[z if axis_ == x else x] += 2 totalSize[z if axis_ == x else x] += 2
totalSize[axis_] = max(totalSize[axis_], len(func)) totalSize[axis_] = max(totalSize[axis_], len(func))
with open( with open(
os.path.abspath(outfile), os.path.abspath(outfile),
"ab+", "ab+",
) as f: ) as f:
f.write(brotli.compress(_bytes + b"XE")) f.write(brotli.compress(_bytes + b"XE"))
return (True, totalLen, 0, list(totalSize.values())) return True, totalLen, 0, list(totalSize.values())
def formatipt(notice: str, fun, errnote: str = "", *extraArg):
'''循环输入,以某种格式 def format_ipt(notice: str, fun, err_note: str = "", *extraArg):
"""循环输入,以某种格式
notice: 输入时的提示 notice: 输入时的提示
fun: 格式函数 fun: 格式函数
errnote: 输入不符格式时的提示 err_note: 输入不符格式时的提示
*extraArg: 对于函数的其他参数''' *extraArg: 对于函数的其他参数"""
while True: while True:
result = input(notice) result = input(notice)
try: try:
funresult = fun(result, *extraArg) fun_result = fun(result, *extraArg)
break break
except: except BaseError:
print(errnote) print(err_note)
continue continue
return result, funresult return result, fun_result

View File

@ -1,2 +1,3 @@
Brotli==1.0.9 Brotli==1.0.9
mido==1.2.10 mido==1.2.10
rich==13.2.0