Thursday, April 5, 2018

Ex10. Label sprites

A sprite has to have an image (self.image) and rect (self.rect). If the label was not static we will have to define an update method where the two properties might change.


We have a sprite group, labels, containing both labels.


Whenever we want to draw a new frame, we will just have to call labels.draw(screen)



# Ex10.py 
# Label Class as sprites

import pygame as pg

FILL_COLOR = pg.Color("cyan")

class Label(pg.sprite.Sprite):
    def __init__(self,text,x,y,back_color,text_color):
        pg.sprite.Sprite.__init__(self)
        self.text = text
        self.font = pg.font.SysFont("arial",24)
        self.back_color = pg.Color(back_color)
        self.text_color = pg.Color(text_color)
        self.pad = 2
        self.image = self.get_surf()
        self.rect = self.image.get_rect()
        self.rect.topleft = (x,y)
 
    def get_surf(self):
        pad_text = ' ' * self.pad
        text_string = pad_text + self.text + pad_text
        text_image = self.font.render(text_string, True,
                                      self.text_color)
        rect = text_image.get_rect()
        rect.height = 2 * round(rect.height/2)
        rect.width = rect.width + 2 * rect.height
        surf = pg.Surface((rect.width+2*rect.height, rect.height))
        surf.fill(FILL_COLOR)
        rect_text = rect.move(rect.height,0)
        pg.draw.rect(surf,self.back_color,rect_text)
        surf.blit(text_image,rect_text)
        left_circ_cen = (rect.height//2,rect.centery)
        pg.draw.circle(surf,self.back_color,
                       left_circ_cen,rect.height//2)
        right_circ_cen = (rect.width+rect.height+rect.height//2,
                          rect.centery)
        pg.draw.circle(surf,self.back_color,right_circ_cen,
                       rect.height//2)
        left_rect = pg.Rect(rect.height//2, 0, rect.height//2,
                            rect.height)
        pg.draw.rect(surf,self.back_color,left_rect)
        right_rect = pg.Rect(rect.width+rect.height, 0,
                             rect.height//2, rect.height)
        pg.draw.rect(surf,self.back_color,right_rect)
        return surf

width, height = 640, 480

pg.init()

screen = pg.display.set_mode((width, height))
pg.display.set_caption('Ex10. Label Sprite Class')
clock = pg.time.Clock()
FPS = 30

w = width // 4
labels = pg.sprite.Group()
label1 = Label("I am label 1", w,  height//2, "red", "blue")
label2 = Label("And I am label 2", w, height//2+100, "blue", "red")
labels.add(label1)
labels.add(label2)

screen.fill(FILL_COLOR)

labels.draw(screen)

pg.display.update()

done = False
while not done:
    clock.tick(FPS)
    for event in pg.event.get():
        if event.type == pg.QUIT:
         done = True

pg.quit()

The output is same as in the previous example.


No comments:

Post a Comment