Search code examples
pythonpython-3.xpygamedrawingsimplify

Is there a way I can simplify this rectangle drawing code?


I was wondering if this part of code can be simplified, it looks a bit repetitive

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 ... are color tuples from another file that i've imported

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)

Solution

  • I'm not sure how you import the files - if you imported them in a dict it could be cleaner eg:

    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)