'鸡'对象没有属性'rect'

时间:2016-01-14 12:49:32

标签: python pygame

我目前正在使用python编写更大的程序。这是一个简单的游戏,但我有一个错误。有人能帮助我吗?

错误

          Traceback (most recent call last):
  File "C:/Users/kkuja/Desktop/game.py", line 36, in <module>
    MainWindow.MainLoop()
  File "C:/Users/kkuja/Desktop/game.py", line 17, in MainLoop
    self.chicken_sprites.draw(self.screen)
  File "C:\Users\kkuja\AppData\Local\Programs\Python\Python35\lib\site-packages\pygame\sprite.py", line 475, in draw
    self.spritedict[spr] = surface_blit(spr.image, spr.rect)
AttributeError: 'Chicken' object has no attribute 'rect'

代码

import os, sys
import pygame

class Game:
    def __init__(self, width=640, height=480):
        pygame.init()
        self.width = width
        self.height = height
        self.screen = pygame.display.set_mode([self.width, self.height])
    def MainLoop(self):
        self.ChickenLoad();

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        self.chicken_sprites.draw(self.screen)
        pygame.display.flip()

    def ChickenLoad(self):
        self.chicken = Chicken()
        self.chicken_sprites = pygame.sprite.Group(self.chicken)

class Chicken(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("chic.jpg")


 if __name__ == "__main__":
    MainWindow = Game()
    MainWindow.MainLoop()

提前致谢!

1 个答案:

答案 0 :(得分:3)

在您的代码self.chicken_sprites.draw(self.screen)中的函数chicken.rect正在尝试访问,但您没有定义它。

如果您参考official documentation,您可以找到代码的和平

class Block(pygame.sprite.Sprite):

    # Constructor. Pass in the color of the block,
    # and its x and y position
    def __init__(self, color, width, height):
       # Call the parent class (Sprite) constructor
       pygame.sprite.Sprite.__init__(self)

       # Create an image of the block, and fill it with a color.
       # This could also be an image loaded from the disk.
       self.image = pygame.Surface([width, height])
       self.image.fill(color)

       # Fetch the rectangle object that has the dimensions of the image
       # Update the position of this object by setting the values of rect.x and rect.y
       self.rect = self.image.get_rect()

您未在self.rect中设置Chicken,它应该如下所示。

class Chicken(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("chic.jpg")
        self.rect = self.image.get_rect(); #here rect is created