You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Pygame加法练习代码实现答对答错均刷新随机数字

Pygame加法练习小游戏问题修复

核心问题说明

你当前的代码存在几处错误,导致无法实现答对答错刷新新题的需求:

  • 调用start_the_game()生成新随机数后,没有将返回的新x、y赋值给全局变量,界面一直渲染旧题目
  • 答错分支的start_the_game漏写了括号,根本没有执行生成新随机数的逻辑
  • 事件处理中重复调用渲染和画面更新方法属于冗余代码,主循环本身已经自带了对应逻辑

修正后的完整主程序代码

import pygame
import random
from InputBox import InputBox

pygame.init()

clock = pygame.time.Clock()
surface = pygame.display.set_mode((600, 400))
pygame.display.set_caption("加法练习小游戏")
font = pygame.font.SysFont('comicsans', 50)
base_font = pygame.font.Font(None, 32)
user_text = ''
color_active = pygame.Color('lightskyblue3')
running = True
points = 0

def start_the_game():
    x = random.randint(0, 10)
    y = random.randint(0, 10)
    return x, y

def display_the_game(x, y):
    surface.fill((255, 70, 90))
    # 渲染加法题目
    text = font.render(f"{x}+{y}", True, (255, 255, 255))
    # 渲染得分
    punts = font.render(f"得分:{points}", True, (255,255,255))
    surface.blit(text, (260, 120))
    surface.blit(punts, (350,30))
    input_box.draw(surface)

x, y = start_the_game()
input_box = InputBox(190, 250, 200, 32)

while running:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        else:
            result = input_box.handle_event(event)
            if result is not None:
                # 校验答案
                if int(result) == x + y:
                    # 答对加分
                    points += 5
                # 无论对错都刷新新题目
                x, y = start_the_game()

    display_the_game(x, y)
    pygame.display.update()

pygame.quit()

改动说明

  • 将界面标题、得分提示改为中文,更符合使用习惯
  • 移除事件处理中冗余的渲染、画面更新代码,逻辑更简洁
  • 无论答对答错,都将start_the_game()返回的新随机数赋值给x、y,实现题目自动刷新
  • 拆分答对加分逻辑和公共刷新题目逻辑,减少重复代码
  • 你引用的InputBox模块代码无需修改,可正常使用

内容的提问来源于stack exchange,提问作者Torchllama

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 13:06:03