message_input.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. import os
  2. import time
  3. import pygame
  4. import pygame.freetype as freetype
  5. from typing import List
  6. from client_local.ui.font import get_font
  7. # Initialize Pygame and Clock
  8. # pygame.init()
  9. # screen = pygame.display.set_mode((800, 600))
  10. # pygame.display.set_caption("Chat Optimization Demo")
  11. # clock = pygame.time.Clock()
  12. # Preload font once
  13. Current_Path = os.getcwd()
  14. # FONT_PATH = r"\res\font\simsun.ttc"
  15. # FONT_PATH = r"\res\font\SourceHanSerifCN-Bold.otf"
  16. FONT_PATH = Current_Path + r"\res\font\hk4e_zh-cn.ttf"
  17. # FONT_PATH = r"\res\font\SourceHanSerif-VF.ttc"
  18. _font = None
  19. _font_small = None
  20. def init_fonts():
  21. global _font, _font_small
  22. if not freetype.get_init():
  23. freetype.init()
  24. _font = get_font(font_name="hk4e_zh-cn.ttf", size=14)
  25. _font_small = get_font(font_name="hk4e_zh-cn.ttf", size=12)
  26. class FontManager:
  27. def __init__(self) -> None:
  28. self._inited = False
  29. self._font = None
  30. self._font_small = None
  31. self._cache = {} # key -> pygame.Surface
  32. self._cache_order = []
  33. self._cache_max = 256
  34. def init(self, font_path=FONT_PATH) -> None:
  35. # Must be called after pygame.init(); best after display.set_mode()
  36. if not freetype.get_init():
  37. freetype.init()
  38. self._font = freetype.Font(font_path, 14)
  39. self._font_small = freetype.Font(font_path, 12)
  40. self._inited = True
  41. # surfaces depend on display pixel format; safest to drop old cache
  42. self._cache.clear()
  43. self._cache_order.clear()
  44. def _cache_put(self, key, surf: pygame.Surface) -> pygame.Surface:
  45. self._cache[key] = surf
  46. self._cache_order.append(key)
  47. if len(self._cache_order) > self._cache_max:
  48. old = self._cache_order.pop(0)
  49. self._cache.pop(old, None)
  50. return surf
  51. def render_small_cached(self, text, colour, shadow=True):
  52. if not self._inited:
  53. raise RuntimeError("FontManager not initialized. Call font_mgr.init(...) after pygame init/display set.")
  54. key = ("small", text, tuple(colour), shadow)
  55. hit = self._cache.get(key)
  56. if hit is not None:
  57. return hit
  58. # Render once, then combine into ONE surface (1 blit per message)
  59. if shadow:
  60. shadow_surf, _ = self._font_small.render(text, fgcolor=(0, 0, 0))
  61. text_surf, _ = self._font_small.render(text, fgcolor=colour)
  62. w = text_surf.get_width() + (1 if shadow else 0)
  63. h = text_surf.get_height() + (1 if shadow else 0)
  64. combined = pygame.Surface((w, h), pygame.SRCALPHA, 32)
  65. if shadow:
  66. combined.blit(shadow_surf, (1, 1))
  67. combined.blit(text_surf, (0, 0))
  68. # Convert AFTER display.set_mode for faster blits
  69. if pygame.display.get_surface() is not None:
  70. combined = combined.convert_alpha()
  71. return self._cache_put(key, combined)
  72. def render_normal_cached(self, text, colour, shadow=True):
  73. if not self._inited:
  74. raise RuntimeError("FontManager not initialized. Call font_mgr.init(...) after pygame init/display set.")
  75. key = ("small", text, tuple(colour), shadow)
  76. hit = self._cache.get(key)
  77. if hit is not None:
  78. return hit
  79. # Render once, then combine into ONE surface (1 blit per message)
  80. if shadow:
  81. shadow_surf, _ = self._font.render(text, fgcolor=(0, 0, 0))
  82. text_surf, _ = self._font.render(text, fgcolor=colour)
  83. w = text_surf.get_width() + (1 if shadow else 0)
  84. h = text_surf.get_height() + (1 if shadow else 0)
  85. combined = pygame.Surface((w, h), pygame.SRCALPHA, 32)
  86. if shadow:
  87. combined.blit(shadow_surf, (1, 1))
  88. combined.blit(text_surf, (0, 0))
  89. # Convert AFTER display.set_mode for faster blits
  90. if pygame.display.get_surface() is not None:
  91. combined = combined.convert_alpha()
  92. return self._cache_put(key, combined)
  93. font_mgr = FontManager()
  94. class Message:
  95. def __init__(self, sender: str, text: str, duration_ms: int = 20000, colour: tuple = (255, 255, 255)):
  96. self.sender = sender
  97. self.text = text
  98. self.start = pygame.time.get_ticks()
  99. self.duration = duration_ms
  100. content = f"{sender}:{text}" if text else sender
  101. self.surf = font_mgr.render_small_cached(content, tuple(colour), shadow=True)
  102. # self.surf = font_mgr.render_normal_cached(content, tuple(colour), shadow=True)
  103. def expired(self) -> bool:
  104. return pygame.time.get_ticks() - self.start > self.duration
  105. class TextInput:
  106. FONT_NAMES = ",".join([
  107. r'res\font\simsun.ttc',
  108. "notosanscjktcregular",
  109. "notosansmonocjktcregular",
  110. "notosansregular,",
  111. "microsoftjhengheimicrosoftjhengheiuilight",
  112. "microsoftyaheimicrosoftyaheiuilight",
  113. "msgothicmsuigothicmspgothic",
  114. "msmincho",
  115. "Arial",
  116. ])
  117. def __init__(self, prompt: str, pos, screen_dimensions, print_event: bool, text_color="white", entryObj=None) -> None:
  118. self.prompt = prompt
  119. self.print_event = print_event
  120. self.CHAT_BOX_POS = pygame.Rect(pos, (screen_dimensions[1], 40))
  121. self.entryObj = entryObj
  122. self._ime_editing = False
  123. self._ime_text = ""
  124. self._ime_text_pos = 0
  125. self._ime_editing_text = ""
  126. self._ime_editing_pos = 0
  127. self.font = _font
  128. self.font_small = _font_small
  129. self.text_color = text_color
  130. def update(self, events=None) -> None:
  131. if events is None:
  132. events = []
  133. if self.entryObj and not self.entryObj.show:
  134. return
  135. for event in events:
  136. if event.type == pygame.KEYDOWN:
  137. if self.print_event:
  138. print(event)
  139. if self._ime_editing:
  140. if not self._ime_editing_text:
  141. self._ime_editing = False
  142. continue
  143. key = event.key
  144. if key == pygame.K_BACKSPACE and self._ime_text_pos > 0:
  145. self._ime_text = self._ime_text[:self._ime_text_pos - 1] + self._ime_text[self._ime_text_pos:]
  146. self._ime_text_pos -= 1
  147. elif key == pygame.K_DELETE:
  148. self._ime_text = self._ime_text[:self._ime_text_pos] + self._ime_text[self._ime_text_pos + 1:]
  149. elif key == pygame.K_LEFT:
  150. self._ime_text_pos = max(0, self._ime_text_pos - 1)
  151. elif key == pygame.K_RIGHT:
  152. self._ime_text_pos = min(len(self._ime_text), self._ime_text_pos + 1)
  153. elif key in (pygame.K_RETURN, pygame.K_KP_ENTER) and self._ime_text:
  154. if self.entryObj:
  155. self.entryObj.new_message(sender="玩家", message=self._ime_text)
  156. self._ime_text = ""
  157. self._ime_text_pos = 0
  158. elif event.type == pygame.TEXTEDITING:
  159. self._ime_editing = True
  160. self._ime_editing_text = event.text
  161. self._ime_editing_pos = event.start
  162. elif event.type == pygame.TEXTINPUT:
  163. self._ime_editing = False
  164. self._ime_text = self._ime_text[:self._ime_text_pos] + event.text + self._ime_text[self._ime_text_pos:]
  165. self._ime_text_pos += len(event.text)
  166. def draw(self, screen: pygame.Surface) -> None:
  167. start = self.CHAT_BOX_POS.copy()
  168. left = self.prompt + self._ime_text[:self._ime_text_pos]
  169. mid = self._ime_editing_text[:self._ime_editing_pos] + "|" + self._ime_editing_text[self._ime_editing_pos:]
  170. right = self._ime_text[self._ime_text_pos:]
  171. surf_l, _ = self.font.render(left, fgcolor=self.text_color)
  172. screen.blit(surf_l, (start.x, start.y)); start.x += surf_l.get_width()
  173. surf_m, _ = self.font.render(mid, fgcolor=self.text_color, style=freetype.STYLE_UNDERLINE)
  174. screen.blit(surf_m, (start.x, start.y)); start.x += surf_m.get_width()
  175. surf_r, _ = self.font.render(right, fgcolor=self.text_color)
  176. screen.blit(surf_r, (start.x, start.y))
  177. class InputEntry(pygame.sprite.Sprite):
  178. def __init__(self):
  179. super().__init__()
  180. self.image = pygame.image.load(f"{Current_Path}/res/img/ui/common/chat_entry.png").convert_alpha()
  181. self.rect = self.image.get_rect(topleft=(250, 500))
  182. self.show = False
  183. self.text_input = TextInput("", (self.rect.x + 20, self.rect.y + 5), self.rect.size, False, "black", self)
  184. self.messages: List[Message] = [
  185. Message("QQTPVE制作组", "重开游戏按0, 更多设置详见主菜单之游戏设置", duration_ms=20000),
  186. Message("QQTPVE制作组", "单机作者: 永恒, 联机作者: KY, 运营: 100の雨女", duration_ms=20000),
  187. Message("QQTPVE制作组", "欢迎使用单机版探险! 本项目完全免费,任何售卖渠道均为剽窃! 最新官方群号956553296!", duration_ms=20000),
  188. ]
  189. self.max_msgs = 10
  190. self.y_gap = 20
  191. self.last_msg_time = time.time()
  192. def update(self, events=None):
  193. if events is None:
  194. events = []
  195. if self.show:
  196. self.text_input.update(events)
  197. # 清理过期消息
  198. self.messages = [m for m in self.messages if not m.expired()]
  199. if time.time() - self.last_msg_time > 5: # 每5秒上移一行
  200. self.new_message()
  201. def draw(self, screen: pygame.Surface):
  202. if self.show:
  203. screen.blit(self.image, self.rect.topleft)
  204. self.text_input.draw(screen)
  205. x0, y0 = 100, 480
  206. for i, msg in enumerate(self.messages):
  207. dy = i * self.y_gap
  208. screen.blit(msg.surf, (x0, y0 - dy))
  209. def new_message(self, sender='', message='', colour=(255, 255, 255)):
  210. self.messages.insert(0, Message(sender, message, colour=colour))
  211. if len(self.messages) > self.max_msgs:
  212. self.messages.pop()
  213. self.last_msg_time = time.time()
  214. class InputLevel(pygame.sprite.Sprite):
  215. def __init__(self):
  216. super().__init__()
  217. self.image = pygame.image.load(f"{Current_Path}/res/img/ui/common/chat_entry.png").convert_alpha()
  218. self.rect = self.image.get_rect(topleft=(250, 500))
  219. self.show = False
  220. self.text_input = TextInput("", (self.rect.x + 20, self.rect.y + 5), self.rect.size, False, "black", self)
  221. self.messages: List[Message] = []
  222. self.max_msgs = 10
  223. self.y_gap = 20
  224. self.last_msg_time = time.time()
  225. def update(self, events=None):
  226. if events is None:
  227. events = []
  228. if self.show:
  229. self.text_input.update(events)
  230. self.messages = [m for m in self.messages if not m.expired()]
  231. if time.time() - self.last_msg_time > 5: # 每5秒上移一行
  232. self.new_message()
  233. def draw(self, screen: pygame.Surface):
  234. x0, y0 = 100, 480
  235. for i, msg in enumerate(self.messages):
  236. dy = i * self.y_gap
  237. screen.blit(msg.surf, (x0, y0 - dy))
  238. def new_message(self, sender='', message='', colour=(255, 255, 255)):
  239. self.messages.insert(0, Message(sender, message, colour=colour))
  240. if len(self.messages) > self.max_msgs:
  241. self.messages.pop()
  242. self.last_msg_time = time.time()