| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273 |
- import os
- import time
- import pygame
- import pygame.freetype as freetype
- from typing import List
- from client_local.ui.font import get_font
- # Initialize Pygame and Clock
- # pygame.init()
- # screen = pygame.display.set_mode((800, 600))
- # pygame.display.set_caption("Chat Optimization Demo")
- # clock = pygame.time.Clock()
- # Preload font once
- Current_Path = os.getcwd()
- # FONT_PATH = r"\res\font\simsun.ttc"
- # FONT_PATH = r"\res\font\SourceHanSerifCN-Bold.otf"
- FONT_PATH = Current_Path + r"\res\font\hk4e_zh-cn.ttf"
- # FONT_PATH = r"\res\font\SourceHanSerif-VF.ttc"
- _font = None
- _font_small = None
- def init_fonts():
- global _font, _font_small
- if not freetype.get_init():
- freetype.init()
- _font = get_font(font_name="hk4e_zh-cn.ttf", size=14)
- _font_small = get_font(font_name="hk4e_zh-cn.ttf", size=12)
- class FontManager:
- def __init__(self) -> None:
- self._inited = False
- self._font = None
- self._font_small = None
- self._cache = {} # key -> pygame.Surface
- self._cache_order = []
- self._cache_max = 256
- def init(self, font_path=FONT_PATH) -> None:
- # Must be called after pygame.init(); best after display.set_mode()
- if not freetype.get_init():
- freetype.init()
- self._font = freetype.Font(font_path, 14)
- self._font_small = freetype.Font(font_path, 12)
- self._inited = True
- # surfaces depend on display pixel format; safest to drop old cache
- self._cache.clear()
- self._cache_order.clear()
- def _cache_put(self, key, surf: pygame.Surface) -> pygame.Surface:
- self._cache[key] = surf
- self._cache_order.append(key)
- if len(self._cache_order) > self._cache_max:
- old = self._cache_order.pop(0)
- self._cache.pop(old, None)
- return surf
- def render_small_cached(self, text, colour, shadow=True):
- if not self._inited:
- raise RuntimeError("FontManager not initialized. Call font_mgr.init(...) after pygame init/display set.")
- key = ("small", text, tuple(colour), shadow)
- hit = self._cache.get(key)
- if hit is not None:
- return hit
- # Render once, then combine into ONE surface (1 blit per message)
- if shadow:
- shadow_surf, _ = self._font_small.render(text, fgcolor=(0, 0, 0))
- text_surf, _ = self._font_small.render(text, fgcolor=colour)
- w = text_surf.get_width() + (1 if shadow else 0)
- h = text_surf.get_height() + (1 if shadow else 0)
- combined = pygame.Surface((w, h), pygame.SRCALPHA, 32)
- if shadow:
- combined.blit(shadow_surf, (1, 1))
- combined.blit(text_surf, (0, 0))
- # Convert AFTER display.set_mode for faster blits
- if pygame.display.get_surface() is not None:
- combined = combined.convert_alpha()
- return self._cache_put(key, combined)
- def render_normal_cached(self, text, colour, shadow=True):
- if not self._inited:
- raise RuntimeError("FontManager not initialized. Call font_mgr.init(...) after pygame init/display set.")
- key = ("small", text, tuple(colour), shadow)
- hit = self._cache.get(key)
- if hit is not None:
- return hit
- # Render once, then combine into ONE surface (1 blit per message)
- if shadow:
- shadow_surf, _ = self._font.render(text, fgcolor=(0, 0, 0))
- text_surf, _ = self._font.render(text, fgcolor=colour)
- w = text_surf.get_width() + (1 if shadow else 0)
- h = text_surf.get_height() + (1 if shadow else 0)
- combined = pygame.Surface((w, h), pygame.SRCALPHA, 32)
- if shadow:
- combined.blit(shadow_surf, (1, 1))
- combined.blit(text_surf, (0, 0))
- # Convert AFTER display.set_mode for faster blits
- if pygame.display.get_surface() is not None:
- combined = combined.convert_alpha()
- return self._cache_put(key, combined)
- font_mgr = FontManager()
- class Message:
- def __init__(self, sender: str, text: str, duration_ms: int = 20000, colour: tuple = (255, 255, 255)):
- self.sender = sender
- self.text = text
- self.start = pygame.time.get_ticks()
- self.duration = duration_ms
- content = f"{sender}:{text}" if text else sender
- self.surf = font_mgr.render_small_cached(content, tuple(colour), shadow=True)
- # self.surf = font_mgr.render_normal_cached(content, tuple(colour), shadow=True)
- def expired(self) -> bool:
- return pygame.time.get_ticks() - self.start > self.duration
- class TextInput:
- FONT_NAMES = ",".join([
- r'res\font\simsun.ttc',
- "notosanscjktcregular",
- "notosansmonocjktcregular",
- "notosansregular,",
- "microsoftjhengheimicrosoftjhengheiuilight",
- "microsoftyaheimicrosoftyaheiuilight",
- "msgothicmsuigothicmspgothic",
- "msmincho",
- "Arial",
- ])
- def __init__(self, prompt: str, pos, screen_dimensions, print_event: bool, text_color="white", entryObj=None) -> None:
- self.prompt = prompt
- self.print_event = print_event
- self.CHAT_BOX_POS = pygame.Rect(pos, (screen_dimensions[1], 40))
- self.entryObj = entryObj
- self._ime_editing = False
- self._ime_text = ""
- self._ime_text_pos = 0
- self._ime_editing_text = ""
- self._ime_editing_pos = 0
- self.font = _font
- self.font_small = _font_small
- self.text_color = text_color
- def update(self, events=None) -> None:
- if events is None:
- events = []
- if self.entryObj and not self.entryObj.show:
- return
- for event in events:
- if event.type == pygame.KEYDOWN:
- if self.print_event:
- print(event)
- if self._ime_editing:
- if not self._ime_editing_text:
- self._ime_editing = False
- continue
- key = event.key
- if key == pygame.K_BACKSPACE and self._ime_text_pos > 0:
- self._ime_text = self._ime_text[:self._ime_text_pos - 1] + self._ime_text[self._ime_text_pos:]
- self._ime_text_pos -= 1
- elif key == pygame.K_DELETE:
- self._ime_text = self._ime_text[:self._ime_text_pos] + self._ime_text[self._ime_text_pos + 1:]
- elif key == pygame.K_LEFT:
- self._ime_text_pos = max(0, self._ime_text_pos - 1)
- elif key == pygame.K_RIGHT:
- self._ime_text_pos = min(len(self._ime_text), self._ime_text_pos + 1)
- elif key in (pygame.K_RETURN, pygame.K_KP_ENTER) and self._ime_text:
- if self.entryObj:
- self.entryObj.new_message(sender="玩家", message=self._ime_text)
- self._ime_text = ""
- self._ime_text_pos = 0
- elif event.type == pygame.TEXTEDITING:
- self._ime_editing = True
- self._ime_editing_text = event.text
- self._ime_editing_pos = event.start
- elif event.type == pygame.TEXTINPUT:
- self._ime_editing = False
- self._ime_text = self._ime_text[:self._ime_text_pos] + event.text + self._ime_text[self._ime_text_pos:]
- self._ime_text_pos += len(event.text)
- def draw(self, screen: pygame.Surface) -> None:
- start = self.CHAT_BOX_POS.copy()
- left = self.prompt + self._ime_text[:self._ime_text_pos]
- mid = self._ime_editing_text[:self._ime_editing_pos] + "|" + self._ime_editing_text[self._ime_editing_pos:]
- right = self._ime_text[self._ime_text_pos:]
- surf_l, _ = self.font.render(left, fgcolor=self.text_color)
- screen.blit(surf_l, (start.x, start.y)); start.x += surf_l.get_width()
- surf_m, _ = self.font.render(mid, fgcolor=self.text_color, style=freetype.STYLE_UNDERLINE)
- screen.blit(surf_m, (start.x, start.y)); start.x += surf_m.get_width()
- surf_r, _ = self.font.render(right, fgcolor=self.text_color)
- screen.blit(surf_r, (start.x, start.y))
- class InputEntry(pygame.sprite.Sprite):
- def __init__(self):
- super().__init__()
- self.image = pygame.image.load(f"{Current_Path}/res/img/ui/common/chat_entry.png").convert_alpha()
- self.rect = self.image.get_rect(topleft=(250, 500))
- self.show = False
- self.text_input = TextInput("", (self.rect.x + 20, self.rect.y + 5), self.rect.size, False, "black", self)
- self.messages: List[Message] = [
- Message("QQTPVE制作组", "重开游戏按0, 更多设置详见主菜单之游戏设置", duration_ms=20000),
- Message("QQTPVE制作组", "单机作者: 永恒, 联机作者: KY, 运营: 100の雨女", duration_ms=20000),
- Message("QQTPVE制作组", "欢迎使用单机版探险! 本项目完全免费,任何售卖渠道均为剽窃! 最新官方群号956553296!", duration_ms=20000),
- ]
- self.max_msgs = 10
- self.y_gap = 20
- self.last_msg_time = time.time()
- def update(self, events=None):
- if events is None:
- events = []
- if self.show:
- self.text_input.update(events)
- # 清理过期消息
- self.messages = [m for m in self.messages if not m.expired()]
- if time.time() - self.last_msg_time > 5: # 每5秒上移一行
- self.new_message()
- def draw(self, screen: pygame.Surface):
- if self.show:
- screen.blit(self.image, self.rect.topleft)
- self.text_input.draw(screen)
- x0, y0 = 100, 480
- for i, msg in enumerate(self.messages):
- dy = i * self.y_gap
- screen.blit(msg.surf, (x0, y0 - dy))
- def new_message(self, sender='', message='', colour=(255, 255, 255)):
- self.messages.insert(0, Message(sender, message, colour=colour))
- if len(self.messages) > self.max_msgs:
- self.messages.pop()
- self.last_msg_time = time.time()
- class InputLevel(pygame.sprite.Sprite):
- def __init__(self):
- super().__init__()
- self.image = pygame.image.load(f"{Current_Path}/res/img/ui/common/chat_entry.png").convert_alpha()
- self.rect = self.image.get_rect(topleft=(250, 500))
- self.show = False
- self.text_input = TextInput("", (self.rect.x + 20, self.rect.y + 5), self.rect.size, False, "black", self)
- self.messages: List[Message] = []
- self.max_msgs = 10
- self.y_gap = 20
- self.last_msg_time = time.time()
- def update(self, events=None):
- if events is None:
- events = []
- if self.show:
- self.text_input.update(events)
- self.messages = [m for m in self.messages if not m.expired()]
- if time.time() - self.last_msg_time > 5: # 每5秒上移一行
- self.new_message()
- def draw(self, screen: pygame.Surface):
- x0, y0 = 100, 480
- for i, msg in enumerate(self.messages):
- dy = i * self.y_gap
- screen.blit(msg.surf, (x0, y0 - dy))
- def new_message(self, sender='', message='', colour=(255, 255, 255)):
- self.messages.insert(0, Message(sender, message, colour=colour))
- if len(self.messages) > self.max_msgs:
- self.messages.pop()
- self.last_msg_time = time.time()
|