Python跨类复用属性可行吗?pygame小球移动项目开发问题
现有代码的核心Bug与修正方向
- 传参类型不匹配
你实例化Point类时写的c = Point(p, p)存在类型错误:Point类的构造方法需要接收两个数值型的x、y坐标,但你传入的是两个Player类的实例对象,根本无法读取到实际的坐标值。 - 事件队列抢占冲突
Point类的get_circle_position方法内部调用了pygame.event.poll(),会从全局事件队列里提前取走鼠标移动事件,导致主循环中pygame.event.get()无法拿到完整的事件列表,后续的窗口退出判断、交互响应都会失效。 - 坐标存储逻辑冗余
你想要复用Player类坐标、避免重复编写坐标逻辑的需求完全可以实现,当前的卡点是Player类把坐标存在元组self.coordinates里,没有拆成独立可修改的x、y属性,后续做移动、读取位置时,还要在Point类里重复存一份坐标,非常容易出现两边数据不同步的问题。
完全不需要单独搭建Point类做坐标中转,直接把x、y作为独立属性存在Player实例上,所有读取坐标的操作直接从Player对象获取,就能实现零重复存储的效果。
正确的逻辑整合方式
- 删掉冗余的Point类,把你原本想在Point里实现的「读取圆形当前位置」的功能,直接写成Player类的方法,方法内部直接读取自身的x、y属性,不需要外部传值。
- 移除无用的
pyautogui导入,pygame自带的pygame.mouse.get_pos()就能准确读取窗口内的鼠标坐标,不会出现跨屏幕的坐标偏移问题。 - 不要用动态给Player实例挂载自定义属性的写法(比如你之前写的
p.getposition = c),这种写法可读性极差,新手写多了很容易找不到代码对应的逻辑位置。
可直接运行的优化后代码
import pygame import random import math # 用于计算两点向量距离 pygame.init() screen_width, screen_height = 500, 500 screen = pygame.display.set_mode((screen_width, screen_height)) clock = pygame.time.Clock() # 控制游戏帧率稳定 class Player: def __init__(self, x, y, circle_color, circle_radius, circle_outline_width): self.circle_color = circle_color # 拆为独立的x、y属性,方便后续修改、读取 self.x = x self.y = y self.circle_radius = circle_radius # 修正原代码的拼写错误 self.circle_outline_width = circle_outline_width self.speed = 3 # 固定移动速度 # 复用原本想在Point类中实现的位置读取功能 def get_circle_position(self): return f"Circle at X: {self.x}, Y:{self.y}" def move_towards_mouse(self): # 获取窗口内鼠标实时坐标 mouse_x, mouse_y = pygame.mouse.get_pos() # 计算玩家与鼠标的坐标差 dx = mouse_x - self.x dy = mouse_y - self.y # 计算两点直线距离,避免除零错误 distance = math.hypot(dx, dy) if distance > 0: # 向量归一化后乘以固定步长,实现匀速平滑移动 step_x = (dx / distance) * self.speed step_y = (dy / distance) * self.speed self.x += step_x self.y += step_y def draw(self, window): # 补上遗漏的描边宽度参数 pygame.draw.circle( window, self.circle_color, (self.x, self.y), self.circle_radius, self.circle_outline_width ) def constantly_display(window, player): window.fill(pygame.Color("white")) player.draw(window) pygame.display.update() def main(): run = True p = Player( random.randint(35, screen_width - 40), random.randint(35, screen_height - 40), pygame.Color( random.randint(0, 200), random.randint(0, 200), random.randint(0, 200) ), 40, 5 ) while run: clock.tick(60) # 锁定60帧刷新率 for event in pygame.event.get(): if event.type == pygame.QUIT: run = False # 每帧先执行移动逻辑 p.move_towards_mouse() # 打印位置信息可验证读取逻辑是否正常 print(p.get_circle_position()) constantly_display(screen, p) pygame.quit() if __name__ == "__main__": main()
额外的语法优化建议
- 代码结构上,把所有方法和逻辑按类划分,不要在类外部给实例动态挂载自定义属性,方便后续读代码时快速定位逻辑位置。
- 向量移动计算时一定要加距离判断,当玩家和鼠标位置已经重合时,不要继续执行除法计算,避免出现除零报错。
- 加上帧率控制,不然没有时钟锁帧的话,游戏会在不同性能的电脑上跑出完全不一样的移动速度。
内容的提问来源于stack exchange,提问作者Danny
相关产品推荐
相关产品推荐

