2011-10-23 31 views
2

我不知道这是否是正确的网站,但你们一直如此的帮助之前,我想对我使用Python和有问题得到您的指点pygame的。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() 

谢谢你的帮助。 :-)

回答

2

在块构建,你叫self.image.fill(color)。这将用这种颜色填充精灵的整个图像,所以你得到一个矩形。

的示例代码,你有电话self.image.set_colorkey(white)做填充后,这样,当它被绘制,背景填充是透明的。这可能是最快的解决方案。

+0

辉煌,感谢您的帮助,我现在已经定了! :-) – Singular1ty

1

您正在用给定的color填充表面,然后在相同的color中绘制您的形状。当然,它不会以这种方式显示,而且您只会看到长方形的纯色表面。

+0

感谢您的帮助,我已经给我剔新来的家伙,但感谢你的投入,现实生活中的金丹有! :-) – Singular1ty