From 0cb5b54eb71505104fc6db0ef08e6d3dd6740fc0 Mon Sep 17 00:00:00 2001 From: shenjack <3695888@qq.com> Date: Sun, 14 May 2023 20:23:20 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E5=96=84=20MainGame?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Difficult_Rocket/__init__.py | 1 + Difficult_Rocket/main.py | 47 +++++++++++++++---- Difficult_Rocket/utils/options.py | 11 +++-- configs/logger.toml | 1 - .../Difficult_Rocket_rs/src/src/lib.rs | 12 ++--- .../Difficult_Rocket_rs/src/src/python.rs | 4 +- mods/dr_game/__init__.py | 2 +- 7 files changed, 56 insertions(+), 22 deletions(-) diff --git a/Difficult_Rocket/__init__.py b/Difficult_Rocket/__init__.py index f654bda..fefefe9 100644 --- a/Difficult_Rocket/__init__.py +++ b/Difficult_Rocket/__init__.py @@ -5,6 +5,7 @@ # ------------------------------- import sys +import time import importlib import traceback import contextlib diff --git a/Difficult_Rocket/main.py b/Difficult_Rocket/main.py index 50ca58d..77081c0 100644 --- a/Difficult_Rocket/main.py +++ b/Difficult_Rocket/main.py @@ -15,6 +15,7 @@ import os import sys import time import logging +import traceback import importlib import importlib.util import logging.config @@ -28,16 +29,16 @@ if __name__ == '__main__': # been start will not run this sys.path.append('/bin/libs') sys.path.append('/bin') -from Difficult_Rocket import client, server, DR_option, DR_runtime if TYPE_CHECKING: from Difficult_Rocket.api.mod import ModInfo else: ModInfo = TypeVar('ModInfo') from Difficult_Rocket.utils import tools -from Difficult_Rocket.utils.translate import tr -from Difficult_Rocket.crash import write_info_to_cache from Difficult_Rocket.api.types import Options +from Difficult_Rocket.utils.translate import tr from Difficult_Rocket.utils.thread import new_thread +from Difficult_Rocket.crash import write_info_to_cache +from Difficult_Rocket import client, server, DR_option, DR_runtime class Game: @@ -206,12 +207,23 @@ class MainGame(Options): console: Console main_config: Dict + logging_config: Dict logger: logging.Logger mod_module: List["ModInfo"] def init_logger(self) -> None: - ... + log_path = self.logging_config['handlers']['file']['filename'] + log_path = Path(f"logs/{log_path.format(time.strftime('%Y-%m-%d %H-%M-%S' , time.gmtime(DR_runtime.start_time_ns)))}") + mkdir = False + if not log_path.exists(): + log_path.mkdir(parents=True) + mkdir = True + self.logging_config['handlers']['file']['filename'] = log_path.name + logging.config.dictConfig(self.logging_config) + self.logger = logging.getLogger('main') + if mkdir: + self.logger.info(tr().main.logger.mkdir()) def init_console(self) -> None: self.console = Console() @@ -274,14 +286,33 @@ class MainGame(Options): if hasattr(mod, event_name): try: getattr(mod, event_name)(*args, **kwargs) - except Exception as e: - self.logger.error(tr().main.mod.event.error().format(event_name, e, mod.mod_id)) + except Exception: + error = traceback.format_exc() + self.logger.error(tr().main.mod.event.error().format(event_name, error, mod.mod_id)) - def init(self, **kwargs) -> None: - ... + def log_env(self) -> None: + cache_steam = StringIO() + write_info_to_cache(cache_steam) + text = cache_steam.getvalue() + self.logger.info(text) + self.flush_option() + self.logger.info(self.as_markdown()) + + def setup(self) -> None: + self.client = client.Client(game=self, net_mode='local') + self.server = server.Server(net_mode='local') + + def init(self, **kwargs) -> bool: + self.load_file() + self.setup() + self.log_env() + return True def load_file(self) -> bool: """加载文件""" + self.logging_config = tools.load_file('configs/logger.toml') self.init_logger() self.init_mods() + self.init_console() return True + diff --git a/Difficult_Rocket/utils/options.py b/Difficult_Rocket/utils/options.py index b8586e9..8ec927b 100644 --- a/Difficult_Rocket/utils/options.py +++ b/Difficult_Rocket/utils/options.py @@ -66,9 +66,10 @@ class Options: if option not in self.cached_options: raise OptionNameNotDefined(f"option: {option} with value: {value} is not defined") setattr(self, option, value) + run_load_file = True if hasattr(self, 'init'): - self.init(**kwargs) - if hasattr(self, 'load_file'): + run_load_file = not self.init(**kwargs) # 默认 False/None + if hasattr(self, 'load_file') and run_load_file: try: self.load_file() except Exception: @@ -78,8 +79,10 @@ class Options: if TYPE_CHECKING: _options: Dict[str, Union[Callable, object]] = {} - def init(self, **kwargs) -> None: - """ 如果子类定义了这个函数,则会在 __init__ 之后调用这个函数 """ + def init(self, **kwargs) -> bool: + """ 如果子类定义了这个函数,则会在 __init__ 之后调用这个函数 + 返回值为 True 则不会调用 load_file 函数 + """ def load_file(self) -> bool: """如果子类定义了这个函数,则会在 __init__ 和 init 之后再调用这个函数 diff --git a/configs/logger.toml b/configs/logger.toml index 927a7cd..5a65de0 100644 --- a/configs/logger.toml +++ b/configs/logger.toml @@ -27,7 +27,6 @@ level = "DEBUG" [handlers.file] class = "logging.FileHandler" filename = "{} DR.log" -datefmt = "%Y-%m-%d %H:%M:%S" encoding = "utf-8" formatter = "file" level = "DEBUG" diff --git a/mods/dr_game/Difficult_Rocket_rs/src/src/lib.rs b/mods/dr_game/Difficult_Rocket_rs/src/src/lib.rs index 861fd2e..c40b0b5 100644 --- a/mods/dr_game/Difficult_Rocket_rs/src/src/lib.rs +++ b/mods/dr_game/Difficult_Rocket_rs/src/src/lib.rs @@ -19,15 +19,15 @@ use pyo3::prelude::*; // const MOD_PATH: String = String::from("mods"); enum LoadState { - init, - wait_start, - pre_start, - running, - clean, + Init, + WaitStart, + PreStart, + Running, + Clean, } #[pyfunction] -fn get_version_str() -> String { "0.2.7.0".to_string() } +fn get_version_str() -> String { "0.2.8.0".to_string() } #[pyfunction] fn test_call(py_obj: &PyAny) -> PyResult { diff --git a/mods/dr_game/Difficult_Rocket_rs/src/src/python.rs b/mods/dr_game/Difficult_Rocket_rs/src/src/python.rs index 56494b8..32cccc2 100644 --- a/mods/dr_game/Difficult_Rocket_rs/src/src/python.rs +++ b/mods/dr_game/Difficult_Rocket_rs/src/src/python.rs @@ -212,7 +212,7 @@ pub mod console { } fn stop(&self) -> bool { - if let (Some(sender)) = &self.stop_sender { + if let Some(sender) = &self.stop_sender { sender.send(()).unwrap(); return true; } @@ -221,7 +221,7 @@ pub mod console { fn get_command(&self) -> Option { // 获取输入 - if let (Some(receiver)) = &self.keyboard_input_receiver { + if let Some(receiver) = &self.keyboard_input_receiver { if let Ok(string) = receiver.try_recv() { return Some(string); } diff --git a/mods/dr_game/__init__.py b/mods/dr_game/__init__.py index 19ad067..48fee02 100644 --- a/mods/dr_game/__init__.py +++ b/mods/dr_game/__init__.py @@ -15,7 +15,7 @@ from Difficult_Rocket.api.mod import ModInfo from Difficult_Rocket.api.types import Options from Difficult_Rocket.client import ClientWindow -DR_rust_version = Version("0.2.7.0") # DR_mod 的 Rust 编写部分的兼容版本 +DR_rust_version = Version("0.2.8.0") # DR_mod 的 Rust 编写部分的兼容版本 class _DR_mod_runtime(Options):