component.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. import pygame
  2. import random
  3. from game.sound import sound_player
  4. # hk4e_zh_cn12 = pygame.font.Font(r"res\font\hk4e_zh-cn.ttf", 12)
  5. font_dict = dict() # {("Microsoft JhengHei", 12, bold): pygame.font}
  6. def get_font(font_name, size, font_type='sys', bold=False):
  7. global font_dict
  8. load_font = font_dict.get((font_name, size, bold), None)
  9. if load_font is None:
  10. if font_type == 'sys':
  11. font_dict[(font_name, size, bold)] = pygame.font.SysFont(font_name, size, bold=bold)
  12. else:
  13. font_dict[(font_name, size, bold)] = pygame.font.Font(f"res\\font\\{font_name}", size)
  14. load_font = font_dict.get((font_name, size, bold), None)
  15. return load_font
  16. class PygameButton:
  17. """
  18. 文字渲染按钮
  19. """
  20. def __init__(
  21. self, screen, text, relx, rely, font_size, bg_color,
  22. fg_color=(0,0,0), action=None, anchor='center', is_bold=True, fix_shape=None, bg_alpha=255,
  23. frosted_glass=False, blur_radius=4, glass_alpha=120, frame_radius=8, glass_surf_color=(255,255,255), background=None,
  24. wait_notification=False, notify_action=None
  25. ):
  26. self.screen = screen
  27. self.text = text
  28. self.lines = text.split('\n')
  29. # self.font = get_font("Microsoft JhengHei", font_size, font_type='sys', bold=is_bold)
  30. # self.font = get_font("SourceHanSerifCN-Bold.otf", font_size, font_type='local', bold=is_bold)
  31. self.font = get_font("hk4e_zh-cn.ttf", font_size, font_type='local', bold=is_bold)
  32. # self.font = pygame.font.SysFont("Microsoft JhengHei", font_size, bold=is_bold)
  33. # self.font = pygame.font.Font(r"res\font\SourceHanSerif-VF.ttc", font_size)
  34. # self.font = pygame.font.Font(r"res\font\SourceHanSerifCN-Bold.otf", font_size)
  35. # 监听者模式参数
  36. self.wait_notification = wait_notification
  37. self.new_notification = None
  38. self.notify_action = notify_action
  39. # 毛玻璃相关参数
  40. self.frosted_glass = frosted_glass
  41. self.blur_radius = blur_radius
  42. self.glass_alpha = glass_alpha
  43. self.frame_radius = frame_radius
  44. self.background = background
  45. self.glass_surf_color = glass_surf_color
  46. # 普通模式颜色设置
  47. self._init_normal_colors(bg_color, bg_alpha)
  48. self.fg_color = fg_color
  49. self.action = action
  50. self.relx = relx
  51. self.rely = rely
  52. self.fix_shape = fix_shape
  53. self.anchor = anchor # 'center', 'topleft'
  54. self.hovered = False
  55. self._render()
  56. # 毛玻璃特效所需Surface
  57. if self.frosted_glass:
  58. self._init_frosted_glass()
  59. def _init_normal_colors(self, bg_color, bg_alpha):
  60. """初始化普通模式的背景颜色"""
  61. self.bg_color_normal = pygame.Color(bg_color)
  62. self.bg_color_normal.a = bg_alpha
  63. # 悬停颜色计算
  64. h = self.bg_color_normal
  65. hover_rgb = (
  66. max(0, int(h.r * 0.8)),
  67. max(0, int(h.g * 0.8)),
  68. max(0, int(h.b * 0.8)),
  69. )
  70. self.bg_color_hover = pygame.Color(*hover_rgb)
  71. self.bg_color_hover.a = bg_alpha
  72. def _init_frosted_glass(self):
  73. """初始化毛玻璃特效所需资源"""
  74. # 创建模糊用的临时surface
  75. self.blur_surface = pygame.Surface(
  76. (self.bg_rect.width//self.blur_radius,
  77. self.bg_rect.height//self.blur_radius),
  78. pygame.SRCALPHA
  79. )
  80. self.overlay_surf = pygame.Surface(
  81. (self.bg_rect.width, self.bg_rect.height),
  82. pygame.SRCALPHA
  83. )
  84. # self.overlay_surf.fill((255, 255, 255, self.glass_alpha))
  85. self.overlay_surf.fill((*self.glass_surf_color, self.glass_alpha))
  86. def _create_blurred_background(self, background):
  87. """创建模糊背景(毛玻璃特效核心)"""
  88. if not self.frosted_glass:
  89. return
  90. # 截取背景区域
  91. try:
  92. sub = background.subsurface(self.bg_rect)
  93. except ValueError:
  94. return
  95. # 快速缩放模糊算法
  96. scaled = pygame.transform.scale(
  97. sub,
  98. (self.bg_rect.w//self.blur_radius,
  99. self.bg_rect.h//self.blur_radius)
  100. )
  101. self.blur_surface = pygame.transform.smoothscale(
  102. scaled,
  103. (self.bg_rect.w, self.bg_rect.h)
  104. )
  105. def _render(self):
  106. # 渲染多行文本
  107. self.text_surfs = [self.font.render(line, True, self.fg_color) for line in self.lines]
  108. widths = [surf.get_width() for surf in self.text_surfs]
  109. heights = [surf.get_height() for surf in self.text_surfs]
  110. if self.fix_shape is None:
  111. total_width = max(widths)
  112. total_height = sum(heights) + (len(heights)-1) * 5
  113. else:
  114. total_width = self.fix_shape[0]
  115. total_height = self.fix_shape[1]
  116. sw, sh = self.screen.get_size()
  117. x = int(sw * self.relx)
  118. y = int(sh * self.rely)
  119. # 根据锚点决定位置
  120. if self.anchor == 'center':
  121. topleft = (x - total_width//2 - 10, y - total_height//2 - 5)
  122. elif self.anchor == 'topleft':
  123. topleft = (x, y)
  124. else:
  125. topleft = (x - total_width//2 - 10, y - total_height//2 - 5)
  126. self.bg_rect = pygame.Rect(topleft[0], topleft[1], total_width + 20, total_height + 10)
  127. # 计算每行文本位置
  128. self.text_positions = []
  129. offset_y = self.bg_rect.y + 5
  130. for surf in self.text_surfs:
  131. line_x = self.bg_rect.x + (self.bg_rect.width - surf.get_width())//2 if self.anchor=='center' else self.bg_rect.x + 10
  132. self.text_positions.append((line_x, offset_y))
  133. offset_y += surf.get_height() + 5
  134. if self.frosted_glass:
  135. self._init_frosted_glass()
  136. def draw(self):
  137. """新增background参数用于毛玻璃特效"""
  138. if self.frosted_glass and self.background is not None:
  139. # 毛玻璃模式
  140. self._draw_frosted_glass(self.background.bg_image)
  141. else:
  142. # 普通模式
  143. self._draw_normal()
  144. # 绘制文本(通用)
  145. for surf, pos in zip(self.text_surfs, self.text_positions):
  146. self.screen.blit(surf, pos)
  147. def _draw_normal(self):
  148. """普通按钮绘制"""
  149. color = self.bg_color_hover if self.hovered else self.bg_color_normal
  150. bg_surf = pygame.Surface(
  151. (self.bg_rect.width, self.bg_rect.height),
  152. pygame.SRCALPHA
  153. )
  154. bg_surf.fill(color)
  155. self.screen.blit(bg_surf, self.bg_rect.topleft)
  156. def _draw_frosted_glass(self, background):
  157. """毛玻璃特效绘制"""
  158. # 生成模糊背景
  159. self._create_blurred_background(background)
  160. # 绘制模糊层
  161. if not (self.hovered and self.action is not None):
  162. self.screen.blit(self.blur_surface, self.bg_rect.topleft)
  163. # 添加白色半透覆盖层
  164. self.screen.blit(self.overlay_surf, self.bg_rect.topleft)
  165. # 绘制边框
  166. pygame.draw.rect(
  167. self.screen,
  168. (63, 63, 63, 31),
  169. self.bg_rect,
  170. 1,
  171. border_radius=self.frame_radius
  172. )
  173. def handle_event(self, event):
  174. if event.type == pygame.MOUSEMOTION:
  175. self.hovered = self.bg_rect.collidepoint(event.pos)
  176. elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
  177. if self.hovered:
  178. if self.action:
  179. self.action()
  180. def set_text(self, new_text):
  181. self.text = new_text
  182. self.lines = new_text.split('\n')
  183. self._render()
  184. class PygameButtonBackIMG():
  185. """
  186. 一个仅使用图片作为按钮的类,不含文字渲染,图片本身包含文字。
  187. - default_img_path: 默认状态下的背景图路径
  188. - hover_img_path: 悬停状态下的背景图路径
  189. """
  190. def __init__(self, menu, screen, relx, rely,
  191. default_img_path, hover_img_path,
  192. action=None, hover_in_action=None, hover_out_action=None,
  193. anchor='center', shiny_spark=True):
  194. self.menu = menu
  195. self.screen = screen
  196. # 加载按钮图片
  197. self.default_img = pygame.image.load(default_img_path).convert_alpha()
  198. self.hover_img = pygame.image.load(hover_img_path).convert_alpha()
  199. self.action = action
  200. self.hover_in_action = hover_in_action
  201. self.hover_out_action = hover_out_action
  202. self.relx = relx
  203. self.rely = rely
  204. self.anchor = anchor # 'center' 或 'topleft'
  205. self.hovered = False
  206. self.shiny_spark = shiny_spark
  207. # 按钮尺寸使用图片原始尺寸
  208. self.width, self.height = self.default_img.get_size()
  209. self.spawn_timer = 0
  210. # 计算按钮位置
  211. sw, sh = self.screen.get_size()
  212. x = int(sw * self.relx)
  213. y = int(sh * self.rely)
  214. self.x, self.y = x, y
  215. if self.anchor == 'center':
  216. topleft = (x - self.width//2, y - self.height//2)
  217. else:
  218. topleft = (x, y)
  219. self.bg_rect = pygame.Rect(topleft[0], topleft[1], self.width, self.height)
  220. def draw(self):
  221. # (实时刷新) 根据悬停状态绘制对应图片
  222. img = self.hover_img if self.hovered else self.default_img
  223. self.screen.blit(img, self.bg_rect.topleft)
  224. if self.shiny_spark:
  225. if self.hovered:
  226. self.spawn_timer += 1
  227. if self.spawn_timer >= 10:
  228. self.spawn_timer = 0
  229. for _ in range(10):
  230. self.menu.particles.append(ButtonParticle(self.x, self.y))
  231. def handle_event(self, event):
  232. if event.type == pygame.MOUSEMOTION:
  233. # 先记录上一次的悬停状态
  234. was_hovered = self.hovered
  235. # 更新当前悬停状态
  236. now_hovered = self.bg_rect.collidepoint(event.pos)
  237. self.hovered = now_hovered
  238. # 鼠标刚进入区域
  239. if not was_hovered and now_hovered and self.hover_in_action:
  240. self.hover_in_action()
  241. # 鼠标刚离开区域
  242. elif was_hovered and not now_hovered and self.hover_out_action:
  243. self.hover_out_action()
  244. elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
  245. if self.hovered and self.action:
  246. self.action()
  247. def update_image(self, new_default, new_hover):
  248. self.default_img = pygame.image.load(new_default).convert_alpha()
  249. self.hover_img = pygame.image.load(new_hover).convert_alpha()
  250. self.draw()
  251. class PygameButtonBackIMGRoll:
  252. def __init__(
  253. self,
  254. menu,
  255. screen,
  256. relx,
  257. rely,
  258. default_img_path,
  259. options,
  260. action=None,
  261. roll_action=None,
  262. hover_in_action=None,
  263. hover_out_action=None,
  264. anchor='center',
  265. font_name="Microsoft JhengHei",
  266. font_size=30,
  267. small_scale=0.7,
  268. small_alpha=100,
  269. color=(255, 255, 255),
  270. shiny_spark=True,
  271. related_button=None,
  272. notify_action=None
  273. ):
  274. self.menu = menu
  275. self.screen = screen
  276. self.relx = relx
  277. self.rely = rely
  278. self.anchor = anchor
  279. self.action = action
  280. self.hovered = False
  281. self.hover_in_action = hover_in_action
  282. self.hover_out_action = hover_out_action
  283. self.roll_action = roll_action
  284. self.shiny_spark = shiny_spark
  285. if related_button is None:
  286. self.related_button = []
  287. else:
  288. self.related_button = related_button
  289. if notify_action is None:
  290. self.notify_action = []
  291. else:
  292. self.notify_action = notify_action
  293. # 加载背景图
  294. self.default_img = pygame.image.load(default_img_path).convert_alpha()
  295. self.width, self.height = self.default_img.get_size()
  296. # 设置选项列表
  297. self.options = options
  298. self.current_index = 0
  299. # 字体与文字效果
  300. self.font = get_font(font_name, font_size, font_type='local', bold=True)
  301. self.small_font = get_font(font_name, int(font_size * small_scale), font_type='local', bold=True)
  302. # self.font = pygame.font.SysFont(font_name, font_size, bold=True)
  303. # self.small_font = pygame.font.SysFont(font_name, int(font_size * small_scale), bold=True)
  304. self.color = color
  305. self.small_alpha = small_alpha
  306. # 算出按钮在屏幕上的位置和区域
  307. sw, sh = self.screen.get_size()
  308. x = int(sw * self.relx)
  309. y = int(sh * self.rely)
  310. self.x, self.y = x, y
  311. if self.anchor == 'center':
  312. topleft = (x - self.width // 2, y - self.height // 2)
  313. else:
  314. topleft = (x, y)
  315. self.bg_rect = pygame.Rect(topleft[0], topleft[1], self.width, self.height)
  316. # 用于粒子效果
  317. self.spawn_timer = 0
  318. def draw(self):
  319. # 绘制背景图
  320. img = self.default_img
  321. self.screen.blit(img, self.bg_rect.topleft)
  322. # 粒子效果
  323. if self.shiny_spark:
  324. if getattr(self, 'hovered', False):
  325. self.spawn_timer += 1
  326. if self.spawn_timer >= 10:
  327. self.spawn_timer = 0
  328. for _ in range(10):
  329. self.menu.particles.append(ButtonParticle(self.x, self.y))
  330. # 绘制滚动文字:上一个、当前、下一个
  331. count = len(self.options)
  332. if count:
  333. # 中心文字
  334. text = self.options[self.current_index]
  335. surf = self.font.render(text, True, self.color)
  336. rect = surf.get_rect(center=(self.x, self.y))
  337. self.screen.blit(surf, rect)
  338. # 上一个
  339. prev_i = (self.current_index - 1) % count
  340. prev_text = self.options[prev_i]
  341. prev_s = self.small_font.render(prev_text, True, self.color)
  342. prev_s.set_alpha(self.small_alpha)
  343. offset = self.font.get_height() * 1.5
  344. prev_rect = prev_s.get_rect(center=(self.x, self.y - offset))
  345. self.screen.blit(prev_s, prev_rect)
  346. # 下一个
  347. next_i = (self.current_index + 1) % count
  348. next_text = self.options[next_i]
  349. next_s = self.small_font.render(next_text, True, self.color)
  350. next_s.set_alpha(self.small_alpha)
  351. next_rect = next_s.get_rect(center=(self.x, self.y + offset))
  352. self.screen.blit(next_s, next_rect)
  353. def handle_event(self, event):
  354. # 鼠标移动:检测悬停
  355. if event.type == pygame.MOUSEMOTION:
  356. was = getattr(self, 'hovered', False)
  357. now = self.bg_rect.collidepoint(event.pos)
  358. self.hovered = now
  359. if not was and now and self.hover_in_action:
  360. self.hover_in_action()
  361. elif was and not now and self.hover_out_action:
  362. self.hover_out_action()
  363. # 鼠标滚轮:滚动切换文字
  364. elif event.type == pygame.MOUSEBUTTONDOWN:
  365. if self.bg_rect.collidepoint(event.pos):
  366. # 滚轮向上(按钮4)
  367. if event.button == 4:
  368. self.roll_up()
  369. # 滚轮向下(按钮5)
  370. elif event.button == 5:
  371. self.roll_down()
  372. # 左键点击
  373. elif event.button == 1 and self.action and getattr(self, 'hovered', False):
  374. self.action()
  375. def roll_up(self):
  376. self.current_index = (self.current_index - 1) % len(self.options)
  377. sound_player.play("turn")
  378. if self.roll_action:
  379. self.roll_action(self.options[self.current_index])
  380. for i, observer in enumerate(self.related_button):
  381. self.notify_action[i](observer)
  382. def roll_down(self):
  383. self.current_index = (self.current_index + 1) % len(self.options)
  384. sound_player.play("turn")
  385. if self.roll_action:
  386. self.roll_action(self.options[self.current_index])
  387. for i, observer in enumerate(self.related_button):
  388. self.notify_action[i](observer)
  389. def get_current_text(self):
  390. return self.options[self.current_index]
  391. def set_current_text(self, option):
  392. self.current_index = self.options.index(option)
  393. class Particle:
  394. def __init__(self, x, y):
  395. self.x = x
  396. self.y = y
  397. self.radius = random.randint(1, 3)
  398. # self.color = (200, 200, 200)
  399. self.color = (170, 188, 157)
  400. # 垂直速度
  401. self.speed_y = random.uniform(0.3, 0.6)
  402. # 水平速度,模拟风吹
  403. self.speed_x = random.uniform(-0.3, 0.3)
  404. # 透明度和生命周期
  405. self.alpha = 191
  406. self.life = random.randint(100, 600) # 寿命更长
  407. self.surface = pygame.Surface((self.radius*2, self.radius*2), pygame.SRCALPHA)
  408. def update(self):
  409. # 更新位置
  410. self.y -= self.speed_y
  411. self.x += self.speed_x
  412. self.speed_y += random.uniform(0, 0.01)
  413. self.speed_x += random.uniform(-0.06, 0.06)
  414. # 减缓透明度下降速度
  415. self.life -= 1
  416. self.alpha = max(0, int(191 * min(1., self.life / 300)))
  417. # 重绘粒子
  418. self.surface.fill((0,0,0,0))
  419. pygame.draw.circle(
  420. self.surface,
  421. (self.color[0], self.color[1], self.color[2], self.alpha),
  422. (self.radius, self.radius),
  423. self.radius
  424. )
  425. def draw(self, screen):
  426. screen.blit(self.surface, (self.x - self.radius, self.y - self.radius))
  427. def is_alive(self):
  428. return self.life > 0 and self.alpha > 0
  429. class ButtonParticle:
  430. def __init__(self, x, y):
  431. self.x = x
  432. self.y = y
  433. self.radius = random.randint(1, 3)
  434. # self.color = (200, 200, 200)
  435. # self.color = (170, 188, 157)
  436. self.color = (244, 213, 97)
  437. # 垂直速度
  438. self.speed_y = random.uniform(-5, 5)
  439. # 水平速度,模拟风吹
  440. self.speed_x = random.uniform(-10, 10)
  441. # 透明度和生命周期
  442. self.alpha = 255
  443. self.fix_life = 30
  444. self.life = random.randint(10, 20) # 寿命更长
  445. self.surface = pygame.Surface((self.radius*2, self.radius*2), pygame.SRCALPHA)
  446. def update(self):
  447. # 更新位置
  448. self.y -= self.speed_y
  449. self.x += self.speed_x
  450. self.speed_y *= 0.9
  451. self.speed_x *= 0.9
  452. # 减缓透明度下降速度
  453. self.fix_life -= 1
  454. if self.fix_life < 0:
  455. self.life -= 1
  456. self.alpha = max(0, int(191 * min(1., self.life / 30)))
  457. # 重绘粒子
  458. self.surface.fill((0,0,0,0))
  459. pygame.draw.circle(
  460. self.surface,
  461. (self.color[0], self.color[1], self.color[2], self.alpha),
  462. (self.radius, self.radius),
  463. self.radius
  464. )
  465. def draw(self, screen):
  466. screen.blit(self.surface, (self.x - self.radius, self.y - self.radius))
  467. def is_alive(self):
  468. return self.life > 0 and self.alpha > 0
  469. class PygameIMG:
  470. def __init__(self, menu, screen, relx, rely, default_img_path=None, py_img=None, anchor='center'):
  471. self.menu = menu
  472. self.screen = screen
  473. # 加载按钮图片
  474. if default_img_path is not None:
  475. self.default_img = pygame.image.load(default_img_path).convert_alpha()
  476. else:
  477. self.default_img = py_img
  478. self.relx = relx
  479. self.rely = rely
  480. self.anchor = anchor # 'center' 或 'topleft'
  481. self.hovered = False
  482. # 按钮尺寸使用图片原始尺寸
  483. self.width, self.height = self.default_img.get_size()
  484. # 计算按钮位置
  485. sw, sh = self.screen.get_size()
  486. x = int(sw * self.relx)
  487. y = int(sh * self.rely)
  488. self.x, self.y = x, y
  489. if self.anchor == 'center':
  490. topleft = (x - self.width//2, y - self.height//2)
  491. else:
  492. topleft = (x, y)
  493. self.bg_rect = pygame.Rect(topleft[0], topleft[1], self.width, self.height)
  494. def draw(self):
  495. # (实时刷新) 根据悬停状态绘制对应图片
  496. img = self.default_img
  497. self.screen.blit(img, self.bg_rect.topleft)
  498. def update_image(self, new_default):
  499. self.default_img = new_default
  500. # self.default_img = pygame.image.load(new_default).convert_alpha()
  501. self.draw()
  502. def handle_event(self, event):
  503. pass