2017-05-05 19 views
1
import pygame as pg # rename pygame module with pg 
import sys # application termination for some windows machines 

def main(): 
    pg.init() #initialize pygame 
    clock = pg.time.Clock() #create a time object 
    fps = 30 #game frame rate 
    size = [400, 400] #screen size 
    bg = [255, 255, 255] #screen background 

    screen = pg.display.set_mode(size) 
    surface = pg.Surface(screen.get_size()) 

    blocks = [] 
    block_color = [255, 0, 0] 

    def create_blocks(blocks): 
     """ function will create blocks and assign a position to them""" 

     block_width = 20 
     block_height = 20 

     # nested for loop for fast position assignment 
     for i in range(0, 40, block_width): 
      for j in range(0, 40, block_height): 
       # offsets block objects 20px from one another 
       x = 2*i 
       y = 2*j 

       #block rect object 
       rect = pg.Rect(x, y, block_width, block_height) 

       #append rect to blocks list 
       blocks.append(rect) 

    def draw_blocks(surface, blocks, block_color): 
     """ draws blocks object to surface""" 

     #loops through rects in the blocks list and draws them on surface 
     for block in blocks: 
      pg.draw.rect(surface, block_color, block) 

    create_blocks(blocks) 

    while True: 
     for event in pg.event.get(): 
      if event.type == pg.QUIT: 
       return False 

     screen.blit(surface, [0, 0]) 
     surface.fill(bg) 

     draw_blocks(surface, blocks, block_color) 

     pg.display.update() 
     clock.tick(fps) 

    pg.quit() # closses pygame window 
    sys.exit # for machines that wont accept pygame quit() event 

if __name__ == '__main__': 
    main() 

这是一个测试代码,用于显示我的问题。我问的基本上是一种方法,我可以以某种方式请求我的表面对象内的儿童的类型和数量。例如,如果我在表面中有一个圆形,一个正方形,一条线或其他类型的对象,我想要一个列表中的所有类型,并且我也想要这个数字。我如何要求pygame中的表面儿童的类型和数量?

回答

1

曲面只保存关于它们所包含的像素/颜色的信息,而不是关于您在其上绘制的图形的信息。如果你想知道有多少形状,你必须使用列表,pygame.sprite.Group或其他数据结构来存储关于它们的信息。

您已经在您的blocks列表中有块(即pygame.Rect),所以您只需拨打len(blocks)即可获取块的数量。您还可以使用rects来将圆圈存储在circles列表中。

最终,您可以创建自己的Shape类或使用pygame.sprite.Sprite s并将它们的实例放入您的列表/精灵组中。