如何使圆形精灵出现 - pygame

How to make a circular sprite appear - pygame

我需要我的精灵出现在 pygame window 中。我该怎么做呢?重要代码:

#This will be a list that will contain all the sprites we intend to use in our game.
    all_sprites_list = pygame.sprite.Group()


    #creating the player
    player = player(BLUE, 60, 80, 70)
    player.rect.x = 200
    player.rect.y = 300

在代码的末尾我有 pygame.display.update()。我的精灵 class(正确导入):

class player(pygame.sprite.Sprite):
    def __init__(self, color, width, height, speed):
        # Call the parent class (Sprite) constructor
        super().__init__()

        # Pass in the color of the player, and its x and y position, width and height.
        # Set the background color and set it to be transparent
        self.image = pygame.Surface([width, height])
        self.image.fill(WHITE)
        self.image.set_colorkey(WHITE)

        #Initialise attributes of the car.
        self.width = width
        self.height = height
        self.color = color
        self.speed = speed

        # Draw the player
        pygame.draw.circle(self.image, self.color, (400, 600), 5)

        self.rect = self.image.get_rect()

可能是一个愚蠢的人为错误。我尝试用 self.rect = self.image.get_circle() 替换 self.rect = self.image.get_rect() 因为我的精灵是圆形的但是这个 returns:

self.rect = self.image.get_circle()
AttributeError: 'pygame.Surface' object has no attribute 'get_circle'

请问有什么帮助吗?

get_circle() 不存在。请参阅 pygame.Surface. get_rect() returns a rectangle with the width and height of the Surface. The circle is just a buch of pixels on the surface, there is no "circle" object. pygame.draw.circle() 在 Surface 上绘制一些像素,这些像素排列成圆形。

您必须将圆圈以 Surface 对象为中心 self.image。 Surface的大小是(width, height),因此中心是(width // 2, height // 2):

self.image = pygame.Surface([width, height])
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)
pygame.draw.circle(self.image, self.color, (width // 2, height // 2), 5)
self.rect = self.image.get_rect()

请注意,由于圆的半径为 5,因此创建大小为 60x80 的曲面没有任何意义。此外,我建议将 xy 坐标以及 radius 传递给 player

class Player(pygame.sprite.Sprite):
    def __init__(self, color, x, y, radius, speed):
        # Call the parent class (Sprite) constructor
        super().__init__()

        # Pass in the color of the player, and its x and y position, width and height.
        # Set the background color and set it to be transparent
        self.image = pygame.Surface((radius*2, radius*2))
        self.image.fill(WHITE)
        self.image.set_colorkey(WHITE)

        #Initialise attributes of the car.
        self.color = color
        self.speed = speed

        # Draw the player
        pygame.draw.circle(self.image, self.color, (radius, radius), radius)

        self.rect = self.image.get_rect(center = (x, y))
all_sprites_list = pygame.sprite.Group()

player = Player(BLUE, 200, 300, 5, 70)
all_sprites.add(player)

不要为class和class的实例使用相同的名称,因为变量名称覆盖了class名称。而 Class Names should normally use the CapWords convention, Variable Names 应该是小写的。
所以 class 的名称是 Player,变量(实例)的名称是 player