我如何请求 pygame 中地表子项的类型和数量?

how do i request the types and number of surface children in pygame?

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()

这是我为可视化我的问题而制作的测试代码。我要问的基本上是一种方法,通过它我可以以某种方式请求我的表面对象内的子项的类型和数量。例如,如果我的表面上有一个圆、一个正方形、一条线或其他类型的物体,我想要一个表面上所有类型的列表,我还想要一个数字。

表面仅包含有关 pixels/colors 它们构成的信息,而不是有关您在其上绘制的形状的信息。如果你想知道有多少个形状,你必须使用列表、pygame.sprite.Groups 或其他数据结构来存储有关它们的信息。

您的 blocks 列表中已有块(pygame.Rect),因此您只需调用 len(blocks) 即可获取块数。您也可以使用 rects 将圆圈存储在 circles 列表中。

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