为什么我们必须使用 self.rect 和 self.image 来确定 Rect 和 Surf on Sprites?

Why We Have to Use self.rect and self.image to Determine Rect and Surf on Sprites?

我是 pygame 的新人,所以我对 sprite 了解不多。我想让我的代码更干净,所以我使用了精灵。为了用 rect 显示我的图像,我写道:

    self.frame_index = 0
    self.surf = self.frames[self.frame_index]
    self.frame_rect = self.surf.get_rect(midtop = (self.x_pos, self.y_pos))

但它引发了 AttributeError: 'Enemy' object has no attribute 'image' 错误。敌人是我的 class' 名字。当我使用 self.image 和 self.rect 而不是 self.surf 和 self.frame_rect 我的代码工作正常。

我的主要问题是:当我们使用精灵来确定我们的表面和矩形时,为什么我们必须使用 self.rect 和 self.image?

My main question is: Why we have to use self.rect and self.image when we use a sprite to determine our surface and rect?

这与pygame.sprite.Group. Groups are used to manage Sprites. pygame.sprite.Group.draw() and pygame.sprite.Group.update()有关,是pygame.sprite.Group提供的方法。

前者委托给包含的pygame.sprite.Sprites - you have to implement the method. See pygame.sprite.Group.update()update方法:

Calls the update() method on all Sprites in the Group [...]

后者使用包含的pygame.sprite.Spriteimagerect属性来绘制对象——你必须确保pygame.sprite.Sprite具有所需的属性。见 pygame.sprite.Group.draw():

Draws the contained Sprites to the Surface argument. This uses the Sprite.image attribute for the source surface, and Sprite.rect. [...]


最小示例:

import pygame

pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()

class Player(pygame.sprite.Sprite):
    
    def __init__(self, center_pos):
        super().__init__() 
        self.image = pygame.Surface((40, 40))
        self.image.fill((0, 255, 0))
        self.rect = self.image.get_rect(center = center_pos)
    
    def update(self, surf):
        keys = pygame.key.get_pressed()
        self.rect.x += (keys[pygame.K_d]-keys[pygame.K_a]) * 5
        self.rect.y += (keys[pygame.K_s]-keys[pygame.K_w]) * 5
        self.rect.clamp_ip(surf.get_rect())

all_sprites = pygame.sprite.Group([Player(window.get_rect().center)])

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    all_sprites.update(window)

    window.fill(0)
    all_sprites.draw(window)
    pygame.display.flip()

pygame.quit()
exit()