有没有一种方法可以简化此矩形绘图代码?

时间:2020-01-06 10:47:37

标签: python python-3.x pygame drawing simplify

我想知道这部分代码是否可以简化,看起来有点重复

def show(self, W, screen):
    x = self.i * W
    y = self.j * W
    rect = pygame.Rect(x, y, W, W)
    pygame.draw.rect(screen, BG, rect)
    # TODO optimize this code
    if self.new:
        # TODO better popup animation
        rect.inflate(-50, -50)
        pygame.draw.rect(screen,(255, 255, 255), rect)
        rect.inflate(10, 10)
        pygame.draw.rect(screen, (255, 255, 255), rect)
        self.new = False
    else:
        if self.value == 2:
            pygame.draw.rect(screen, Sqr2, rect)
        elif self.value == 4:
            pygame.draw.rect(screen, Sqr4, rect)
        elif self.value == 8:
            pygame.draw.rect(screen, Sqr8, rect)
        elif self.value == 16:
            pygame.draw.rect(screen, Sqr16, rect)
        elif self.value == 32:
            pygame.draw.rect(screen, Sqr32, rect)
        elif self.value == 64:
            pygame.draw.rect(screen, Sqr64, rect)
        elif self.value == 128:
            pygame.draw.rect(screen, Sqr128, rect)
        elif self.value == 256:
            pygame.draw.rect(screen, Sqr256, rect)
        elif self.value == 512:
            pygame.draw.rect(screen, Sqr512, rect)
        elif self.value == 1024:
            pygame.draw.rect(screen, Sqr1024, rect)
        pygame.draw.rect(screen, BORDER, rect, 10)

Sqr2,4,8 ...是我导入的另一个文件中的颜色元组

Sqr2 = (245, 245, 245)
Sqr4 = (245, 245, 220)
Sqr8 = (255, 160, 122)
Sqr16 = (255, 127, 80)
Sqr32 = (255, 99, 71)
Sqr64 = (255, 0, 0)
Sqr128 = (255, 250, 96)
Sqr256 = (240, 224, 80)
Sqr512 = (240, 224, 16)
Sqr1024 = (250, 208, 0)

2 个答案:

答案 0 :(得分:3)

我不确定您如何导入文件-如果将文件导入到dict中,可能会更干净,例如:

d = {2:(245,245,245),4:(245,245,220),...#etc}

else:
    pygame.draw.rect(screen,d[self.value],rect)
pygame.draw.rect(screen,BORDER,rect,10)

答案 1 :(得分:2)

您可以在字典中定义Sqr变量,如下所示:

Sqrs = {2: (245, 245, 245),
        4: (245, 245, 220),
        8: (255, 160, 122),
        16: (255, 127, 80),
        32: (255, 99, 71),
        64: (255, 0, 0),
        128: (255, 250, 96),
        256: (240, 224, 80),
        512: (240, 224, 16),
        1024: (250, 208, 0)}

然后使用

绘制形状
pygame.draw.rect(screen, Sqrs[self.value], rect)