The example is simple but you can update with new features.
I will make some buttons: Start game, Options and Exit game.
The pygame come with rect function to draw rectangles.
I start with one python class named my_button.
Like any graphic interface is needed to make visual elements and link with actions.
For each button, I draw one rectangle with text and functions to check mouse.
The functions of my_button are:
label - will add some text;
color - change color when the button is hovering:
draw - will deal with drawing the button, color, and mouse...;
check_hover - return boolean value based on mous eover my_button;
import pygame
pygame.init()
class my_button:
def __init__(self, text):
self.text = text
self.is_hover = False
self.default_color = (100,100,100)
self.hover_color = (0,255,25)
self.font_color = (0,0,255)
self.obj = None
def label(self):
font = pygame.font.Font(None, 22)
return font.render(self.text, 1, self.font_color)
def color(self):
if self.is_hover:
return self.hover_color
else:
return self.default_color
def draw(self, screen, mouse, rect_coord, label_coord):
self.obj = pygame.draw.rect(screen, self.color(), rect_coord)
screen.blit(self.label(), label_coord)
self.check_hover(mouse)
def check_hover(self, mouse):
if self.obj.collidepoint(mouse):
self.is_hover = True
else:
self.is_hover = False
if __name__ == '__main__':
start = my_button('Start game')
option = my_button('Option')
exit = my_button('Exit game')
screen = pygame.display.set_mode((400,350))
clock = pygame.time.Clock()
run = True
while run:
screen.fill((0,0,0))
mouse = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.MOUSEBUTTONDOWN:
if my_button_.obj.collidepoint(mouse):
print('my_button start clicked')
elif my_button_2.obj.collidepoint(mouse):
print('my_button option clicked')
elif my_button_3.obj.collidepoint(mouse):
print('my_button exit clicked')
start.draw(screen, mouse, (100,100,120,22), (125,103))
option.draw(screen, mouse, (100,130,120,22), (125,133))
exit.draw(screen, mouse, (100,160,120,22), (125,163))
pygame.display.update()
clock.tick(50)
... and this is the result of the pygame script.