-
Notifications
You must be signed in to change notification settings - Fork 0
/
button.py
63 lines (42 loc) · 1.78 KB
/
button.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/usr/bin/env python
# encoding: utf-8
from __future__ import unicode_literals
from __future__ import print_function
import pygame
from pygame.locals import MOUSEBUTTONUP, MOUSEBUTTONDOWN
from events import EventSystem
class Button(EventSystem):
active_image = None
inactive_image = None
def __init__(self, display, label, **kwargs):
if Button.active_image is None:
Button.label_font = pygame.font.Font('Signika-Light.ttf', 24)
Button.active_image = pygame.image.load('img/button-active.png')
Button.inactive_image = pygame.image.load('img/button-inactive.png')
self.display = display
self.is_mousedown = False
self.label = label
self.label_surface = Button.label_font.render(self.label, True,
(240, 240, 240))
self.rect = pygame.Rect((0, 0), Button.active_image.get_size())
self.label_rect = self.label_surface.get_rect()
self.update_rect(**kwargs)
def update_rect(self, **kwargs):
for name, value in kwargs.items():
setattr(self.rect, name, value)
self.label_rect.center = self.rect.center
def draw(self):
if self.is_mousedown:
self.display.blit(Button.active_image, self.rect)
else:
self.display.blit(Button.inactive_image, self.rect)
self.display.blit(self.label_surface, self.label_rect)
def handle(self, event):
if event.type == MOUSEBUTTONDOWN and self.contains(event.pos):
self.is_mousedown = True
elif event.type == MOUSEBUTTONUP:
if self.is_mousedown and self.contains(event.pos):
self.emit('click')
self.is_mousedown = False
def contains(self, point):
return self.rect.collidepoint(point)