重构 Game obj

This commit is contained in:
shenjack 2023-05-14 20:42:18 +08:00
parent 4f0ec98879
commit ad19ef1e28
5 changed files with 33 additions and 155 deletions

View File

@ -11,7 +11,6 @@ github: @shenjackyuanjie
gitee: @shenjackyuanjie
"""
import os
import sys
import time
import logging
@ -41,135 +40,6 @@ from Difficult_Rocket.crash import write_info_to_cache
from Difficult_Rocket import client, server, DR_option, DR_runtime
class Game:
def __init__(self):
# basic config
self.on_python_v_info = sys.version_info
self.on_python_v = sys.version.split(' ')[0]
self.start_time = time.strftime('%Y-%m-%d %H-%M-%S', time.gmtime(time.time()))
# lang_config
self.language = tools.load_file('configs/main.toml', 'runtime')['language']
DR_option.language = self.language
# logging config
log_config = tools.load_file('configs/logger.toml')
file_name = log_config['handlers']['file']['filename']
del log_config['handlers']['file']['datefmt']
log_config['handlers']['file']['filename'] = f'logs/{file_name.format(self.start_time)}'
try:
logging.config.dictConfig(log_config)
self.logger = logging.getLogger('main')
except ValueError: # it should be no 'logs/' folder
os.mkdir('logs')
logging.config.dictConfig(log_config)
self.logger = logging.getLogger('main')
self.logger.info(tr().main.logger.mkdir())
self.logger.info(tr().language_set_to())
self.logger.info(tr().main.logger.created())
# version check
self.log_env()
self.python_version_check()
self.loaded_mods = []
# self.client = client.Client
# self.server = server.Server
self.setup()
def log_env(self) -> None:
cache_steam = StringIO()
write_info_to_cache(cache_steam)
text = cache_steam.getvalue()
self.logger.info(text)
def load_mods(self) -> None:
mods = []
mod_path = Path(DR_runtime.mod_path)
if not mod_path.exists():
self.logger.info(tr().main.mod.find.faild.no_mod_folder())
return
# 寻找有效 mod
paths = mod_path.iterdir()
sys.path.append(DR_runtime.mod_path)
for mod_path in paths:
try:
if mod_path.name == '__pycache__':
continue
self.logger.info(tr().main.mod.find.start().format(mod_path))
if mod_path.is_dir():
if importlib.util.find_spec(mod_path.name) is not None:
mods.append(mod_path.name)
else:
self.logger.warning(tr().main.mod.load.faild.info().format(mod_path.name, tr().main.mod.find.faild.no_spec()))
elif mod_path.suffix in ('.pyz', '.zip', '.pyd', '.py'):
if importlib.util.find_spec(mod_path.name) is not None:
mods.append(mod_path.name)
except ImportError as e:
self.logger.warning(tr().main.mod.find.faild().format(mod_path, e))
self.logger.info(tr().main.mod.find.done())
# 加载有效 mod
module = []
for mod in mods:
try:
self.logger.info(tr().main.mod.load.start().format(mod))
mod_module = importlib.import_module(mod)
if not hasattr(mod_module, "mod_class"):
self.logger.warning(tr().main.mod.load.faild.info().format(mod, tr().main.mod.load.faild.no_mod_class()))
del mod_module # 释放内存
continue
mod_class: type(ModInfo) = mod_module.mod_class
mod_class = mod_class()
module.append(mod_class)
self.logger.info(tr().main.mod.load.info().format(mod_class.mod_id, mod_class.version))
except ImportError as e:
self.logger.warning(tr().main.mod.load.faild.info().format(mod, e))
self.logger.info(tr().main.mod.load.done())
self.loaded_mods = module
mod_list = []
for mod in module:
mod_list.append((mod.mod_id, mod.version))
# 调用 on_load
self.dispatch_event('on_load', game=self)
DR_runtime.DR_Mod_List = mod_list
def dispatch_event(self, event_name: str, *args, **kwargs) -> None:
for mod in self.loaded_mods:
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))
def setup(self) -> None:
self.load_mods()
self.client = client.Client(game=self, net_mode='local')
self.server = server.Server(net_mode='local')
def python_version_check(self) -> None: # best 3.8+ and write at 3.8.10
self.logger.info(f"{tr().main.version.now_on()} {self.on_python_v}")
if self.on_python_v_info[0] == 2:
self.logger.critical(tr().main.version.need3p())
raise SystemError(tr().main.version.need3p())
elif self.on_python_v_info[1] < 8:
warning = tools.name_handler(tr.main.version.best38p())
self.logger.warning(warning)
# @new_thread('main')
def _start(self):
self.server.run()
if DR_option.use_multiprocess:
try:
game_process = multiprocessing.Process(target=self.client.start, name='pyglet app')
game_process.start()
game_process.join()
except Exception:
return -1
else:
return 1
else:
self.client.start()
def start(self) -> None:
self._start()
class Console(Options):
name = 'python stdin console'
@ -199,12 +69,13 @@ class Console(Options):
return self.caches.pop(0)
class MainGame(Options):
class Game(Options):
name = 'MainGame'
client: client.Client
server: server.Server
console: Console
console_class: Console = Console
main_config: Dict
logging_config: Dict
@ -214,23 +85,20 @@ class MainGame(Options):
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)))}")
log_path = Path(f"logs/{log_path.format(time.strftime('%Y-%m-%d %H-%M-%S' , time.gmtime(DR_runtime.start_time_ns / 1000_000_000)))}")
mkdir = False
if not log_path.exists():
if not Path("logs/").exists():
log_path.mkdir(parents=True)
mkdir = True
self.logging_config['handlers']['file']['filename'] = log_path.name
self.logging_config['handlers']['file']['filename'] = str(log_path.absolute())
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()
self.console.start()
def init_mods(self) -> None:
"""验证/加载 mod"""
print(self)
mods = []
mod_path = Path(DR_runtime.mod_path)
if not mod_path.exists():
@ -280,6 +148,24 @@ class MainGame(Options):
self.dispatch_event('on_load', game=self)
DR_runtime.DR_Mod_List = mod_list
def init_console(self) -> None:
self.console = Console()
self.console.start()
def start(self):
self.server.run()
if DR_option.use_multiprocess:
try:
game_process = multiprocessing.Process(target=self.client.start, name='pyglet app')
game_process.start()
game_process.join()
except Exception:
return -1
else:
return 1
else:
self.client.start()
def dispatch_event(self, event_name: str, *args, **kwargs) -> None:
"""向 mod 分发事件"""
for mod in self.mod_module:
@ -296,7 +182,10 @@ class MainGame(Options):
text = cache_steam.getvalue()
self.logger.info(text)
self.flush_option()
self.logger.info(self.as_markdown())
config_cache = self.logging_config.copy()
self.logging_config = {"logging_config": "too long to show"}
self.logger.info(f"\n{self.as_markdown()}")
self.logging_config = config_cache
def setup(self) -> None:
self.client = client.Client(game=self, net_mode='local')

View File

@ -68,7 +68,8 @@ class Options:
setattr(self, option, value)
run_load_file = True
if hasattr(self, 'init'):
run_load_file = not self.init(**kwargs) # 默认 False/None
run_load_file = self.init(**kwargs) # 默认 False/None
run_load_file = not run_load_file
if hasattr(self, 'load_file') and run_load_file:
try:
self.load_file()

View File

@ -18,6 +18,7 @@ use pyo3::prelude::*;
// const MOD_PATH: String = String::from("mods");
#[allow(unused)]
enum LoadState {
Init,
WaitStart,

View File

@ -69,11 +69,7 @@ class DR_mod(ModInfo):
return False
from .console import RustConsole
def init_console(self) -> None:
self.console = RustConsole()
self.console.start()
game.init_console = init_console # 替换掉原来的 init_console 函数
game.console_class = RustConsole # 替换掉原来的 console 类
if old_self:
game.client.window.add_sub_screen("SR1_ship", old_self.screen)

View File

@ -36,7 +36,7 @@ if TYPE_CHECKING:
from Difficult_Rocket.client import ClientWindow
if DR_mod_runtime.use_DR_rust:
from .Difficult_Rocket_rs import CenterCamera_rs, SR1PartList_rs, Console_rs
from .Difficult_Rocket_rs import CenterCamera_rs, SR1PartList_rs
logger = logging.getLogger('client')
@ -135,7 +135,6 @@ class SR1ShipRender(BaseScreen):
min_zoom=(1 / 2) ** 10, max_zoom=10)
self.rust_parts = None
self.part_list_rs = SR1PartList_rs('configs/PartList.xml', 'default_part_list')
self.console = Console_rs()
def load_xml(self, file_path: str) -> bool:
try:
@ -271,11 +270,6 @@ class SR1ShipRender(BaseScreen):
self.debug_mouse_label.draw()
if SR1ShipRender_Option.debug_mouse_d_pos:
self.debug_mouse_delta_line.draw()
if DR_mod_runtime.use_DR_rust:
read_input = self.console.get_command()
if read_input:
print(f"Rust console: |{read_input}|")
window.dispatch_event("on_command", CommandText(read_input))
def on_resize(self, width: int, height: int, window: "ClientWindow"):
if not self.rendered:
@ -387,9 +381,6 @@ class SR1ShipRender(BaseScreen):
if self.load_xml(path): # 加载成功一个就停下
break
self.render_ship()
def on_close(self, window: "ClientWindow"):
self.console.stop_console()
if __name__ == '__main__':