Как заставить круговой спрайт появляться - pygame - PullRequest
1 голос
/ 26 апреля 2020

Мне нужно, чтобы мой спрайт появился в окне Pygame. Как мне это сделать? Важный код:

#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 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_rect() на self.rect = self.image.get_circle(), поскольку мой спрайт является круглым, но это возвращает:

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

Могу ли я получить некоторую помощь, пожалуйста?

1 Ответ

2 голосов
/ 26 апреля 2020

get_circle() не существует. См. pygame.Surface. get_rect() возвращает прямоугольник с шириной и высотой поверхности. Круг - это просто пучок пикселей на поверхности, объекта «круг» нет. pygame.draw.circle() закрашивает некоторые пиксели на поверхности, которые располагаются в круглую форму.

Вы должны отцентрировать окружность к объекту Surface self.image. Размер поверхности равен (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, создавать поверхность нет смысла. размером 60х80. Более того, я рекомендую передать координаты x и y и 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)

Не используйте одно и то же имя для класса и экземпляр класса, потому что имя переменной охватывает имя класса. В то время как Имена классов должны обычно использовать соглашение CapWords, Имена переменных должны быть строчными.
Таким образом, имя класса Player и имя переменной (экземпляра) это player.

...