Line is not drawn (It seems that pygame.draw.polygon is not running)

254 Views Asked by At

I made Button frame. But Square is not drawn.

class button:
    def __init__(self,screen,size): # size -->(width,height)
        self.width = size[0]
        self.height = size[1]
        self.screen = screen
    def Buttongenerate(self,TEXT,POS):
        font = pygame.font.Font(None,self.height//3)
        text = font.render(TEXT,True,(250,250,250))
        textsize = font.size(TEXT)
        TEXTPOS = [self.width+(self.width-textsize[0])/2,\
           self.height+(self.height-textsize[1])/2]
        self.screen.blit(text,TEXTPOS)
        pygame.draw.polygon(self.screen, (250,250,250), [[POS[0],POS[1]],\ 
        [POS[0]+self.width,POS[1]],[POS[0]+self.width,POS[1]+self.height],\ 
        [POS[0],POS[1]+self.height]], 2)


while True:
    screen.fill((0,0,0))
    buttontest2 = button(screen,(200,100))
    buttontest2.Buttongenerate("TEST",(200,200))
    pygame.display.flip()
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
            exit(0)

When I run this code , but It seems that pygame.draw.polygon is not running

enter image description here

1

There are 1 best solutions below

0
sloth On BEST ANSWER

pygame.draw.polygon works just fine.

Your problem is that you calculate TEXTPOS wrong (I just guess the text should be rendered inside the rectangle). You should use

TEXTPOS = [POS[0]+(self.width-textsize[0])/2, POS[1]+(self.height-textsize[1])/2]

which actually uses POS to calculate the final position of the text.

Otherwise, the text is rendered above the rectangle. Here's the full, running code:

import pygame
pygame.init()
screen = pygame.display.set_mode((600,600))
class button:
    def __init__(self,screen,size): # size -->(width,height)
        self.width = size[0]
        self.height = size[1]
        self.screen = screen
    def Buttongenerate(self,TEXT,POS):
        font = pygame.font.Font(None,self.height//3)
        text = font.render(TEXT,True,(250,250,250))
        textsize = font.size(TEXT)
        TEXTPOS = [POS[0]+(self.width-textsize[0])/2, POS[1]+(self.height-textsize[1])/2]
        self.screen.blit(text,TEXTPOS)
        pygame.draw.polygon(self.screen, (250,250,250), [[POS[0],POS[1]],[POS[0]+self.width,POS[1]],[POS[0]+self.width,POS[1]+self.height],[POS[0],POS[1]+self.height]], 2)

while True:
    screen.fill((0,0,0))
    buttontest2 = button(screen,(200,100))
    buttontest2.Buttongenerate("TEST",(200,200))
    pygame.display.flip()
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()

Note that it would be better to create a new surface for the text and rectangle once instead of loading the font, rendering the text, and drawing on the screen surface every iteration of the main loop.