pymud 0.21.0a3__py3-none-any.whl → 0.21.0a5__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.
pymud/main.py CHANGED
@@ -1,207 +1,221 @@
1
- import os, sys, json, platform, shutil, logging, argparse, locale
2
- from pathlib import Path
3
- from .pymud import PyMudApp
4
- from .settings import Settings
5
-
6
- CFG_TEMPLATE = {
7
- "language" : "chs", # 语言设置,默认为简体中文
8
- "client": {
9
- "buffer_lines" : 5000, # 保留缓冲行数
10
-
11
- "interval" : 10, # 在自动执行中,两次命令输入中的间隔时间(ms)
12
- "auto_connect" : True, # 创建会话后,是否自动连接
13
- "auto_reconnect" : False, # 在会话异常断开之后,是否自动重连
14
- "var_autosave" : True, # 断开时自动保存会话变量
15
- "var_autoload" : True, # 初始化时自动加载会话变量
16
-
17
- "echo_input" : False,
18
- "beautify" : True, # 专门为解决控制台下PKUXKX字符画对不齐的问题
19
-
20
- "status_display" : 1, # 状态窗口显示情况设置,0-不显示,1-显示在下方,2-显示在右侧
21
- "status_height" : 4, # 下侧状态栏的高度
22
- "status_width" : 30, # 右侧状态栏的宽度
23
-
24
- },
25
- "sessions" : {
26
- "pkuxkx" : {
27
- "host" : "mud.pkuxkx.net",
28
- "port" : "8081",
29
- "encoding" : "utf8",
30
- "autologin" : "{0};{1}",
31
- "default_script": "examples",
32
- "chars" : {
33
- "display_title" : ["yourid", "yourpassword", ""],
34
- }
35
- }
36
- },
37
- "keys" : {
38
- "f3" : "#ig",
39
- "f4" : "#clear",
40
- "f11" : "#close",
41
- "f12" : "#exit",
42
- }
43
- }
44
-
45
- def detect_system_language():
46
- """
47
- 检测系统语言,返回中文或英文"
48
- """
49
- lang = "chs"
50
- try:
51
- value = locale.getlocale()[0]
52
- if value and (value.lower().startswith("zh") or value.lower().startswith("chinese")): # 中文
53
- lang = "chs"
54
- else:
55
- lang = "eng"
56
- except Exception as e:
57
- # default is chs
58
- pass
59
-
60
- return lang
61
-
62
- def init_pymud_env(args):
63
- lang = detect_system_language()
64
- if lang == "chs":
65
- print(f"欢迎使用PyMUD, 版本{Settings.__version__}. 使用PyMUD时, 建议建立一个新目录(任意位置),并将自己的脚本以及配置文件放到该目录下.")
66
- print("即将开始为首次运行初始化环境...")
67
-
68
- dir = args.dir
69
- if dir:
70
- print(f"你已经指定了创建脚本的目录为 {args.dir}")
71
- dir = Path(dir)
72
- else:
73
- dir = Path.home().joinpath('pkuxkx')
74
-
75
- system = platform.system().lower()
76
- dir_enter = input(f"检测到当前系统为 {system}, 请指定游戏脚本的目录(若目录不存在会自动创建),直接回车表示使用默认值 [{dir}]:")
77
- if dir_enter:
78
- dir = Path(dir_enter)
79
-
80
- if dir.exists() and dir.is_dir():
81
- print(f'检测到给定目录 {dir} 已存在,切换至此目录...')
82
- else:
83
- print(f'检测到给定目录 {dir} 不存在,正在创建并切换至目录...')
84
- dir.mkdir()
85
-
86
- os.chdir(dir)
87
-
88
- if os.path.exists('pymud.cfg'):
89
- print(f'检测到脚本目录下已存在pymud.cfg文件,将直接使用此文件进入PyMUD...')
90
- else:
91
- print(f'检测到脚本目录下不存在pymud.cfg文件,将使用默认内容创建该配置文件...')
92
- with open('pymud.cfg', mode = 'x') as fp:
93
- fp.writelines(json.dumps(CFG_TEMPLATE, indent = 4))
94
-
95
- if not os.path.exists('examples.py'):
96
- from pymud import pkuxkx
97
- module_dir = pkuxkx.__file__
98
- shutil.copyfile(module_dir, 'examples.py')
99
- print(f'已将样例脚本拷贝至脚本目录,并加入默认配置文件')
100
-
101
- print(f"后续可自行修改 {dir} 目录下的 pymud.cfg 文件以进行配置。")
102
- if system == "windows":
103
- print(f"后续运行PyMUD, 请在 {dir} 目录下键入命令: python -m pymud,或直接使用快捷命令 pymud")
104
- else:
105
- print(f"后续运行PyMUD, 请在 {dir} 目录下键入命令: python3 -m pymud,或直接使用快捷命令 pymud")
106
-
107
- input('所有内容已初始化完毕, 请按回车进入PyMUD.')
108
-
109
- else:
110
- print(f"Welcome to PyMUD, version {Settings.__version__}. When using pymud, it is suggested that a new folder should be created (in any place), and the cfg configuration and all the scripts have been placed in the directory.")
111
- print("Starting to initialize the environment for the first time...")
112
- dir = args.dir
113
- if dir:
114
- print(f"You have specified the directory to create the script as {args.dir}")
115
- dir = Path(dir)
116
- else:
117
- dir = Path.home().joinpath('pkuxkx')
118
-
119
- system = platform.system().lower()
120
- dir_enter = input(f"Detected the current system is {system}, please specify the directory of the game script (if the directory does not exist, it will be automatically created), press Enter to use the default value [{dir}]:")
121
- if dir_enter:
122
- dir = Path(dir_enter)
123
-
124
- if dir.exists() and dir.is_dir():
125
- print(f'Detected that the given directory {dir} already exists, switching to this directory...')
126
- else:
127
- print(f'Detected that the given directory {dir} does not exist, creating and switching to the directory...')
128
- dir.mkdir()
129
-
130
- os.chdir(dir)
131
-
132
- if os.path.exists('pymud.cfg'):
133
- print(f'Detected that the pymud.cfg file already exists in the script directory, entering PyMUD directly using this file...')
134
- else:
135
- print(f'Detected that the pymud.cfg file does not exist in the script directory, creating the configuration file using the default content...')
136
- with open('pymud.cfg', mode = 'x') as fp:
137
- CFG_TEMPLATE["language"] = "eng"
138
- fp.writelines(json.dumps(CFG_TEMPLATE, indent = 4))
139
-
140
- if not os.path.exists('examples.py'):
141
- from pymud import pkuxkx
142
- module_dir = pkuxkx.__file__
143
- shutil.copyfile(module_dir, 'examples.py')
144
- print(f'The sample script has been copied to the script directory and added to the default configuration file')
145
-
146
- print(f"Afterwards, you can modify the pymud.cfg file in the {dir} directory for configuration.")
147
- if system == "windows":
148
- print(f"Afterwards, please type the command 'python -m pymud' in the {dir} directory to run PyMUD, or use the shortcut command pymud")
149
- else:
150
- print(f"Afterwards, please type the command 'python3 -m pymud' in the {dir} directory to run PyMUD, or use the shortcut command pymud")
151
-
152
- input('Press Enter to enter PyMUD.')
153
-
154
- startApp(args)
155
-
156
- def startApp(args):
157
- startup_path = Path(args.startup_dir).resolve()
158
- sys.path.append(f"{startup_path}")
159
- os.chdir(startup_path)
160
-
161
- if args.debug:
162
- logging.basicConfig(level = logging.NOTSET,
163
- format = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
164
- datefmt = '%m-%d %H:%M',
165
- filename = args.logfile,
166
- filemode = 'a' if args.filemode else 'w',
167
- encoding = "utf-8"
168
- )
169
-
170
- else:
171
- logging.basicConfig(level = logging.NOTSET,
172
- format = '%(asctime)s %(name)-12s: %(message)s',
173
- datefmt = '%m-%d %H:%M',
174
- handlers = [logging.NullHandler()],
175
- )
176
-
177
- cfg = startup_path.joinpath("pymud.cfg")
178
- cfg_data = None
179
- if os.path.exists(cfg):
180
- with open(cfg, "r", encoding="utf8", errors="ignore") as fp:
181
- cfg_data = json.load(fp)
182
-
183
- app = PyMudApp(cfg_data)
184
- app.run()
185
-
186
- def main():
187
- parser = argparse.ArgumentParser(prog = "pymud", description = "PyMUD命令行参数帮助")
188
- subparsers = parser.add_subparsers(help = 'init用于初始化运行环境')
189
-
190
- par_init = subparsers.add_parser('init', description = '初始化pymud运行环境, 包括建立脚本目录, 创建默认配置文件, 创建样例脚本等.')
191
- par_init.add_argument('-d', '--dir', dest = 'dir', metavar = 'dir', type = str, default = '', help = '指定构建脚本目录的名称, 不指定时会根据操作系统选择不同默认值')
192
- par_init.set_defaults(func = init_pymud_env)
193
-
194
- parser.add_argument('-d', '--debug', dest = 'debug', action = 'store_true', default = False, help = '指定以调试模式进入PyMUD。此时,系统log等级将设置为logging.NOTSET, 所有log数据均会被记录。默认不启用。')
195
- parser.add_argument('-l', '--logfile', dest = 'logfile', metavar = 'logfile', default = 'pymud.log', help = '指定调试模式下记录文件名,不指定时,默认为当前目录下的pymud.log')
196
- parser.add_argument('-a', '--appendmode', dest = 'filemode', action = 'store_true', default = True, help = '指定log文件的访问模式是否为append尾部添加模式,默认为True。当为False时,使用w模式,即每次运行清空之前记录')
197
- parser.add_argument('-s', '--startup_dir', dest = 'startup_dir', metavar = 'startup_dir', default = '.', help = '指定启动目录,默认为当前目录。使用该参数可以在任何目录下,通过指定脚本目录来启动')
198
-
199
- args=parser.parse_args()
200
-
201
- if hasattr(args, 'func'):
202
- args.func(args)
203
- else:
204
- startApp(args)
205
-
206
- if __name__ == "__main__":
1
+ import os, sys, json, platform, shutil, logging, argparse, locale
2
+ from pathlib import Path
3
+ from .pymud import PyMudApp
4
+ from .settings import Settings
5
+
6
+ CFG_TEMPLATE = {
7
+ "language" : "chs", # 语言设置,默认为简体中文
8
+
9
+ "client": {
10
+ "buffer_lines" : 5000, # 保留缓冲行数
11
+
12
+ "interval" : 10, # 在自动执行中,两次命令输入中的间隔时间(ms)
13
+ "auto_connect" : True, # 创建会话后,是否自动连接
14
+ "auto_reconnect" : False, # 在会话异常断开之后,是否自动重连
15
+ "reconnect_wait" : 15, # 自动重连等待的时间(秒数)
16
+ "var_autosave" : True, # 断开时自动保存会话变量
17
+ "var_autoload" : True, # 初始化时自动加载会话变量
18
+
19
+ "beautify" : True, # 专门为解决控制台下PKUXKX字符画对不齐的问题
20
+ "history_records" : 500,
21
+
22
+ "status_divider" : False, # 是否显示状态栏的分隔线
23
+ "status_display" : 1, # 状态窗口显示情况设置,0-不显示,1-显示在下方,2-显示在右侧
24
+ "status_height" : 4, # 下侧状态栏的高度
25
+ "status_width" : 30, # 右侧状态栏的宽度
26
+
27
+
28
+ },
29
+
30
+ "sessions" : {
31
+ "pkuxkx" : {
32
+ "host" : "mud.pkuxkx.net",
33
+ "port" : "8081",
34
+ "encoding" : "utf8",
35
+ "autologin" : "{0};{1}",
36
+ "default_script": "examples",
37
+ "chars" : {
38
+ "display_title" : ["yourid", "yourpassword", ""],
39
+ }
40
+ }
41
+ },
42
+ "keys" : {
43
+ "f3" : "#ig",
44
+ "f4" : "#clear",
45
+ "f11" : "#close",
46
+ "f12" : "#exit",
47
+ }
48
+ }
49
+
50
+ def detect_system_language():
51
+ """
52
+ 检测系统语言,返回中文或英文"
53
+ """
54
+ lang = "chs"
55
+ try:
56
+ value = locale.getlocale()[0]
57
+ if value and (value.lower().startswith("zh") or value.lower().startswith("chinese")): # 中文
58
+ lang = "chs"
59
+ else:
60
+ lang = "eng"
61
+ except Exception as e:
62
+ # default is chs
63
+ pass
64
+
65
+ return lang
66
+
67
+ def init_pymud_env(args):
68
+ system = "unknown"
69
+ lang = detect_system_language()
70
+ if lang == "chs":
71
+ print(f"欢迎使用PyMUD, 版本{Settings.__version__}. 使用PyMUD时, 建议建立一个新目录(任意位置),并将自己的脚本以及配置文件放到该目录下.")
72
+ print("即将开始为首次运行初始化环境...")
73
+
74
+ dir = args.dir
75
+ if dir:
76
+ if dir == ".":
77
+ dir_msg = "当前目录"
78
+ else:
79
+ dir_msg = f": {dir}"
80
+ print(f"你已经指定了创建脚本的目录为{dir_msg}")
81
+ dir = Path(dir)
82
+ else:
83
+ dir = Path.home().joinpath('pkuxkx')
84
+
85
+ system = platform.system().lower()
86
+ dir_enter = input(f"检测到当前系统为 {system}, 请指定游戏脚本的目录(若目录不存在会自动创建),直接回车表示使用默认值 [{dir}]:")
87
+ if dir_enter:
88
+ dir = Path(dir_enter)
89
+
90
+ if dir.exists() and dir.is_dir():
91
+ print(f'检测到给定目录 {dir} 已存在,切换至此目录...')
92
+ else:
93
+ print(f'检测到给定目录 {dir} 不存在,正在创建并切换至目录...')
94
+ dir.mkdir()
95
+
96
+ os.chdir(dir)
97
+
98
+ if os.path.exists('pymud.cfg'):
99
+ print(f'检测到脚本目录下已存在pymud.cfg文件,将直接使用此文件进入PyMUD...')
100
+ else:
101
+ print(f'检测到脚本目录下不存在pymud.cfg文件,将使用默认内容创建该配置文件...')
102
+ with open('pymud.cfg', mode = 'x') as fp:
103
+ fp.writelines(json.dumps(CFG_TEMPLATE, indent = 4))
104
+
105
+ if not os.path.exists('examples.py'):
106
+ from pymud import pkuxkx
107
+ module_dir = pkuxkx.__file__
108
+ shutil.copyfile(module_dir, 'examples.py')
109
+ print(f'已将样例脚本拷贝至脚本目录,并加入默认配置文件')
110
+
111
+ print(f"后续可自行修改 {dir} 目录下的 pymud.cfg 文件以进行配置。")
112
+ if system == "windows":
113
+ print(f"后续运行PyMUD, 请在 {dir} 目录下键入命令: python -m pymud,或直接使用快捷命令 pymud")
114
+ else:
115
+ print(f"后续运行PyMUD, 请在 {dir} 目录下键入命令: python3 -m pymud,或直接使用快捷命令 pymud")
116
+
117
+ input('所有内容已初始化完毕, 请按回车进入PyMUD.')
118
+
119
+ else:
120
+ print(f"Welcome to PyMUD, version {Settings.__version__}. When using pymud, it is suggested that a new folder should be created (in any place), and the cfg configuration and all the scripts have been placed in the directory.")
121
+ print("Starting to initialize the environment for the first time...")
122
+ dir = args.dir
123
+ if dir:
124
+ if dir == ".":
125
+ dir_msg = "current directory"
126
+ else:
127
+ dir_msg = f": {dir}"
128
+ print(f"You have specified the directory to create the script as {dir_msg}")
129
+ dir = Path(dir)
130
+ else:
131
+ dir = Path.home().joinpath('pkuxkx')
132
+
133
+ system = platform.system().lower()
134
+ dir_enter = input(f"Detected the current system is {system}, please specify the directory of the game script (if the directory does not exist, it will be automatically created), press Enter to use the default value [{dir}]:")
135
+ if dir_enter:
136
+ dir = Path(dir_enter)
137
+
138
+ if dir.exists() and dir.is_dir():
139
+ print(f'Detected that the given directory {dir} already exists, switching to this directory...')
140
+ else:
141
+ print(f'Detected that the given directory {dir} does not exist, creating and switching to the directory...')
142
+ dir.mkdir()
143
+
144
+ os.chdir(dir)
145
+
146
+ if os.path.exists('pymud.cfg'):
147
+ print(f'Detected that the pymud.cfg file already exists in the script directory, entering PyMUD directly using this file...')
148
+ else:
149
+ print(f'Detected that the pymud.cfg file does not exist in the script directory, creating the configuration file using the default content...')
150
+ with open('pymud.cfg', mode = 'x') as fp:
151
+ CFG_TEMPLATE["language"] = "eng"
152
+ fp.writelines(json.dumps(CFG_TEMPLATE, indent = 4))
153
+
154
+ if not os.path.exists('examples.py'):
155
+ from pymud import pkuxkx
156
+ module_dir = pkuxkx.__file__
157
+ shutil.copyfile(module_dir, 'examples.py')
158
+ print(f'The sample script has been copied to the script directory and added to the default configuration file')
159
+
160
+ print(f"Afterwards, you can modify the pymud.cfg file in the {dir} directory for configuration.")
161
+ if system == "windows":
162
+ print(f"Afterwards, please type the command 'python -m pymud' in the {dir} directory to run PyMUD, or use the shortcut command pymud")
163
+ else:
164
+ print(f"Afterwards, please type the command 'python3 -m pymud' in the {dir} directory to run PyMUD, or use the shortcut command pymud")
165
+
166
+ input('Press Enter to enter PyMUD.')
167
+
168
+ startApp(args)
169
+
170
+ def startApp(args):
171
+ startup_path = Path(args.startup_dir).resolve()
172
+ sys.path.append(f"{startup_path}")
173
+ os.chdir(startup_path)
174
+
175
+ if args.debug:
176
+ logging.basicConfig(level = logging.NOTSET,
177
+ format = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
178
+ datefmt = '%m-%d %H:%M',
179
+ filename = args.logfile,
180
+ filemode = 'a' if args.filemode else 'w',
181
+ encoding = "utf-8"
182
+ )
183
+
184
+ else:
185
+ logging.basicConfig(level = logging.NOTSET,
186
+ format = '%(asctime)s %(name)-12s: %(message)s',
187
+ datefmt = '%m-%d %H:%M',
188
+ handlers = [logging.NullHandler()],
189
+ )
190
+
191
+ cfg = startup_path.joinpath("pymud.cfg")
192
+ cfg_data = None
193
+ if os.path.exists(cfg):
194
+ with open(cfg, "r", encoding="utf8", errors="ignore") as fp:
195
+ cfg_data = json.load(fp)
196
+
197
+ app = PyMudApp(cfg_data)
198
+ app.run()
199
+
200
+ def main():
201
+ parser = argparse.ArgumentParser(prog = "pymud", description = "PyMUD命令行参数帮助")
202
+ subparsers = parser.add_subparsers(help = 'init用于初始化运行环境')
203
+
204
+ par_init = subparsers.add_parser('init', description = '初始化pymud运行环境, 包括建立脚本目录, 创建默认配置文件, 创建样例脚本等.')
205
+ par_init.add_argument('-d', '--dir', dest = 'dir', metavar = 'dir', type = str, default = '.', help = '指定构建脚本目录的名称, 不指定时会根据操作系统选择不同默认值')
206
+ par_init.set_defaults(func = init_pymud_env)
207
+
208
+ parser.add_argument('-d', '--debug', dest = 'debug', action = 'store_true', default = False, help = '指定以调试模式进入PyMUD。此时,系统log等级将设置为logging.NOTSET, 所有log数据均会被记录。默认不启用。')
209
+ parser.add_argument('-l', '--logfile', dest = 'logfile', metavar = 'logfile', default = 'pymud.log', help = '指定调试模式下记录文件名,不指定时,默认为当前目录下的pymud.log')
210
+ parser.add_argument('-a', '--appendmode', dest = 'filemode', action = 'store_true', default = True, help = '指定log文件的访问模式是否为append尾部添加模式,默认为True。当为False时,使用w模式,即每次运行清空之前记录')
211
+ parser.add_argument('-s', '--startup_dir', dest = 'startup_dir', metavar = 'startup_dir', default = '.', help = '指定启动目录,默认为当前目录。使用该参数可以在任何目录下,通过指定脚本目录来启动')
212
+
213
+ args=parser.parse_args()
214
+
215
+ if hasattr(args, 'func'):
216
+ args.func(args)
217
+ else:
218
+ startApp(args)
219
+
220
+ if __name__ == "__main__":
207
221
  main()