【问题标题】:Drawing polygons in pygame using list使用列表在pygame中绘制多边形
【发布时间】:2025-11-26 20:25:01
【问题描述】:

我想画很多简单的多边形。所以我决定制作一个由所有多边形组成的元组,这样我就可以使用 for poly in POLYGONS.

POLYGONS = (sc,(255,255,255),(0,50),ect.)

for poly in POLYGONS:
    pygame.draw.polygon(poly)

但是当我真正这样做时,函数将这个元组作为 tge 第一个参数。有什么办法可以提高效率(没有 i[0],i[1] 等等)? 我是一个初学者程序员,所以这个问题听起来很明显。

【问题讨论】:

    标签: python pygame


    【解决方案1】:

    你必须创建一个元组列表:

    POLYGONS = [
        ((255, 0, 0), [(100, 50), (50, 150), [150, 150]], True),
        ((0, 0, 255), [(100, 150), (50, 50), [150, 50]], True)
    ]
    

    你必须用asterisk (*) operator解压缩元组:

    for poly in POLYGONS:
        pygame.draw.polygon(window, *poly)
    

    小例子:

    import pygame
    
    pygame.init()
    window = pygame.display.set_mode((200, 200))
    clock = pygame.time.Clock()
    
    POLYGONS = [
        ((255, 0, 0), [(100, 50), (50, 150), [150, 150]], True),
        ((0, 0, 255), [(100, 150), (50, 50), [150, 50]], True)
    ]
    
    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False 
    
        window_center = window.get_rect().center
    
        window.fill(0)
        for poly in POLYGONS:
            pygame.draw.polygon(window, *poly)
        pygame.display.flip()
        clock.tick(60)
    
    pygame.quit()
    exit()
    

    【讨论】: