import pygame import sys # 初始化 pygame pygame.init() # 设置窗口大小 width, height = 800, 600 screen = pygame.display.set_mode((width, height)) pygame.display.set_caption('拼图游戏') class Button: def __init__(self, text, font, color, hover_color, pos, size): self.text = text self.font = font self.color = color self.hover_color = hover_color self.pos = pos self.size = size self.rect = pygame.Rect(pos, size) self.hovered = False def draw(self, surface): if self.hovered: pygame.draw.rect(surface, self.hover_color, self.rect) else: pygame.draw.rect(surface, self.color, self.rect) text_surface = self.font.render(self.text, True, (255, 255, 255)) text_rect = text_surface.get_rect(center=self.rect.center) surface.blit(text_surface, text_rect) def update(self, mouse_pos): if self.rect.collidepoint(mouse_pos): self.hovered = True else: self.hovered = False def clicked(self, mouse_pos): return self.rect.collidepoint(mouse_pos) # 初始化字体 pygame.font.init() tfont = pygame.font.Font(None, width//4) cfont = pygame.font.Font(None, width//20) # 创建按钮 button1 = Button('3*3模式', cfont, (100, 100, 100), (150, 150, 150), (width/2 - 100, height/2.2), (200, 50)) button2 = Button('4*4模式', cfont, (100, 100, 100), (150, 150, 150), (width/2 - 100, height/1.8), (200, 50)) button3 = Button('5*5模式', cfont, (100, 100, 100), (150, 150, 150), (width/2 - 100, height/1.5), (200, 50)) buttons = [button1, button2, button3] # 游戏循环 running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() for button in buttons: if button.clicked(mouse_pos): if button.text == '3*3模式': print("点击了 3*3 模式按钮") # 执行 3*3 模式对应的操作 elif button.text == '4*4模式': print("点击了 4*4 模式按钮") # 执行 4*4 模式对应的操作 elif button.text == '5*5模式': print("点击了 5*5 模式按钮") # 执行 5*5 模式对应的操作 # 获取鼠标位置 mouse_pos = pygame.mouse.get_pos() # 清空屏幕 screen.fill((255, 255, 255)) # 绘制标题和按钮 title = tfont.render('拼图游戏', True, (10, 10, 10)) trect = title.get_rect() trect.midtop = (width/2, height/10) screen.blit(title, trect) for button in buttons: button.update(mouse_pos) button.draw(screen) pygame.display.flip() pygame.quit()