python - 如何在 Pygame 环境中绘制矩形和圆形

标签 python pygame sprite pygame-surface

我正在尝试使用各种形状的 Sprite 创建一个 pygame 环境,但我的代码似乎不起作用。这是我所拥有的:

class Object(pygame.sprite.Sprite):

    def __init__(self, position, color, size, type):

        # create square sprite
        pygame.sprite.Sprite.__init__(self)
        if type == 'agent':
            self.image = pygame.Surface((size, size))
            self.image.fill(color)
            self.rect = self.image.get_rect()
        else:
            red = (200,0,0)
            self.image = pygame.display.set_mode((size, size))
            self.image.fill(color)
            self.rect = pygame.draw.circle(self.image, color,(), 20)


        # initial conditions
        self.start_x = position[0]
        self.start_y = position[1]
        self.state = np.asarray([self.start_x, self.start_y])
        self.rect.x = int((self.start_x * 500) + 100 - self.rect.size[0] / 2)
        self.rect.y = int((self.start_y * 500) + 100 - self.rect.size[1] / 2)
有没有人注意到 Object 类有任何问题?

最佳答案

您必须创建一个 pygame.Surface , 而不是创建一个新窗口 ( pygame.display.set_mode )。
Surface 的像素格式必须包含每像素 alpha ( SRCALPHA )。圆的中心点必须是曲面的中心。半径
必须是 Surface 大小的一半:

self.image = pygame.Surface((size, size), pygame.SRCALPHA)
radius = size // 2
pygame.draw.circle(self.image, color, (radius, radius), radius)
类(class)Object :
class Object(pygame.sprite.Sprite):

    def __init__(self, position, color, size, type):

        # create square sprite
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.Surface((size, size), pygame.SRCALPHA)
        self.rect = self.image.get_rect()
        
        if type == 'agent':
            self.image.fill(color)
        else:
            radius = size // 2
            pygame.draw.circle(self.image, color, (radius, radius), radius)

        # initial conditions
        self.start_x = position[0]
        self.start_y = position[1]
        self.state = np.asarray([self.start_x, self.start_y])
        self.rect.x = int((self.start_x * 500) + 100 - self.rect.size[0] / 2)
        self.rect.y = int((self.start_y * 500) + 100 - self.rect.size[1] / 2)

关于python - 如何在 Pygame 环境中绘制矩形和圆形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68854226/

相关文章:

Python (pygame) : Get image color information?

android - OpenGL ES 2.0——简单粒子系统的最佳途径

python - 有没有一种Python式的方法将基于范围的分段函数分组为单个函数?

python - PyCharm SQLAlchemy 自动完成

python - 如何在pygame中使物体移动一定角度

python - 鼠标点击矩形的困境

python - 通过自定义 AMI 获取 EC2 实例的 AWS CloudFormation 中的用户数据不起作用

python - 如何防止我的 FOR 循环过早结束?

unity3d - Sprite 意外地 reshape

python - Pygame 查询 - 在同一类中生成多个 Sprite