Pygame实现Fitts定律时点击中点生成大量随机圆点的问题
问题解决:Pygame实现Fitts定律时点击生成大量圆点的问题
问题根源
你当前用pygame.mouse.get_pressed()判断点击,这个方法在鼠标左键按住的每一帧都会返回True,而Pygame主循环每秒会运行几十到上百帧,所以按住鼠标时会连续执行生成圆点的代码,导致出现大量圆点。正确的做法是监听MOUSEBUTTONDOWN事件,这个事件只会在鼠标按下的瞬间触发一次。
修正后的代码
import pygame import math import random pygame.init() width = 1024 height = 768 display = pygame.display.set_mode((width, height)) # 颜色定义 black = (0, 0, 0) white = (255, 255, 255) purple = (128, 0, 128) grey = (128, 128, 128) sky = (0, 0, 220) blue = (85, 206, 255) orange = (255, 127, 80) red = (200, 0, 0) light_red = (255, 0, 0) green = (0, 200, 0) light_green = (0, 255, 0) colors = [white, grey, purple, sky, blue, orange, red, light_red, green, light_green] clock = pygame.time.Clock() # 初始化目标圆点参数 current_pos = (512, 384) current_color = green current_radius = random.randint(14, 20) while True: display.fill(black) # 每一帧先清空屏幕 # 绘制当前的目标圆点 pygame.draw.circle(display, current_color, current_pos, current_radius) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() # 监听鼠标左键按下事件 if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: x, y = event.pos # 计算鼠标与圆点中心的距离 dx = x - current_pos[0] dy = y - current_pos[1] if math.sqrt(dx**2 + dy**2) < current_radius: # 根据当前圆点位置切换下一个目标 if current_pos == (512, 384): # 点击中间圆点,生成随机位置的彩色圆点 cx = random.randint(20, width - 20) cy = random.randint(20, height - 20) current_pos = (cx, cy) current_color = random.choice(colors) current_radius = random.randint(14, 20) else: # 点击随机圆点,回到中间绿色圆点 current_pos = (512, 384) current_color = green current_radius = random.randint(14, 20) pygame.display.update() clock.tick(60) # 限制帧率为60帧/秒
关键修改说明
- 改用
MOUSEBUTTONDOWN事件处理点击,确保每次点击只触发一次生成逻辑 - 将屏幕清空和圆点绘制移到主循环开头,保证每一帧都正确渲染当前状态,避免残留之前的圆点
- 用
current_pos、current_color、current_radius统一管理当前显示的圆点参数,逻辑更清晰 - 限制帧率为60,避免循环运行过快
内容的提问来源于stack exchange,提问作者Steve J
相关产品推荐
相关产品推荐

