import pygame
pygame.init()

# 窗口大小
WIDTH, HEIGHT = 600, 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("简易颜色识别")

# 测试色块
RED = (255, 0, 0)
screen.fill((40, 40, 40))
pygame.draw.rect(screen, RED, (200,150,100,100))

clock = pygame.time.Clock()
running = True

# 颜色匹配函数（带容错，不用严格一模一样）
def check_color(pixel_rgb, target, tolerance=10):
    r,g,b = pixel_rgb
    tr,tg,tb = target
    return abs(r-tr)<=tolerance and abs(g-tg)<=tolerance and abs(b-tb)<=tolerance


while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        # 鼠标左键按下读取像素
        if event.type == pygame.MOUSEBUTTONDOWN:
            x, y = pygame.mouse.get_pos()
            rgba = screen.get_at((x, y))
            rgb = rgba[:3]
            print(f"点击坐标({x},{y}) RGB = {rgb}")
            
            # 判断是不是红色方块
            if check_color(rgb, RED):
                print(">>> 识别到红色色块！")


    pygame.display.flip()
    clock.tick(60)

pygame.quit()
def find_target_color(surface, target_rgb, tol=15):
    w,h = surface.get_size()
    for x in range(0,w,5):   # 隔5像素扫描，提速
        for y in range(0,h,5):
            c = surface.get_at((x,y))[:3]
            if check_color(c,target_rgb,tol):
                return (x,y)
    return None

# 使用：pos = find_target_color(screen,(255,0,0))
# if pos: print("找到红色位置",pos)

