Add button colors parameter, make code clearer in UiButton

This commit is contained in:
Michał Czekański 2020-04-04 15:48:51 +02:00
parent 74a08be69f
commit 6fc3a3155d

View File

@ -1,3 +1,5 @@
from enum import Enum
import pygame import pygame
from src.ui.UiElement import UiElement from src.ui.UiElement import UiElement
@ -5,37 +7,46 @@ from src.ui.UiElement import UiElement
class UiButton(UiElement): class UiButton(UiElement):
def __init__(self, rect: pygame.Rect, text="Click", color=(125, 125, 125)): def __init__(self, rect: pygame.Rect, notClickedBtnColor=(125, 125, 125), clickedBtnColor=(255, 255, 255),
text="Click", textColor=(0, 0, 0), font=None):
super().__init__(rect) super().__init__(rect)
if font is None:
self.font = pygame.font.Font(None, 25)
self.textColor = textColor
self.clickedBtnColor = clickedBtnColor
self.notClickedBtnColor = notClickedBtnColor
self.text = text self.text = text
self.color = color self.__initBtnImages__()
self.DEFAULTIMAGE = 0
self.CLICKINGIMAGE = 1
self._images = [
pygame.Surface((rect.width, rect.height)),
pygame.Surface((rect.width, rect.height)),
]
# fill images with color - red, gree, blue
self._images[0].fill((255, 0, 0))
self._images[1].fill((0, 255, 0))
self.beingClicked = False self.beingClicked = False
self.image = self._images[0] self.image = self._images[0]
def eventHandler(self, event): def eventHandler(self, event):
# change selected color if rectangle clicked
# change selected color if rectange clicked if event.type == pygame.MOUSEBUTTONDOWN:
if event.type == pygame.MOUSEBUTTONDOWN: # is some button clicked if event.button == 1:
if event.button == 1: # is left button clicked
if self.rect.collidepoint(event.pos): # is mouse over button if self.rect.collidepoint(event.pos): # is mouse over button
self.image = self._images[ButtonImages.CLICKING_IMAGE.value]
self.image = self._images[self.CLICKINGIMAGE]
self.beingClicked = True self.beingClicked = True
elif event.type == pygame.MOUSEBUTTONUP and self.beingClicked: elif event.type == pygame.MOUSEBUTTONUP and self.beingClicked:
if event.button == 1: if event.button == 1:
self.beingClicked = False self.beingClicked = False
self.image = self._images[self.DEFAULTIMAGE] self.image = self._images[ButtonImages.DEFAULT_IMAGE.value]
def __initBtnImages__(self):
self._images = [
pygame.Surface((self.rect.width, self.rect.height)),
pygame.Surface((self.rect.width, self.rect.height)),
]
self._images[ButtonImages.DEFAULT_IMAGE.value].fill(self.notClickedBtnColor)
self._images[ButtonImages.CLICKING_IMAGE.value].fill(self.clickedBtnColor)
self.textSurface = self.font.render(self.text, False, (0, 0, 0))
self.textSurfaceDest = (self.rect.centerx - (self.textSurface.get_width() / 2),
self.rect.centery - (self.textSurface.get_height() / 2))
self._images[0].blit(self.textSurface, self.textSurfaceDest)
self._images[1].blit(self.textSurface, self.textSurfaceDest)
class ButtonImages(Enum):
DEFAULT_IMAGE = 0
CLICKING_IMAGE = 1