如何将可交互输入框功能集成到Pygame随机加法运算代码中
Pygame随机加法答题程序合并实现
合并前冻结问题原因
两段代码各自包含完整的Pygame初始化、事件循环、渲染逻辑,直接拼接会导致重复初始化资源、事件处理逻辑冲突,从而出现程序冻结的问题。
核心修改点
- 移除重复的Pygame初始化、窗口创建逻辑,统一管理全局变量和公共资源
- 保留第二段代码的可交互InputBox输入框类,适配答题场景增加数字输入限制、回车提交逻辑
- 复用第一段代码的随机加法题生成逻辑,新增答案校验、得分统计、自动刷新题目功能
完整可运行代码
import pygame import random # 全局初始化 pygame.init() surface = pygame.display.set_mode((600, 400)) pygame.display.set_caption("Projecte MatZanfe") clock = pygame.time.Clock() # 公共资源配置 FONT_TITLE = pygame.font.SysFont('comicsans', 50) FONT_INPUT = pygame.font.SysFont('comicsans', 32) COLOR_INACTIVE = pygame.Color('lightskyblue3') COLOR_ACTIVE = pygame.Color('dodgerblue2') COLOR_BG = (255, 70, 90) COLOR_WHITE = (255, 255, 255) # 可交互输入框类 class InputBox: def __init__(self, x, y, w, h, text=''): self.rect = pygame.Rect(x, y, w, h) self.color = COLOR_INACTIVE self.text = text self.txt_surface = FONT_INPUT.render(text, True, self.color) self.active = False def handle_event(self, event): if event.type == pygame.MOUSEBUTTONDOWN: # 点击切换输入框激活状态 self.active = self.rect.collidepoint(event.pos) self.color = COLOR_ACTIVE if self.active else COLOR_INACTIVE if event.type == pygame.KEYDOWN: if self.active: if event.key == pygame.K_RETURN: # 回车提交答案 res = self.text self.text = '' self.txt_surface = FONT_INPUT.render(self.text, True, self.color) return res elif event.key == pygame.K_BACKSPACE: self.text = self.text[:-1] else: # 限制仅可输入数字 if event.unicode.isdigit(): self.text += event.unicode # 重新渲染输入文本 self.txt_surface = FONT_INPUT.render(self.text, True, self.color) return None def update(self): # 自适应文本长度调整输入框宽度 width = max(200, self.txt_surface.get_width()+10) self.rect.w = width def draw(self, screen): screen.blit(self.txt_surface, (self.rect.x+5, self.rect.y+5)) pygame.draw.rect(screen, self.color, self.rect, 2) # 生成随机加法题目 def generate_question(): x = random.randint(0, 10) y = random.randint(0, 10) return x, y, x + y def main(): input_box = InputBox(190, 250, 200, 32) x, y, correct_ans = generate_question() points = 0 running = True while running: # 统一事件处理 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # 输入框事件处理 submit_res = input_box.handle_event(event) if submit_res is not None: # 答案校验 if submit_res.isdigit() and int(submit_res) == correct_ans: points += 1 # 生成新题目 x, y, correct_ans = generate_question() # 组件状态更新 input_box.update() # 统一界面渲染 surface.fill(COLOR_BG) # 绘制加法题目 q_text = FONT_TITLE.render(f"{x}+{y}", True, COLOR_WHITE) surface.blit(q_text, (260, 120)) # 绘制得分 p_text = FONT_INPUT.render(f"得分: {points}", True, COLOR_WHITE) surface.blit(p_text, (20, 20)) # 绘制输入框 input_box.draw(surface) pygame.display.flip() clock.tick(30) pygame.quit() if __name__ == '__main__': main()
内容的提问来源于stack exchange,提问作者Torchllama
相关产品推荐
相关产品推荐

