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

Python Pygame简易方块游戏继承Box_User的Player实例无法移动问题求助

问题原因
  • 按键状态未实时更新:你将pygame.key.get_pressed()定义为Player的类属性,该代码只会在类首次加载时执行1次,获取的是游戏启动瞬间的按键状态,后续主循环运行过程中不会再更新,所以永远识别不到后续的按键操作。
  • 方块绘制逻辑错误:Box_User的draw_box方法中,pygame.draw.rect的坐标参数传了全局坐标self.pos_x、self.pos_y,但该方法是在大小为self.box_height * self.box_width的独立Surface上绘图,坐标应相对于该Surface本身,你现在相当于把矩形画到了Surface可视区域外,会导致方块无法正常显示。
  • 跳跃方法逻辑耦合:_jump被定义为静态方法,内部硬编码操作全局实例box,后续如果创建多个Player实例会出现逻辑冲突,同时jump、jump_status被定义为类属性,多个实例会共享状态,导致跳跃逻辑异常。
修复方案
  1. 调整按键获取逻辑:把按键状态获取移到movements方法内部,每次调用时都获取最新的按键状态
  2. 修正绘制逻辑:绘制方块时使用相对于Surface的坐标(0,0)
  3. 调整跳跃方法为实例方法,把跳跃相关属性改为实例属性
  4. 可选优化:移除不必要的静态方法,降低全局变量耦合
修复后的关键代码示例
class Box_User():
    def __init__(self, x, y, height, width):
        self.pos_x = x
        self.pos_y = y
        self.box_height = height
        self.box_width = width
        self.box = pygame.Surface((self.box_height, self.box_width))
        self.color = (0, 20, 0)
        # 跳跃属性改为实例属性
        self.jump = 10
        self.jump_status = False
        self.draw_box()

    def draw_box(self):
        # 绘制坐标改为相对于Surface的(0,0)
        pygame.draw.rect(self.box, self.color, pygame.Rect(0, 0, self.box_height, self.box_width))

    # 改为实例方法,操作当前实例的属性
    def _jump(self):
        if self.jump >= -10:
            self.pos_y -= (self.jump * abs(self.jump)) * 0.3
            scroll[1] += (self.jump * abs(self.jump)) * 0.3
            self.jump -= 1
        else:
            self.jump = 10
            self.jump_status = False

class Player(Box_User):
    def __init__(self, x, y, height, width):
        super().__init__(x, y, height, width)

    def movements(self):
        # 每次调用都获取最新的按键状态
        key_pressed = pygame.key.get_pressed()
        if key_pressed[pygame.K_a]:
            self.pos_x -= 5
        if key_pressed[pygame.K_d]:
            self.pos_x += 5
        if not self.jump_status:
            if key_pressed[pygame.K_w]: 
                self.jump_status = True
        else:
            self._jump()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 14:54:04