| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193 |
- import os
- import time
- import pygame
- import pygame.freetype as freetype
- from typing import List
- # 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 = freetype.Font(FONT_PATH, 14)
- _font_small = freetype.Font(FONT_PATH, 12)
- 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.shadow_surf, _ = _font_small.render(content, fgcolor=(0, 0, 0))
- self.text_surf, _ = _font_small.render(content, fgcolor=colour)
- 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.shadow_surf, (x0 + 1, y0 - dy + 1))
- screen.blit(msg.text_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):
- 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.shadow_surf, (x0 + 1, y0 - dy + 1))
- screen.blit(msg.text_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()
|