Search code examples
pythonpygamedrawrect

How can i creat a multiple rect by pygame?


i want to creat a game like Pong but just one player from downside, and multiple box from up side, when the ball hit the box, the box will disappear. I can't remember name of that game but i don't know hot to create multiple rectangles. I can draw it by easy way


Solution

  • Use pygame.draw.rect to draw a rectangle:

    pygame.draw.rect(screen, color, (x, y, width, height))
    

    Use nested loops to draw create the locations of multiple rectangles

    rectwidth = 40
    rectheight = 40
    rectdist = 10
    
    block_positions = []
    for i in range(10):
        for j in range(2)
            x = 100 + i * (rectdist + rectwidth) 
            y = 100 + j * (rectdist + rectheight)
            block_positions.append((x, y)) 
    

    Draw the rectangles in a loop:

    for x, y in block_positions:
        pygame.draw.rect(screen, (255, 255, 255), (x, y, rectwidth, rectheight))