Difficult-Rocket/Difficult_Rocket/client.py

235 lines
8.4 KiB
Python
Raw Normal View History

2021-09-08 23:38:34 +08:00
# -------------------------------
# Difficult Rocket
# Copyright © 2021 by shenjackyuanjie
# All rights reserved
# -------------------------------
2021-02-20 21:46:14 +08:00
"""
2020-12-13 18:39:12 +08:00
writen by shenjackyuanjie
2021-09-08 23:38:34 +08:00
mail: 3695888@qq.com
github: @shenjackyuanjie
gitee: @shenjackyuanjie
2021-02-20 21:46:14 +08:00
"""
2021-09-08 23:38:34 +08:00
# system function
2021-02-20 21:46:14 +08:00
import os
2021-03-25 23:15:18 +08:00
import sys
2021-04-10 22:51:08 +08:00
import time
import random
import logging
import threading
import configparser
import multiprocessing
2021-09-24 00:04:56 +08:00
from decimal import Decimal
from multiprocessing import Pipe
from multiprocessing.connection import Connection
2021-08-24 22:31:52 +08:00
if __name__ == '__main__': # been start will not run this
sys.path.append('/bin/libs')
sys.path.append('/bin')
2021-07-08 20:42:22 +08:00
# Difficult_Rocket function
from Difficult_Rocket import crash
2021-09-09 23:54:03 +08:00
from Difficult_Rocket.api.Exp import *
from Difficult_Rocket.api.translate import tr
2021-09-08 23:38:34 +08:00
from Difficult_Rocket.drag_sprite import DragSprite
from Difficult_Rocket.api import tools, load_file, new_thread, thread
2021-02-03 22:04:34 +08:00
# libs function
local_lib = True
if local_lib:
from libs import pyglet
from libs.pyglet.window import key, mouse
else:
import pyglet
from pyglet.window import key, mouse
2020-12-16 06:33:33 +08:00
2021-08-13 12:25:29 +08:00
class Client:
def __init__(self, net_mode='local'):
# logging
2021-08-13 12:25:29 +08:00
self.logger = logging.getLogger('client')
# config
self.config = tools.load_file('configs/main.config')
2021-02-22 23:17:16 +08:00
# lang
self.lang = tools.load_file('configs/lang/%s.json5' % self.config['runtime']['language'], 'client')
# value
self.process_id = 'Client'
self.process_name = 'Client process'
2021-02-20 21:46:14 +08:00
self.process_pid = os.getpid()
self.net_mode = net_mode
2021-08-13 12:25:29 +08:00
self.caption = tools.name_handler(self.config['window']['caption'], {'version': self.config['runtime']['version']})
self.window = ClientWindow(net_mode=self.net_mode,
2021-08-13 12:25:29 +08:00
width=int(self.config['window']['width']),
height=int(self.config['window']['height']),
fullscreen=tools.format_bool(self.config['window']['full_screen']),
caption=self.caption,
resizable=tools.format_bool(self.config['window']['resizable']),
visible=tools.format_bool(self.config['window']['visible']))
self.logger.info(tr['client']['setup.done'])
2021-02-20 21:46:14 +08:00
def start(self):
self.window.start_game() # 游戏启动
2021-08-24 22:31:52 +08:00
# TODO 写一下服务端启动相关,还是需要服务端啊
2021-01-11 21:58:51 +08:00
2021-08-13 12:25:29 +08:00
class ClientWindow(pyglet.window.Window):
def __init__(self, net_mode='local', *args, **kwargs):
2021-09-02 22:47:10 +08:00
self.times = [time.time()]
2021-08-13 12:25:29 +08:00
super().__init__(*args, **kwargs)
2021-02-16 12:51:07 +08:00
"""
2021-02-03 22:04:34 +08:00
:param dev_list: 共享内存
:param dev_dic: 共享内存
:param logger: logger
:param net_mode: 网络模式 # local / ip
2021-02-16 12:51:07 +08:00
"""
2021-01-25 12:22:55 +08:00
# logging
2021-08-13 12:25:29 +08:00
self.logger = logging.getLogger('client')
2021-02-03 22:04:34 +08:00
# value
self.net_mode = net_mode
self.run_input = False
2021-08-24 22:31:52 +08:00
# configs
pyglet.resource.path = ['textures']
pyglet.resource.reindex()
self.config_file = tools.load_file('configs/main.config')
2021-09-24 00:04:56 +08:00
self.FPS = Decimal(int(self.config_file['runtime']['fps']))
self.SPF = Decimal('1') / self.FPS
2021-02-22 21:32:13 +08:00
# lang
self.lang = tools.load_file('configs/lang/%s.json5' % self.config_file['runtime']['language'], 'client')
2020-12-16 06:33:33 +08:00
# dic
2021-09-02 22:47:10 +08:00
self.environment = {}
self.textures = {} # all textures
self.runtime = {}
# FPS
self.max_fps = [self.FPS, time.time()]
self.min_fps = [self.FPS, time.time()]
self.fps_wait = 5
2021-02-20 21:46:14 +08:00
# batch
self.part_batch = pyglet.graphics.Batch()
self.label_batch = pyglet.graphics.Batch()
2021-08-24 22:31:52 +08:00
# frame
self.frame = pyglet.gui.Frame(self)
2021-09-24 00:04:56 +08:00
self.M_frame = pyglet.gui.MovableFrame(self)
2021-02-03 22:04:34 +08:00
# setup
self.setup()
2021-08-24 22:31:52 +08:00
self.info_label = pyglet.text.Label(x=10, y=self.height - 10,
anchor_x='left', anchor_y='top',
batch=self.label_batch)
2021-09-24 00:04:56 +08:00
pyglet.clock.schedule_interval(self.update, float(self.SPF))
2021-09-08 23:38:34 +08:00
self.logger.info(self.lang['setup.done'])
2021-09-02 22:47:10 +08:00
@new_thread('client_load_environment')
def load_environment(self) -> None:
# load parts info
self.environment['parts'] = load_file('configs/sys_value/parts.json5')
2021-09-05 00:50:05 +08:00
try:
self.load_textures()
except TexturesError:
2021-09-05 00:50:05 +08:00
raise
2020-12-16 06:33:33 +08:00
2021-08-24 22:31:52 +08:00
@new_thread('client_load_textures')
2021-09-02 22:47:10 +08:00
def load_textures(self) -> None:
# load parts
self.textures['parts'] = {}
for part in self.environment['parts']:
pass
2020-12-16 06:33:33 +08:00
def setup(self):
self.logger.info(tr.lang('window', 'os.pid_is').format(os.getpid(), os.getppid()))
2021-08-24 22:31:52 +08:00
image = pyglet.image.load('textures/Editor/PartButton.png')
2021-09-05 00:50:05 +08:00
self.textures['test'] = DragSprite(10, 20, image, batch=self.label_batch, drag_by_all=False, drag_out_window=True)
2021-09-02 22:47:10 +08:00
self.load_environment()
2021-02-20 21:46:14 +08:00
def start_game(self) -> None:
self.run_input = True
# self.input_line = threading.Thread(target=self.read_input, name='client_read_line', daemon=True)
# self.input_line.start()
pyglet.app.run()
def read_input(self):
self.logger.debug('read_input start')
while self.run_input:
get = input('<<<')
self.logger.info(get)
if get == 'stop':
self.run_input = False
self.logger.debug('read_input end')
"""
draws and some event
"""
2021-01-29 14:07:40 +08:00
2021-09-02 22:47:10 +08:00
def update(self, tick: float):
self.FPS_update(tick)
2021-02-22 21:32:13 +08:00
2021-09-02 22:47:10 +08:00
def FPS_update(self, tick: float):
2021-02-22 12:28:13 +08:00
now_FPS = pyglet.clock.get_fps()
2021-02-22 21:32:13 +08:00
if now_FPS > self.max_fps[0]:
self.max_fps = [now_FPS, time.time()]
elif now_FPS < self.min_fps[0]:
self.min_fps = [now_FPS, time.time()]
else:
if (time.time() - self.max_fps[1]) > self.fps_wait:
self.max_fps = [self.FPS, time.time()]
elif (time.time() - self.min_fps[1]) > self.fps_wait:
self.min_fps = [self.FPS, time.time()]
2021-09-02 22:47:10 +08:00
self.info_label.text = 'FPS: {:.1f} {:.1f} ({:.1f}/{:.1f}) | MSPF: {:.5f} '.format(now_FPS, 1 / tick, self.max_fps[0], self.min_fps[0], tick)
2021-02-21 11:58:47 +08:00
2020-12-16 06:33:33 +08:00
def on_draw(self):
2021-02-22 21:32:13 +08:00
self.clear()
2021-02-20 21:46:14 +08:00
self.draw_batch()
2021-09-02 22:47:10 +08:00
def on_resize(self, width: int, height: int):
super().on_resize(width, height)
self.info_label.y = height - 10
2021-02-20 21:46:14 +08:00
def draw_batch(self):
self.part_batch.draw()
self.label_batch.draw()
"""
2021-01-28 22:50:28 +08:00
keyboard and mouse input
"""
2021-01-28 22:50:28 +08:00
2021-08-13 12:25:29 +08:00
def on_mouse_motion(self, x, y, dx, dy) -> None:
2021-04-10 22:48:22 +08:00
# self.logger.debug('按键移动 %s %s %s %s' % (x, y, dx, dy))
pass
2020-12-16 06:33:33 +08:00
2021-08-13 12:25:29 +08:00
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers) -> None:
2021-08-24 22:31:52 +08:00
# self.logger.debug('按键拖拽 %s %s %s %s %s %s' % (x, y, dx, dy, buttons, modifiers))
self.textures['test'].on_mouse_drag(x, y, dx, dy, buttons, modifiers)
2021-04-10 22:48:22 +08:00
pass
2021-08-13 12:25:29 +08:00
def on_mouse_press(self, x, y, button, modifiers) -> None:
2021-02-22 23:17:16 +08:00
if button == mouse.LEFT:
2021-08-24 22:31:52 +08:00
self.logger.debug(self.lang['mouse.press'].format([x, y], self.lang['mouse.left']))
2021-02-22 23:17:16 +08:00
elif button == mouse.RIGHT:
2021-08-24 22:31:52 +08:00
self.logger.debug(self.lang['mouse.press'].format([x, y], self.lang['mouse.right']))
self.textures['test']._sprite.rotation = random.randint(0, 360)
2021-08-24 22:31:52 +08:00
self.textures['test'].on_mouse_press(x, y, button, modifiers)
2021-08-13 12:25:29 +08:00
def on_mouse_release(self, x, y, button, modifiers) -> None:
self.logger.debug(tr.lang('window', 'mouse.release').format([x, y], tr.lang('window', 'mouse.right')))
2021-08-24 22:31:52 +08:00
self.textures['test'].on_mouse_release(x, y, button, modifiers)
2021-08-13 12:25:29 +08:00
def on_key_press(self, symbol, modifiers) -> None:
2021-02-22 23:17:16 +08:00
if symbol == key.ESCAPE and not (modifiers & ~(key.MOD_NUMLOCK |
key.MOD_CAPSLOCK |
key.MOD_SCROLLLOCK)):
self.dispatch_event('on_close')
2020-12-16 06:33:33 +08:00
2021-08-13 12:25:29 +08:00
def on_key_release(self, symbol, modifiers) -> None:
2020-12-16 06:33:33 +08:00
pass
2021-08-13 12:25:29 +08:00
def on_close(self) -> None:
self.run_input = False
# self.input_line.join()
2021-08-13 12:25:29 +08:00
config_file = configparser.ConfigParser()
config_file.read('configs/main.config')
config_file['window']['width'] = str(self.width)
config_file['window']['height'] = str(self.height)
config_file.write(open('configs/main.config', 'w', encoding='utf-8'))
2021-09-09 23:54:03 +08:00
super(ClientWindow, self).on_close()