component.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. import pygame
  2. import random
  3. class PygameButton:
  4. """
  5. 文字渲染按钮
  6. """
  7. def __init__(
  8. self, screen, text, relx, rely, font_size, bg_color,
  9. fg_color=(0,0,0), action=None, anchor='center', is_bold=True, fix_shape=None, bg_alpha=255,
  10. frosted_glass=False, blur_radius=4, glass_alpha=120, frame_radius=8, glass_surf_color=(255,255,255), background=None):
  11. self.screen = screen
  12. self.text = text
  13. self.lines = text.split('\n')
  14. self.font = pygame.font.SysFont("Microsoft JhengHei", font_size, bold=is_bold)
  15. # self.font = pygame.font.Font(r"res\font\SourceHanSerif-VF.ttc", font_size)
  16. # self.font = pygame.font.Font(r"res\font\SourceHanSerifCN-Bold.otf", font_size)
  17. # 毛玻璃相关参数
  18. self.frosted_glass = frosted_glass
  19. self.blur_radius = blur_radius
  20. self.glass_alpha = glass_alpha
  21. self.frame_radius = frame_radius
  22. self.background = background
  23. self.glass_surf_color = glass_surf_color
  24. # 普通模式颜色设置
  25. self._init_normal_colors(bg_color, bg_alpha)
  26. self.fg_color = fg_color
  27. self.action = action
  28. self.relx = relx
  29. self.rely = rely
  30. self.fix_shape = fix_shape
  31. self.anchor = anchor # 'center', 'topleft'
  32. self.hovered = False
  33. self._render()
  34. # 毛玻璃特效所需Surface
  35. if self.frosted_glass:
  36. self._init_frosted_glass()
  37. def _init_normal_colors(self, bg_color, bg_alpha):
  38. """初始化普通模式的背景颜色"""
  39. self.bg_color_normal = pygame.Color(bg_color)
  40. self.bg_color_normal.a = bg_alpha
  41. # 悬停颜色计算
  42. h = self.bg_color_normal
  43. hover_rgb = (
  44. max(0, int(h.r * 0.8)),
  45. max(0, int(h.g * 0.8)),
  46. max(0, int(h.b * 0.8)),
  47. )
  48. self.bg_color_hover = pygame.Color(*hover_rgb)
  49. self.bg_color_hover.a = bg_alpha
  50. def _init_frosted_glass(self):
  51. """初始化毛玻璃特效所需资源"""
  52. # 创建模糊用的临时surface
  53. self.blur_surface = pygame.Surface(
  54. (self.bg_rect.width//self.blur_radius,
  55. self.bg_rect.height//self.blur_radius),
  56. pygame.SRCALPHA
  57. )
  58. self.overlay_surf = pygame.Surface(
  59. (self.bg_rect.width, self.bg_rect.height),
  60. pygame.SRCALPHA
  61. )
  62. # self.overlay_surf.fill((255, 255, 255, self.glass_alpha))
  63. self.overlay_surf.fill((*self.glass_surf_color, self.glass_alpha))
  64. def _create_blurred_background(self, background):
  65. """创建模糊背景(毛玻璃特效核心)"""
  66. if not self.frosted_glass:
  67. return
  68. # 截取背景区域
  69. try:
  70. sub = background.subsurface(self.bg_rect)
  71. except ValueError:
  72. return
  73. # 快速缩放模糊算法
  74. scaled = pygame.transform.scale(
  75. sub,
  76. (self.bg_rect.w//self.blur_radius,
  77. self.bg_rect.h//self.blur_radius)
  78. )
  79. self.blur_surface = pygame.transform.smoothscale(
  80. scaled,
  81. (self.bg_rect.w, self.bg_rect.h)
  82. )
  83. def _render(self):
  84. # 渲染多行文本
  85. self.text_surfs = [self.font.render(line, True, self.fg_color) for line in self.lines]
  86. widths = [surf.get_width() for surf in self.text_surfs]
  87. heights = [surf.get_height() for surf in self.text_surfs]
  88. if self.fix_shape is None:
  89. total_width = max(widths)
  90. total_height = sum(heights) + (len(heights)-1) * 5
  91. else:
  92. total_width = self.fix_shape[0]
  93. total_height = self.fix_shape[1]
  94. sw, sh = self.screen.get_size()
  95. x = int(sw * self.relx)
  96. y = int(sh * self.rely)
  97. # 根据锚点决定位置
  98. if self.anchor == 'center':
  99. topleft = (x - total_width//2 - 10, y - total_height//2 - 5)
  100. elif self.anchor == 'topleft':
  101. topleft = (x, y)
  102. else:
  103. topleft = (x - total_width//2 - 10, y - total_height//2 - 5)
  104. self.bg_rect = pygame.Rect(topleft[0], topleft[1], total_width + 20, total_height + 10)
  105. # 计算每行文本位置
  106. self.text_positions = []
  107. offset_y = self.bg_rect.y + 5
  108. for surf in self.text_surfs:
  109. line_x = self.bg_rect.x + (self.bg_rect.width - surf.get_width())//2 if self.anchor=='center' else self.bg_rect.x + 10
  110. self.text_positions.append((line_x, offset_y))
  111. offset_y += surf.get_height() + 5
  112. if self.frosted_glass:
  113. self._init_frosted_glass()
  114. def draw(self):
  115. """新增background参数用于毛玻璃特效"""
  116. if self.frosted_glass and self.background is not None:
  117. # 毛玻璃模式
  118. self._draw_frosted_glass(self.background.bg_image)
  119. else:
  120. # 普通模式
  121. self._draw_normal()
  122. # 绘制文本(通用)
  123. for surf, pos in zip(self.text_surfs, self.text_positions):
  124. self.screen.blit(surf, pos)
  125. def _draw_normal(self):
  126. """普通按钮绘制"""
  127. color = self.bg_color_hover if self.hovered else self.bg_color_normal
  128. bg_surf = pygame.Surface(
  129. (self.bg_rect.width, self.bg_rect.height),
  130. pygame.SRCALPHA
  131. )
  132. bg_surf.fill(color)
  133. self.screen.blit(bg_surf, self.bg_rect.topleft)
  134. def _draw_frosted_glass(self, background):
  135. """毛玻璃特效绘制"""
  136. # 生成模糊背景
  137. self._create_blurred_background(background)
  138. # 绘制模糊层
  139. if not (self.hovered and self.action is not None):
  140. self.screen.blit(self.blur_surface, self.bg_rect.topleft)
  141. # 添加白色半透覆盖层
  142. self.screen.blit(self.overlay_surf, self.bg_rect.topleft)
  143. # 绘制边框
  144. pygame.draw.rect(
  145. self.screen,
  146. (63, 63, 63, 31),
  147. self.bg_rect,
  148. 1,
  149. border_radius=self.frame_radius
  150. )
  151. def handle_event(self, event):
  152. if event.type == pygame.MOUSEMOTION:
  153. self.hovered = self.bg_rect.collidepoint(event.pos)
  154. elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
  155. if self.hovered:
  156. if self.action:
  157. self.action()
  158. class PygameButtonBackIMG:
  159. """
  160. 一个仅使用图片作为按钮的类,不含文字渲染,图片本身包含文字。
  161. - default_img_path: 默认状态下的背景图路径
  162. - hover_img_path: 悬停状态下的背景图路径
  163. """
  164. def __init__(self, menu, screen, relx, rely,
  165. default_img_path, hover_img_path,
  166. action=None, hover_in_action=None, hover_out_action=None,
  167. anchor='center'):
  168. self.menu = menu
  169. self.screen = screen
  170. # 加载按钮图片
  171. self.default_img = pygame.image.load(default_img_path).convert_alpha()
  172. self.hover_img = pygame.image.load(hover_img_path).convert_alpha()
  173. self.action = action
  174. self.hover_in_action = hover_in_action
  175. self.hover_out_action = hover_out_action
  176. self.relx = relx
  177. self.rely = rely
  178. self.anchor = anchor # 'center' 或 'topleft'
  179. self.hovered = False
  180. # 按钮尺寸使用图片原始尺寸
  181. self.width, self.height = self.default_img.get_size()
  182. self.spawn_timer = 0
  183. # 计算按钮位置
  184. sw, sh = self.screen.get_size()
  185. x = int(sw * self.relx)
  186. y = int(sh * self.rely)
  187. self.x, self.y = x, y
  188. if self.anchor == 'center':
  189. topleft = (x - self.width//2, y - self.height//2)
  190. else:
  191. topleft = (x, y)
  192. self.bg_rect = pygame.Rect(topleft[0], topleft[1], self.width, self.height)
  193. def draw(self):
  194. # (实时刷新) 根据悬停状态绘制对应图片
  195. img = self.hover_img if self.hovered else self.default_img
  196. self.screen.blit(img, self.bg_rect.topleft)
  197. if self.hovered:
  198. self.spawn_timer += 1
  199. if self.spawn_timer >= 10:
  200. self.spawn_timer = 0
  201. for _ in range(10):
  202. self.menu.particles.append(ButtonParticle(self.x, self.y))
  203. def handle_event(self, event):
  204. if event.type == pygame.MOUSEMOTION:
  205. # 先记录上一次的悬停状态
  206. was_hovered = self.hovered
  207. # 更新当前悬停状态
  208. now_hovered = self.bg_rect.collidepoint(event.pos)
  209. self.hovered = now_hovered
  210. # 鼠标刚进入区域
  211. if not was_hovered and now_hovered and self.hover_in_action:
  212. self.hover_in_action()
  213. # 鼠标刚离开区域
  214. elif was_hovered and not now_hovered and self.hover_out_action:
  215. self.hover_out_action()
  216. elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
  217. if self.hovered and self.action:
  218. self.action()
  219. class Particle:
  220. def __init__(self, x, y):
  221. self.x = x
  222. self.y = y
  223. self.radius = random.randint(1, 3)
  224. # self.color = (200, 200, 200)
  225. self.color = (170, 188, 157)
  226. # 垂直速度
  227. self.speed_y = random.uniform(0.3, 0.6)
  228. # 水平速度,模拟风吹
  229. self.speed_x = random.uniform(-0.3, 0.3)
  230. # 透明度和生命周期
  231. self.alpha = 191
  232. self.life = random.randint(100, 600) # 寿命更长
  233. self.surface = pygame.Surface((self.radius*2, self.radius*2), pygame.SRCALPHA)
  234. def update(self):
  235. # 更新位置
  236. self.y -= self.speed_y
  237. self.x += self.speed_x
  238. self.speed_y += random.uniform(0, 0.01)
  239. self.speed_x += random.uniform(-0.06, 0.06)
  240. # 减缓透明度下降速度
  241. self.life -= 1
  242. self.alpha = max(0, int(191 * min(1., self.life / 300)))
  243. # 重绘粒子
  244. self.surface.fill((0,0,0,0))
  245. pygame.draw.circle(
  246. self.surface,
  247. (self.color[0], self.color[1], self.color[2], self.alpha),
  248. (self.radius, self.radius),
  249. self.radius
  250. )
  251. def draw(self, screen):
  252. screen.blit(self.surface, (self.x - self.radius, self.y - self.radius))
  253. def is_alive(self):
  254. return self.life > 0 and self.alpha > 0
  255. class ButtonParticle:
  256. def __init__(self, x, y):
  257. self.x = x
  258. self.y = y
  259. self.radius = random.randint(1, 3)
  260. # self.color = (200, 200, 200)
  261. # self.color = (170, 188, 157)
  262. self.color = (244, 213, 97)
  263. # 垂直速度
  264. self.speed_y = random.uniform(-5, 5)
  265. # 水平速度,模拟风吹
  266. self.speed_x = random.uniform(-10, 10)
  267. # 透明度和生命周期
  268. self.alpha = 255
  269. self.fix_life = 30
  270. self.life = random.randint(10, 20) # 寿命更长
  271. self.surface = pygame.Surface((self.radius*2, self.radius*2), pygame.SRCALPHA)
  272. def update(self):
  273. # 更新位置
  274. self.y -= self.speed_y
  275. self.x += self.speed_x
  276. self.speed_y *= 0.9
  277. self.speed_x *= 0.9
  278. # 减缓透明度下降速度
  279. self.fix_life -= 1
  280. if self.fix_life < 0:
  281. self.life -= 1
  282. self.alpha = max(0, int(191 * min(1., self.life / 30)))
  283. # 重绘粒子
  284. self.surface.fill((0,0,0,0))
  285. pygame.draw.circle(
  286. self.surface,
  287. (self.color[0], self.color[1], self.color[2], self.alpha),
  288. (self.radius, self.radius),
  289. self.radius
  290. )
  291. def draw(self, screen):
  292. screen.blit(self.surface, (self.x - self.radius, self.y - self.radius))
  293. def is_alive(self):
  294. return self.life > 0 and self.alpha > 0