-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dropdown.py
77 lines (61 loc) · 3.02 KB
/
Dropdown.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import pygame
from typing import Union
class Dropdown():
def __init__(self, color_menu: list[Union[tuple[int, int, int, int], pygame.Color]],
color_option: list[Union[tuple[int, int, int, int], pygame.Color]], x: int, y: int, w: int, h: int,
font: pygame.font.FontType, main: str, options: list[str]) -> None:
self.color_menu = color_menu
self.color_option = color_option
self.rect = pygame.Rect(x, y, w, h)
self.font = font
self.main = main
self.options = options
self.draw_menu = False
self.menu_active = False
self.active_option = -1
self.selection = self.main
def display(self, surface: pygame.Surface, scroll: int) -> None:
pygame.draw.rect(surface, self.color_menu[self.menu_active], self.rect, 0)
msg = self.font.render(self.main, True, (0, 0, 0))
surface.blit(msg, msg.get_rect(center = self.rect.center))
pygame.draw.polygon(surface, (0, 0, 0), [(self.rect.right - 5, self.rect.top + 5),
(self.rect.right - 21, self.rect.top + 5),
(self.rect.right - 13, self.rect.bottom - 5)])
if self.draw_menu:
for i, text in enumerate(self.options):
rect = self.rect.copy()
rect.y += ((i+1) * self.rect.height) + scroll
pygame.draw.rect(surface, self.color_option[1 if i == self.active_option else 0], rect, 0)
msg = self.font.render(text, True, (0, 0, 0))
surface.blit(msg, msg.get_rect(center = rect.center))
def update(self, event: pygame.event.Event, scroll: int) -> int:
mpos = pygame.mouse.get_pos()
self.menu_active = self.rect.collidepoint(mpos)
self.active_option = -1
for i in range(len(self.options)):
rect = self.rect.copy()
rect.y += (i+1) * self.rect.height + scroll
if rect.collidepoint(mpos):
self.active_option = i
break
if not self.menu_active and self.active_option == -1:
self.draw_menu = False
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if self.menu_active:
self.draw_menu = not self.draw_menu
elif self.draw_menu and self.active_option >= 0:
self.draw_menu = False
return self.active_option
if self.active_option != -1:
self.selection = self.options[self.active_option]
return -1
def get_option(self, n: int = -1) -> str:
if n > 0:
return self.options[n]
return self.selection
def find_option_index(self, option: str) -> int:
return self.options.index(option)
def set_option(self, index: int) -> None:
self.active_option = index
self.selection = self.options[index]
self.main = self.selection