Reputation: 378
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()
This is a test code i made to visualize my question. What i'm asking is basically a method by which i can somehow request the types and number of children inside my surface object. For example if i had a circle, a square, a line or other type of object within my surface i want a list of all the types that are in my surface and i also want the number.
Upvotes: 1
Views: 201
Reputation: 20478
Surfaces only hold information about the pixels/colors they consist of, not about the shapes that you draw on them. If you want to know how many shapes there are, you have to use lists, pygame.sprite.Group
s or other data structures to store information about them.
You already have the blocks (which are pygame.Rect
s) in your blocks
list, so you just need to call len(blocks)
to get the number of blocks. You can as well use rects to store circles in a circles
list.
Eventually you could create your own Shape
classes or use pygame.sprite.Sprite
s and put instances of them into your lists/sprite groups.
Upvotes: 1