# Do the imports
import pygame
from random import choice, randint
# Initiate pygame
pygame.init()
# Initiate pygame fonts
pygame.font.init()
# Pygame clock
clock = pygame.time.Clock()
# Frames per second
fps = 60
# Setup the screen display
screen = pygame.display.set_mode((800,600))
# Create the random font from list
def rndfont():
return choice(pygame.font.get_fonts())
def rndcolor():
return randint(0, 255), randint(0, 255), randint(0, 255)
# Create the label class
class MyLabel:
'''
MyLabel class needs x pos, y pos, width of label, height of label, text for label, and color of label
'''
def __init__(self, x, y, width, height, text, textcolor=(0,0,0), default_font=False):
self.x = x
self.y = y
self.width = width
self.height = height
self.text = text
# Check if default is set to True or False
if default_font:
self.font = None
size = 40
else:
self.font = rndfont()
size = 30
self.sysfont = pygame.font.SysFont(self.font, size)
# Conditional statement to bot show if default_font is set to True
show = '' if default_font else f'({self.font})'
# Create label surface and label rect. Add text to label
self.label_surface = pygame.Surface((self.width, self.height))
self.label_rect = pygame.Rect(self.x, self.y, self.width, self.height)
self.label_surf = self.sysfont.render(f'{self.text} {show}', True, textcolor)
# center text on label
self.text_rect = self.label_surf.get_rect(center=(self.width/2, self.height/2))
# draw blits text to label and label to screen
def draw(self):
self.label_surface.blit(self.label_surf, self.text_rect)
screen.blit(self.label_surface, (self.x, self.y))
# Create labels
label = MyLabel(30,10,580,80, 'Not all fonts will show correct', textcolor='tomato', default_font=True)
label1 = MyLabel(30, 110, 580, 80, 'Some Label Text', rndcolor())
label2 = MyLabel(30, 210, 580, 80, 'More text here', rndcolor())
running = True
while running:
screen.fill('lightgray')
event = pygame.event.poll()
if event.type == pygame.QUIT:
running = False
# Draw labels to screen
label.draw()
label1.draw()
label2.draw()
pygame.display.update()
clock.tick(fps)