| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520 |
- import pygame
- import random
- from game.sound import sound_player
- # hk4e_zh_cn12 = pygame.font.Font(r"res\font\hk4e_zh-cn.ttf", 12)
- font_dict = dict() # {("Microsoft JhengHei", 12, bold): pygame.font}
- def get_font(font_name, size, font_type='sys', bold=False):
- global font_dict
- load_font = font_dict.get((font_name, size, bold), None)
- if load_font is None:
- if font_type == 'sys':
- font_dict[(font_name, size, bold)] = pygame.font.SysFont(font_name, size, bold=bold)
- else:
- font_dict[(font_name, size, bold)] = pygame.font.Font(f"res\\font\\{font_name}", size)
- load_font = font_dict.get((font_name, size, bold), None)
- return load_font
- class PygameButton:
- """
- 文字渲染按钮
- """
- def __init__(
- self, screen, text, relx, rely, font_size, bg_color,
- fg_color=(0,0,0), action=None, anchor='center', is_bold=True, fix_shape=None, bg_alpha=255,
- frosted_glass=False, blur_radius=4, glass_alpha=120, frame_radius=8, glass_surf_color=(255,255,255), background=None,
- wait_notification=False, notify_action=None
- ):
- self.screen = screen
- self.text = text
- self.lines = text.split('\n')
- # self.font = get_font("Microsoft JhengHei", font_size, font_type='sys', bold=is_bold)
- # self.font = get_font("SourceHanSerifCN-Bold.otf", font_size, font_type='local', bold=is_bold)
- self.font = get_font("hk4e_zh-cn.ttf", font_size, font_type='local', bold=is_bold)
- # self.font = pygame.font.SysFont("Microsoft JhengHei", font_size, bold=is_bold)
- # self.font = pygame.font.Font(r"res\font\SourceHanSerif-VF.ttc", font_size)
- # self.font = pygame.font.Font(r"res\font\SourceHanSerifCN-Bold.otf", font_size)
- # 监听者模式参数
- self.wait_notification = wait_notification
- self.new_notification = None
- self.notify_action = notify_action
- # 毛玻璃相关参数
- self.frosted_glass = frosted_glass
- self.blur_radius = blur_radius
- self.glass_alpha = glass_alpha
- self.frame_radius = frame_radius
- self.background = background
- self.glass_surf_color = glass_surf_color
- # 普通模式颜色设置
- self._init_normal_colors(bg_color, bg_alpha)
- self.fg_color = fg_color
- self.action = action
- self.relx = relx
- self.rely = rely
- self.fix_shape = fix_shape
- self.anchor = anchor # 'center', 'topleft'
- self.hovered = False
- self._render()
- # 毛玻璃特效所需Surface
- if self.frosted_glass:
- self._init_frosted_glass()
- def _init_normal_colors(self, bg_color, bg_alpha):
- """初始化普通模式的背景颜色"""
- self.bg_color_normal = pygame.Color(bg_color)
- self.bg_color_normal.a = bg_alpha
- # 悬停颜色计算
- h = self.bg_color_normal
- hover_rgb = (
- max(0, int(h.r * 0.8)),
- max(0, int(h.g * 0.8)),
- max(0, int(h.b * 0.8)),
- )
- self.bg_color_hover = pygame.Color(*hover_rgb)
- self.bg_color_hover.a = bg_alpha
- def _init_frosted_glass(self):
- """初始化毛玻璃特效所需资源"""
- # 创建模糊用的临时surface
- self.blur_surface = pygame.Surface(
- (self.bg_rect.width//self.blur_radius,
- self.bg_rect.height//self.blur_radius),
- pygame.SRCALPHA
- )
- self.overlay_surf = pygame.Surface(
- (self.bg_rect.width, self.bg_rect.height),
- pygame.SRCALPHA
- )
- # self.overlay_surf.fill((255, 255, 255, self.glass_alpha))
- self.overlay_surf.fill((*self.glass_surf_color, self.glass_alpha))
- def _create_blurred_background(self, background):
- """创建模糊背景(毛玻璃特效核心)"""
- if not self.frosted_glass:
- return
- # 截取背景区域
- try:
- sub = background.subsurface(self.bg_rect)
- except ValueError:
- return
- # 快速缩放模糊算法
- scaled = pygame.transform.scale(
- sub,
- (self.bg_rect.w//self.blur_radius,
- self.bg_rect.h//self.blur_radius)
- )
- self.blur_surface = pygame.transform.smoothscale(
- scaled,
- (self.bg_rect.w, self.bg_rect.h)
- )
- def _render(self):
- # 渲染多行文本
- self.text_surfs = [self.font.render(line, True, self.fg_color) for line in self.lines]
- widths = [surf.get_width() for surf in self.text_surfs]
- heights = [surf.get_height() for surf in self.text_surfs]
- if self.fix_shape is None:
- total_width = max(widths)
- total_height = sum(heights) + (len(heights)-1) * 5
- else:
- total_width = self.fix_shape[0]
- total_height = self.fix_shape[1]
- sw, sh = self.screen.get_size()
- x = int(sw * self.relx)
- y = int(sh * self.rely)
- # 根据锚点决定位置
- if self.anchor == 'center':
- topleft = (x - total_width//2 - 10, y - total_height//2 - 5)
- elif self.anchor == 'topleft':
- topleft = (x, y)
- else:
- topleft = (x - total_width//2 - 10, y - total_height//2 - 5)
- self.bg_rect = pygame.Rect(topleft[0], topleft[1], total_width + 20, total_height + 10)
- # 计算每行文本位置
- self.text_positions = []
- offset_y = self.bg_rect.y + 5
- for surf in self.text_surfs:
- line_x = self.bg_rect.x + (self.bg_rect.width - surf.get_width())//2 if self.anchor=='center' else self.bg_rect.x + 10
- self.text_positions.append((line_x, offset_y))
- offset_y += surf.get_height() + 5
- if self.frosted_glass:
- self._init_frosted_glass()
- def draw(self):
- """新增background参数用于毛玻璃特效"""
- if self.frosted_glass and self.background is not None:
- # 毛玻璃模式
- self._draw_frosted_glass(self.background.bg_image)
- else:
- # 普通模式
- self._draw_normal()
- # 绘制文本(通用)
- for surf, pos in zip(self.text_surfs, self.text_positions):
- self.screen.blit(surf, pos)
- def _draw_normal(self):
- """普通按钮绘制"""
- color = self.bg_color_hover if self.hovered else self.bg_color_normal
- bg_surf = pygame.Surface(
- (self.bg_rect.width, self.bg_rect.height),
- pygame.SRCALPHA
- )
- bg_surf.fill(color)
- self.screen.blit(bg_surf, self.bg_rect.topleft)
- def _draw_frosted_glass(self, background):
- """毛玻璃特效绘制"""
- # 生成模糊背景
- self._create_blurred_background(background)
- # 绘制模糊层
- if not (self.hovered and self.action is not None):
- self.screen.blit(self.blur_surface, self.bg_rect.topleft)
- # 添加白色半透覆盖层
- self.screen.blit(self.overlay_surf, self.bg_rect.topleft)
- # 绘制边框
- pygame.draw.rect(
- self.screen,
- (63, 63, 63, 31),
- self.bg_rect,
- 1,
- border_radius=self.frame_radius
- )
- def handle_event(self, event):
- if event.type == pygame.MOUSEMOTION:
- self.hovered = self.bg_rect.collidepoint(event.pos)
- elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
- if self.hovered:
- if self.action:
- self.action()
- def set_text(self, new_text):
- self.text = new_text
- self.lines = new_text.split('\n')
- self._render()
- class PygameButtonBackIMG:
- """
- 一个仅使用图片作为按钮的类,不含文字渲染,图片本身包含文字。
- - default_img_path: 默认状态下的背景图路径
- - hover_img_path: 悬停状态下的背景图路径
- """
- def __init__(self, menu, screen, relx, rely,
- default_img_path, hover_img_path,
- action=None, hover_in_action=None, hover_out_action=None,
- anchor='center', shiny_spark=True):
- self.menu = menu
- self.screen = screen
- # 加载按钮图片
- self.default_img = pygame.image.load(default_img_path).convert_alpha()
- self.hover_img = pygame.image.load(hover_img_path).convert_alpha()
- self.action = action
- self.hover_in_action = hover_in_action
- self.hover_out_action = hover_out_action
- self.relx = relx
- self.rely = rely
- self.anchor = anchor # 'center' 或 'topleft'
- self.hovered = False
- self.shiny_spark = shiny_spark
- # 按钮尺寸使用图片原始尺寸
- self.width, self.height = self.default_img.get_size()
- self.spawn_timer = 0
- # 计算按钮位置
- sw, sh = self.screen.get_size()
- x = int(sw * self.relx)
- y = int(sh * self.rely)
- self.x, self.y = x, y
- if self.anchor == 'center':
- topleft = (x - self.width//2, y - self.height//2)
- else:
- topleft = (x, y)
- self.bg_rect = pygame.Rect(topleft[0], topleft[1], self.width, self.height)
- def draw(self):
- # (实时刷新) 根据悬停状态绘制对应图片
- img = self.hover_img if self.hovered else self.default_img
- self.screen.blit(img, self.bg_rect.topleft)
- if self.shiny_spark:
- if self.hovered:
- self.spawn_timer += 1
- if self.spawn_timer >= 10:
- self.spawn_timer = 0
- for _ in range(10):
- self.menu.particles.append(ButtonParticle(self.x, self.y))
- def handle_event(self, event):
- if event.type == pygame.MOUSEMOTION:
- # 先记录上一次的悬停状态
- was_hovered = self.hovered
- # 更新当前悬停状态
- now_hovered = self.bg_rect.collidepoint(event.pos)
- self.hovered = now_hovered
- # 鼠标刚进入区域
- if not was_hovered and now_hovered and self.hover_in_action:
- self.hover_in_action()
- # 鼠标刚离开区域
- elif was_hovered and not now_hovered and self.hover_out_action:
- self.hover_out_action()
- elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
- if self.hovered and self.action:
- self.action()
- def update_image(self, new_default, new_hover):
- self.default_img = pygame.image.load(new_default).convert_alpha()
- self.hover_img = pygame.image.load(new_hover).convert_alpha()
- self.draw()
- class PygameButtonBackIMGRoll:
- def __init__(
- self,
- menu,
- screen,
- relx,
- rely,
- default_img_path,
- options,
- action=None,
- roll_action=None,
- hover_in_action=None,
- hover_out_action=None,
- anchor='center',
- font_name="Microsoft JhengHei",
- font_size=30,
- small_scale=0.7,
- small_alpha=100,
- color=(255, 255, 255),
- shiny_spark=True,
- related_button=None,
- notify_action=None
- ):
- self.menu = menu
- self.screen = screen
- self.relx = relx
- self.rely = rely
- self.anchor = anchor
- self.action = action
- self.hovered = False
- self.hover_in_action = hover_in_action
- self.hover_out_action = hover_out_action
- self.roll_action = roll_action
- self.shiny_spark = shiny_spark
- if related_button is None:
- self.related_button = []
- else:
- self.related_button = related_button
- if notify_action is None:
- self.notify_action = []
- else:
- self.notify_action = notify_action
- # 加载背景图
- self.default_img = pygame.image.load(default_img_path).convert_alpha()
- self.width, self.height = self.default_img.get_size()
- # 设置选项列表
- self.options = options
- self.current_index = 0
- # 字体与文字效果
- self.font = get_font(font_name, font_size, font_type='local', bold=True)
- self.small_font = get_font(font_name, int(font_size * small_scale), font_type='local', bold=True)
- # self.font = pygame.font.SysFont(font_name, font_size, bold=True)
- # self.small_font = pygame.font.SysFont(font_name, int(font_size * small_scale), bold=True)
- self.color = color
- self.small_alpha = small_alpha
- # 算出按钮在屏幕上的位置和区域
- sw, sh = self.screen.get_size()
- x = int(sw * self.relx)
- y = int(sh * self.rely)
- self.x, self.y = x, y
- if self.anchor == 'center':
- topleft = (x - self.width // 2, y - self.height // 2)
- else:
- topleft = (x, y)
- self.bg_rect = pygame.Rect(topleft[0], topleft[1], self.width, self.height)
- # 用于粒子效果
- self.spawn_timer = 0
- def draw(self):
- # 绘制背景图
- img = self.default_img
- self.screen.blit(img, self.bg_rect.topleft)
- # 粒子效果
- if self.shiny_spark:
- if getattr(self, 'hovered', False):
- self.spawn_timer += 1
- if self.spawn_timer >= 10:
- self.spawn_timer = 0
- for _ in range(10):
- self.menu.particles.append(ButtonParticle(self.x, self.y))
- # 绘制滚动文字:上一个、当前、下一个
- count = len(self.options)
- if count:
- # 中心文字
- text = self.options[self.current_index]
- surf = self.font.render(text, True, self.color)
- rect = surf.get_rect(center=(self.x, self.y))
- self.screen.blit(surf, rect)
- # 上一个
- prev_i = (self.current_index - 1) % count
- prev_text = self.options[prev_i]
- prev_s = self.small_font.render(prev_text, True, self.color)
- prev_s.set_alpha(self.small_alpha)
- offset = self.font.get_height() * 1.5
- prev_rect = prev_s.get_rect(center=(self.x, self.y - offset))
- self.screen.blit(prev_s, prev_rect)
- # 下一个
- next_i = (self.current_index + 1) % count
- next_text = self.options[next_i]
- next_s = self.small_font.render(next_text, True, self.color)
- next_s.set_alpha(self.small_alpha)
- next_rect = next_s.get_rect(center=(self.x, self.y + offset))
- self.screen.blit(next_s, next_rect)
- def handle_event(self, event):
- # 鼠标移动:检测悬停
- if event.type == pygame.MOUSEMOTION:
- was = getattr(self, 'hovered', False)
- now = self.bg_rect.collidepoint(event.pos)
- self.hovered = now
- if not was and now and self.hover_in_action:
- self.hover_in_action()
- elif was and not now and self.hover_out_action:
- self.hover_out_action()
- # 鼠标滚轮:滚动切换文字
- elif event.type == pygame.MOUSEBUTTONDOWN:
- if self.bg_rect.collidepoint(event.pos):
- # 滚轮向上(按钮4)
- if event.button == 4:
- self.roll_up()
- # 滚轮向下(按钮5)
- elif event.button == 5:
- self.roll_down()
- # 左键点击
- elif event.button == 1 and self.action and getattr(self, 'hovered', False):
- self.action()
- def roll_up(self):
- self.current_index = (self.current_index - 1) % len(self.options)
- sound_player.play("turn")
- if self.roll_action:
- self.roll_action(self.options[self.current_index])
- for i, observer in enumerate(self.related_button):
- self.notify_action[i](observer)
- def roll_down(self):
- self.current_index = (self.current_index + 1) % len(self.options)
- sound_player.play("turn")
- if self.roll_action:
- self.roll_action(self.options[self.current_index])
- for i, observer in enumerate(self.related_button):
- self.notify_action[i](observer)
- def get_current_text(self):
- return self.options[self.current_index]
- def set_current_text(self, option):
- self.current_index = self.options.index(option)
- class Particle:
- def __init__(self, x, y):
- self.x = x
- self.y = y
- self.radius = random.randint(1, 3)
- # self.color = (200, 200, 200)
- self.color = (170, 188, 157)
- # 垂直速度
- self.speed_y = random.uniform(0.3, 0.6)
- # 水平速度,模拟风吹
- self.speed_x = random.uniform(-0.3, 0.3)
- # 透明度和生命周期
- self.alpha = 191
- self.life = random.randint(100, 600) # 寿命更长
- self.surface = pygame.Surface((self.radius*2, self.radius*2), pygame.SRCALPHA)
- def update(self):
- # 更新位置
- self.y -= self.speed_y
- self.x += self.speed_x
- self.speed_y += random.uniform(0, 0.01)
- self.speed_x += random.uniform(-0.06, 0.06)
- # 减缓透明度下降速度
- self.life -= 1
- self.alpha = max(0, int(191 * min(1., self.life / 300)))
- # 重绘粒子
- self.surface.fill((0,0,0,0))
- pygame.draw.circle(
- self.surface,
- (self.color[0], self.color[1], self.color[2], self.alpha),
- (self.radius, self.radius),
- self.radius
- )
- def draw(self, screen):
- screen.blit(self.surface, (self.x - self.radius, self.y - self.radius))
- def is_alive(self):
- return self.life > 0 and self.alpha > 0
- class ButtonParticle:
- def __init__(self, x, y):
- self.x = x
- self.y = y
- self.radius = random.randint(1, 3)
- # self.color = (200, 200, 200)
- # self.color = (170, 188, 157)
- self.color = (244, 213, 97)
- # 垂直速度
- self.speed_y = random.uniform(-5, 5)
- # 水平速度,模拟风吹
- self.speed_x = random.uniform(-10, 10)
- # 透明度和生命周期
- self.alpha = 255
- self.fix_life = 30
- self.life = random.randint(10, 20) # 寿命更长
- self.surface = pygame.Surface((self.radius*2, self.radius*2), pygame.SRCALPHA)
- def update(self):
- # 更新位置
- self.y -= self.speed_y
- self.x += self.speed_x
- self.speed_y *= 0.9
- self.speed_x *= 0.9
- # 减缓透明度下降速度
- self.fix_life -= 1
- if self.fix_life < 0:
- self.life -= 1
- self.alpha = max(0, int(191 * min(1., self.life / 30)))
- # 重绘粒子
- self.surface.fill((0,0,0,0))
- pygame.draw.circle(
- self.surface,
- (self.color[0], self.color[1], self.color[2], self.alpha),
- (self.radius, self.radius),
- self.radius
- )
- def draw(self, screen):
- screen.blit(self.surface, (self.x - self.radius, self.y - self.radius))
- def is_alive(self):
- return self.life > 0 and self.alpha > 0
|