获取AttributeError:类型对象“Pipe1”没有属性“height”

2024-09-28 05:24:04 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我一直收到错误AttributeError:类型对象“Pipe1”没有属性“height” 我试图用pygame/python创建flappy bird。只是一个注释,这还没有完成,只是想看看我有没有什么大的错误。如果有帮助的话,这就是python2.7.7。在

import pygame, random, sys

pygame.init()
screen = pygame.display.set_mode([284, 512])

pipex = 335

class Bird(pygame.sprite.Sprite):
    def __init__(self, image, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(image)
        self.rect = self.image.get_rect()
        self.pos = [x, y]

    def move():
        self.pos[0] += 3
        self.pos[1] += 3
        self.rect.center = self.pos

class Pipe1(pygame.sprite.Sprite):
    def __init__(self, image, height):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(image)
        self.rect = self.image.get_rect()
        self.height = height
        self.pos = [pipex, height]
        oppositepipe = Pipe2('flappybirdpipe2.png')

    def scroll():
        global pipex
        self.pos[0] -= 3
        self.rect.center = self.pos

class Pipe2(pygame.sprite.Sprite):
    def __init__(self, image):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(image)
        self.rect = self.image.get_rect()
        self.height = 397 - Pipe1.height
        self.pos = [pipex, self.height]

    def scroll():
        global pipex
        self.pos[0] -= 3
        self.rect.center = self.pos

def draw_pipes():
    newpipe = Pipe1('flappybirdpipe.png', random.randint(115, screen.get_height()))

while True:
    draw_pipes()
    for event in pygame.event.get():
        if event.type == pygame.QUIT():
            pygame.quit()
            sys.exit()

以下是错误消息:

^{pr2}$

Tags: posrectimageselfgetinitdef错误
1条回答
网友
1楼 · 发布于 2024-09-28 05:24:04

我不认为你从拥有两个不同的管道课程中得到什么好处。它们之间唯一真正不同的是图像,而且每个管道基本上都有相同的行为,因此用一个类来表示它们是有意义的。我觉得你应该试试:

  • 只有一个Pipe
  • 将为管道生成高度的代码与Pipe类分开,如 这就是你最初的问题所在。在

基本上,您应该能够将Pipe1Pipe2和{}代码替换为:

class Pipe(pygame.sprite.Sprite):
    def __init__(self, image, height):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(image)
        self.rect = self.image.get_rect()
        self.height = height
        self.pos = [pipex, height]

    def scroll():
        # You don't actually do anything with pipex in this
        # method, so not sure why you were referring to it?
        self.pos[0] -= 3
        self.rect.center = self.pos

def draw_pipes():
    pipe1_height = random.randint(115, screen.get_height())
    pipe1 = Pipe('flappybirdpipe.png', pipe1_height)
    pipe2_height = 397 - pipe1_height
    pipe2 = Pipe('flappybirdpipe2.png', pipe2_height)

相关问题 更多 >

    热门问题