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

运行游戏时出现AttributeError:Pipe类无moving_x属性的问题求助

解决AttributeError: type object 'Pipe' has no attribute 'moving_x'错误

问题情况

运行游戏时反复弹出错误:

AttributeError: type object 'Pipe' has no attribute 'moving_x'

你的Pipe类初始化代码:

def __init__(self, xpos):
    self.fixed_y = random.randint(150, 650)
    self.moving_x = xpos

    self.bot_surf = pygame.image.load("graphics/pipe.png").convert_alpha()
    self.top_surf = pygame.transform.flip(self.bot_surf, False, True)

出错的计分判断代码:

if bird_rect.centerx == Obstacle.Pipe.moving_x:
    score_surf = font.render(str(int(score)), False, ("#FFFFFF"))
    score += 1
screen.blit(score_surf, (550, 100))

错误原因

moving_x是你在__init__里定义的实例属性——只有当你创建Pipe类的具体对象(比如pipe = Obstacle.Pipe(800))时,这个属性才属于该对象。而你现在直接用类名Obstacle.Pipe去访问它,相当于找类本身的属性,自然找不到,就会报错。

修复方法

1. 单个管道场景

先确保已经创建了Pipe实例:

# 游戏初始化阶段创建管道实例
pipe = Obstacle.Pipe(初始x坐标)

然后修改判断代码,改用实例访问属性:

if bird_rect.centerx == pipe.moving_x:
    score_surf = font.render(str(int(score)), False, "#FFFFFF")
    score += 1
screen.blit(score_surf, (550, 100))

2. 多管道场景(更常见)

如果游戏里有多个管道,一般用列表存储所有实例,遍历列表逐个判断:

# 初始化管道列表
pipes = []

# 游戏循环中的计分逻辑
for pipe in pipes:
    if bird_rect.centerx == pipe.moving_x:
        score_surf = font.render(str(int(score)), False, "#FFFFFF")
        score += 1
screen.blit(score_surf, (550, 100))

3. 避免重复计分(优化)

上面的代码可能在多帧内重复触发计分,给每个管道加个标记解决:

# 在Pipe类的__init__中新增标记
def __init__(self, xpos):
    self.fixed_y = random.randint(150, 650)
    self.moving_x = xpos
    self.scored = False  # 标记是否已计分

    self.bot_surf = pygame.image.load("graphics/pipe.png").convert_alpha()
    self.top_surf = pygame.transform.flip(self.bot_surf, False, True)

修改计分逻辑:

for pipe in pipes:
    if bird_rect.centerx == pipe.moving_x and not pipe.scored:
        score_surf = font.render(str(int(score)), False, "#FFFFFF")
        score += 1
        pipe.scored = True  # 标记为已计分,防止重复触发
screen.blit(score_surf, (550, 100))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:55:22