Pygame AttributeError:类User_Ship没有属性'rect'

时间:2013-11-13 01:31:16

标签: python pygame 2d-games

我正在制作太空入侵者克隆,我遇到了一些麻烦。所以现在我有用户控制的船(目前是鼠标,因为这是我在上一个游戏的python文件夹中所拥有的,但我最终会改变它)在屏幕底部来回移动,这就是我想要的,但是当我按空格键时我无法拍摄。我可以启动游戏,但当我按空格键时,我收到此错误:

AttributeError:类User_Ship没有属性'rect'

我不知道如何解决它。此外,我认为一旦修复,我的船仍然不会拍,因为我很难把代码下来,所以可能有一些错误。如果你能给我一些提示和技巧让我的船射击,那就太好了。感谢

from pygame import *
import pygame

size_x = 900
size_y = 650

class Object:
    def disp(self, screen):
        screen.blit(self.sprite, self.rect)

class User_Ship(Object):
    def __init__(self):
        self.sprite = image.load("mouse.bmp")
        self.rect = self.sprite.get_rect()
        self.rect.centerx = size_x/2
        self.rect.centery = size_y - 40
        self.count = 0
        self.move_x = 0
        self.move_y = 0

    def checkwith(self, otherrect):
        if self.rect.colliderect(otherrect):
            exit()

    def cycle(self):
        self.rect.centerx += self.move_x
        if self.rect.centerx < 0:
            self.rect.centerx = 0
        if self.rect.centerx > size_x:
            self.rect.centerx = size_x

        self.rect.centery += self.move_y
        if self.rect.centery < 0:
            self.rect.centery = 800

    def right(self):
        self.move_x += 10

    def left(self):
        self.move_x -= 10

    def stop_x(self):
        self.move_x = 0

    def stop_y(self):
        self.move_y = 0

class Missile(Object):
    def __init__(self):
        self.sprite = image.load("missile.png")
        self.rect = self.sprite.get_rect()

    def update(self):
        self.rect.move_ip(self.speed)
        if self.rect.left < 0 or self.rect.right > size_x or self.rect.top < 0 or self.rect.bottom > size_y:
            self.kill()

missiles = pygame.sprite.RenderUpdates()


init()
screen = display.set_mode((size_x, size_y))
m = User_Ship()
#b = Missile()
clock = time.Clock()

while True:
    for e in event.get():
        if e.type == QUIT:
            quit()
        if e.type == KEYDOWN:
            if e.key == K_RIGHT:
                m.right()
            elif e.key == K_LEFT:
                m.left()
            if (e.key == K_SPACE):
                missiles.add(Missile("missile.png",(User_Ship.rect.centerx)))
        if e.type == KEYUP:
            if e.key == K_RIGHT or e.key == K_LEFT:
                m.stop_x()

    missiles.draw(screen)
    m.cycle()
    screen.fill((255,255,255))
    m.disp(screen)
#   b.disp(screen)
    display.flip()

1 个答案:

答案 0 :(得分:3)

rect不是类属性,而是实例属性。所以,您可能希望像这样访问它

missiles.add(Missile("missile.png",(m.rect.centerx)))