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

标签 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()

提前致谢!

最佳答案

在函数 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()

你没有在你的Chicken中设置self.rect,它应该是这样的。

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

关于python - '鸡'对象没有属性 'rect',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34790063/

相关文章:

python - Pygame 初学者程序,屏幕未定义

windows - 我无法使用python播放音频

python - Flask-admin 是否在运行时导入 html 模板?

python - Pandas Groupby 计算 ewm 未按预期工作

python - 用自定义图案填充 pygame 字体

python - 在第二个 SSH 终端中运行第二个 pygame 程序(用于第二个显示)会暂停,直到按下 ^C

python - Pygame如何让背景不断滚动?

python - 解析Python函数声明

python - 如何读取文件夹中的文件名并按字母顺序和递增顺序访问它们?

python - 如何验证 Flask 应用程序中的 URL 参数?