Python Pygame:基于构造函数参数绘制椭圆或矩形

Python Pygame:基于构造函数参数绘制椭圆或矩形,python,constructor,sprite,pygame,Python,Constructor,Sprite,Pygame,我不知道这是不是一个正确的网站,但你们以前帮了我很大的忙,我想听听你们对Python和Pygame的一个问题的建议 我正在做一个简单的游戏,最近才开始学习Python(到目前为止我很喜欢它),目前我正在使用一个精灵构造函数。此构造函数将管理我的对象,但我希望它根据传递给它的参数绘制椭圆或矩形 #My code class Block(pygame.sprite.Sprite): #Variables! speed = 2 indestructible = True

我不知道这是不是一个正确的网站,但你们以前帮了我很大的忙,我想听听你们对Python和Pygame的一个问题的建议

我正在做一个简单的游戏,最近才开始学习Python(到目前为止我很喜欢它),目前我正在使用一个精灵构造函数。此构造函数将管理我的对象,但我希望它根据传递给它的参数绘制椭圆或矩形

#My code
class Block(pygame.sprite.Sprite):
    #Variables!
    speed = 2
    indestructible = True
    #Constructor
    def __init__(self, color, width, height, name, shapeType):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface([width,height])
        self.image.fill(color)
        #Choose what to draw
        if shapeType == "Ellipse":
            pygame.draw.ellipse(self.image,color,[0,0,width,height])
        elif shapeType == "Rect":
            pygame.draw.rect(self.image,color,[0,0,width,height])
        elif shapeType == "":
            print("Shape type for ",name," not defined.")
            pygame.draw.rect(self.image,color,[0,0,width,height])
        #Init the Rect class for sprites
        self.rect = self.image.get_rect()
我用于绘制正方形的编码如下所示:

#Add 'white star' to the list
for i in range(random.randrange(100,200)):
    whiteStar = Block(white, 1, 1, "White Star", "Rect")
    whiteStar.rect.x = random.randrange(size[0])
    whiteStar.rect.y = random.randrange(size[1])
    whiteStar.speed = 2
    block_list.add(whiteStar)
    all_sprites_list.add(whiteStar)
这真是太棒了。它为我画了一个完美的白色正方形。但这不起作用:

#Create Planet
planet = Block(green, 15,15, "Planet", "Ellipse")
planet.rect.x = random.randrange(size[0])
planet.rect.y = 30
planet.speed = 1
block_list.add(planet)
all_sprites_list.add(planet)
“行星”正确地繁殖,但它是以正方形的形式繁殖的。为什么会这样?我怎样才能修好它?我应该使用位图来更正此问题吗?还是我的编码错了

为了澄清,我知道一个事实,即
self.rect=self.image.get_rect()
可以绘制椭圆,因为下面的编码可以工作

#Not the code I'm using, but this works and proves self.rect = self.image.get_rect() is not the cause
# 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(white)
    self.image.set_colorkey(white)
    pygame.draw.ellipse(self.image,color,[0,0,width,height])

    # Fetch the rectangle object that has the dimensions of the image
    # image.
    # Update the position of this object by setting the values 
    # of rect.x and rect.y
    self.rect = self.image.get_rect()

谢谢你的帮助。:-)

用给定的
颜色填充曲面,然后用相同的
颜色绘制形状。当然,它不会以这种方式显示,您只需获得纯色的矩形曲面。

在块构造函数中,您可以调用
self.image.fill(color)
。这将用该颜色填充精灵的整个图像,因此得到一个矩形


您的示例代码在完成填充后调用了
self.image.set_colorkey(white)
,以便在绘制时,背景填充是透明的。这可能是最快的解决方案。

谢谢你的帮助,我已经为新来的家伙打了个招呼,但谢谢你的投入,这是一个真正的救命稻草!:-)