1+ # Imports
2+ import sys
3+ import pygame
4+
5+ # Configuration
6+ pygame .init ()
7+ fps = 60
8+ fpsClock = pygame .time .Clock ()
9+ width , height = 640 , 480
10+ screen = pygame .display .set_mode ((width , height ))
11+
12+ font = pygame .font .SysFont ('Arial' , 40 )
13+
14+ objects = []
15+
16+ class Button ():
17+ def __init__ (self , x , y , width , height , buttonText = 'Button' , onclickFunction = None , onePress = False ):
18+ self .x = x
19+ self .y = y
20+ self .width = width
21+ self .height = height
22+ self .onclickFunction = onclickFunction
23+ self .onePress = onePress
24+
25+ self .fillColors = {
26+ 'normal' : '#ffffff' ,
27+ 'hover' : '#666666' ,
28+ 'pressed' : '#333333' ,
29+ }
30+
31+ self .buttonSurface = pygame .Surface ((self .width , self .height ))
32+ self .buttonRect = pygame .Rect (self .x , self .y , self .width , self .height )
33+
34+ self .buttonSurf = font .render (buttonText , True , (20 , 20 , 20 ))
35+
36+ self .alreadyPressed = False
37+
38+ objects .append (self )
39+
40+ def process (self ):
41+
42+ mousePos = pygame .mouse .get_pos ()
43+
44+ self .buttonSurface .fill (self .fillColors ['normal' ])
45+ if self .buttonRect .collidepoint (mousePos ):
46+ self .buttonSurface .fill (self .fillColors ['hover' ])
47+
48+ if pygame .mouse .get_pressed (num_buttons = 3 )[0 ]:
49+ self .buttonSurface .fill (self .fillColors ['pressed' ])
50+
51+ if self .onePress :
52+ self .onclickFunction ()
53+
54+ elif not self .alreadyPressed :
55+ self .onclickFunction ()
56+ self .alreadyPressed = True
57+
58+ else :
59+ self .alreadyPressed = False
60+
61+ self .buttonSurface .blit (self .buttonSurf , [
62+ self .buttonRect .width / 2 - self .buttonSurf .get_rect ().width / 2 ,
63+ self .buttonRect .height / 2 - self .buttonSurf .get_rect ().height / 2
64+ ])
65+ screen .blit (self .buttonSurface , self .buttonRect )
66+
67+ def myFunction ():
68+ print ('Button Pressed' )
69+
70+ customButton = Button (30 , 30 , 400 , 100 , 'Button One (onePress)' , myFunction )
71+ customButton = Button (30 , 140 , 400 , 100 , 'Button Two (multiPress)' , myFunction , True )
72+
73+ # Game loop.
74+ while True :
75+ screen .fill ((20 , 20 , 20 ))
76+ for event in pygame .event .get ():
77+ if event .type == pygame .QUIT :
78+ pygame .quit ()
79+ sys .exit ()
80+
81+ for object in objects :
82+ object .process ()
83+
84+ pygame .display .flip ()
85+ fpsClock .tick (fps )
0 commit comments