按行和列数均分矩形对象函数

"""
   按行和列数均分矩形对象函数
   
"""
import pygame
from random import randint

def split_rect(rect,rows,cols):
    """
     均分矩形对象,rect是四元组,rect[0]是左上角x坐标,
     rect[1]是左上角y坐标, rect[2]是宽度,rect[3]是高度
     rect:源矩形,rows:行数,cols:列数
     返回列表
     """
    rect_list = [] 
    width = rect[2]
    height = rect[3]
    row_height = height//rows   # 行高
    col_width = width//cols     # 列宽
    x = 0
    y = 0
    for r in range(0,rows):
        for c in range(0,cols):           
            rect = (x,y,col_width,row_height)
            rect_list.append(rect)
            x = x +  col_width 
        x = 0
        y = y +  row_height 
    return rect_list

width,height = 900,700
rect = (0,0,width,height)
rect_list = split_rect(rect,100,100)
print(rect_list[-1])
image = pygame.Surface((width,height))
for rect in rect_list:
    r = randint(0,255)
    g = randint(0,255)
    b = randint(0,255)
    # print(rect)
    image.fill((r,g,b),rect = pygame.Rect(*rect))

pygame.image.save(image,"c:/彩色格子图形_定义函数.png")