Skip to content

Commit

Permalink
Refactors
Browse files Browse the repository at this point in the history
  • Loading branch information
ppizarror committed Oct 21, 2024
1 parent 6b4af7d commit f08e194
Show file tree
Hide file tree
Showing 16 changed files with 289 additions and 155 deletions.
3 changes: 2 additions & 1 deletion pygame_menu/_decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,8 @@ class Decorator(Base):
:param decorator_id: ID of the decorator
:param verbose: Enable/disable verbose mode (warnings/errors)
"""
_coord_cache: Dict[str, Tuple[int, int, Union[Tuple[Tuple2NumberType, ...], Tuple2NumberType]]] # centerx, centery, coords
_coord_cache: Dict[
str, Tuple[int, int, Union[Tuple[Tuple2NumberType, ...], Tuple2NumberType]]] # centerx, centery, coords
_cache_last_status: Dict[str, Tuple[int, int, int, int, int, int]]
_cache_needs_update: Dict[str, bool]
_cache_surface: Dict[str, Optional['pygame.Surface']]
Expand Down
6 changes: 4 additions & 2 deletions pygame_menu/_scrollarea.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,8 @@ def _make_background_surface(self) -> None:
return

# Make surface
self._bg_surface = make_surface(width=self._rect.width + self._extend_x, height=self._rect.height + self._extend_y)
self._bg_surface = make_surface(width=self._rect.width + self._extend_x,
height=self._rect.height + self._extend_y)
rect = self._bg_surface.get_rect()
if self._area_color is not None:
if isinstance(self._area_color, pygame_menu.BaseImage):
Expand Down Expand Up @@ -940,7 +941,8 @@ def scroll_to_rect(
:return: Scrollarea scrolled to rect. If ``False`` the rect was already inside the visible area
"""
# Check if visible
if self.to_real_position(rect, visible=True).height == 0 and self._parent_scrollarea is not None and scroll_parent:
if (self.to_real_position(rect, visible=True).height == 0 and
self._parent_scrollarea is not None and scroll_parent):
self._parent_scrollarea.scroll_to_rect(self._parent_scrollarea.get_rect(), margin, scroll_parent)
self._parent_scrollarea.scroll_to_rect(self.get_rect(), margin, scroll_parent)

Expand Down
3 changes: 2 additions & 1 deletion pygame_menu/baseimage.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@

# Custom types
ColorChannelType = Literal['r', 'g', 'b']
ChannelType = Union[ColorChannelType, Tuple[ColorChannelType, ColorChannelType], Tuple[ColorChannelType, ColorChannelType, ColorChannelType], List[ColorChannelType]]
ChannelType = Union[ColorChannelType, Tuple[ColorChannelType, ColorChannelType], Tuple[
ColorChannelType, ColorChannelType, ColorChannelType], List[ColorChannelType]]


class BaseImage(Base):
Expand Down
6 changes: 4 additions & 2 deletions pygame_menu/examples/game_selector.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,10 @@ def play_function(difficulty: List, font: 'pygame.font.Font', test: bool = False

# Continue playing
surface.fill(bg_color)
surface.blit(f, (int((WINDOW_SIZE[0] - f.get_width()) / 2), int(WINDOW_SIZE[1] / 2 - f.get_height())))
surface.blit(f_esc, (int((WINDOW_SIZE[0] - f_esc.get_width()) / 2), int(WINDOW_SIZE[1] / 2 + f_esc.get_height())))
surface.blit(f, (int((WINDOW_SIZE[0] - f.get_width()) / 2),
int(WINDOW_SIZE[1] / 2 - f.get_height())))
surface.blit(f_esc, (int((WINDOW_SIZE[0] - f_esc.get_width()) / 2),
int(WINDOW_SIZE[1] / 2 + f_esc.get_height())))
pygame.display.flip()

# If test returns
Expand Down
30 changes: 20 additions & 10 deletions pygame_menu/examples/other/calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,32 +68,42 @@ def __init__(self) -> None:
# Add horizontal frames
f1 = self.menu.add.frame_h(299, 54, margin=(10, 0))
b1 = f1.pack(self.menu.add.button('1', lambda: self._press(1), cursor=cursor))
b2 = f1.pack(self.menu.add.button('2', lambda: self._press(2), cursor=cursor), align=pygame_menu.locals.ALIGN_CENTER)
b3 = f1.pack(self.menu.add.button('3', lambda: self._press(3), cursor=cursor), align=pygame_menu.locals.ALIGN_RIGHT)
b2 = f1.pack(self.menu.add.button('2', lambda: self._press(2), cursor=cursor),
align=pygame_menu.locals.ALIGN_CENTER)
b3 = f1.pack(self.menu.add.button('3', lambda: self._press(3), cursor=cursor),
align=pygame_menu.locals.ALIGN_RIGHT)
self.menu.add.vertical_margin(10)

f2 = self.menu.add.frame_h(299, 54, margin=(10, 0))
b4 = f2.pack(self.menu.add.button('4', lambda: self._press(4), cursor=cursor))
b5 = f2.pack(self.menu.add.button('5', lambda: self._press(5), cursor=cursor), align=pygame_menu.locals.ALIGN_CENTER)
b6 = f2.pack(self.menu.add.button('6', lambda: self._press(6), cursor=cursor), align=pygame_menu.locals.ALIGN_RIGHT)
b5 = f2.pack(self.menu.add.button('5', lambda: self._press(5), cursor=cursor),
align=pygame_menu.locals.ALIGN_CENTER)
b6 = f2.pack(self.menu.add.button('6', lambda: self._press(6), cursor=cursor),
align=pygame_menu.locals.ALIGN_RIGHT)
self.menu.add.vertical_margin(10)

f3 = self.menu.add.frame_h(299, 54, margin=(10, 0))
b7 = f3.pack(self.menu.add.button('7', lambda: self._press(7), cursor=cursor))
b8 = f3.pack(self.menu.add.button('8', lambda: self._press(8), cursor=cursor), align=pygame_menu.locals.ALIGN_CENTER)
b9 = f3.pack(self.menu.add.button('9', lambda: self._press(9), cursor=cursor), align=pygame_menu.locals.ALIGN_RIGHT)
b8 = f3.pack(self.menu.add.button('8', lambda: self._press(8), cursor=cursor),
align=pygame_menu.locals.ALIGN_CENTER)
b9 = f3.pack(self.menu.add.button('9', lambda: self._press(9), cursor=cursor),
align=pygame_menu.locals.ALIGN_RIGHT)
self.menu.add.vertical_margin(10)

f4 = self.menu.add.frame_h(299, 54, margin=(10, 0))
b0 = f4.pack(self.menu.add.button('0', lambda: self._press(0), cursor=cursor))
b_plus = f4.pack(self.menu.add.button('+', lambda: self._press('+'), cursor=cursor), align=pygame_menu.locals.ALIGN_CENTER)
b_minus = f4.pack(self.menu.add.button('-', lambda: self._press('-'), cursor=cursor), align=pygame_menu.locals.ALIGN_RIGHT)
b_plus = f4.pack(self.menu.add.button('+', lambda: self._press('+'), cursor=cursor),
align=pygame_menu.locals.ALIGN_CENTER)
b_minus = f4.pack(self.menu.add.button('-', lambda: self._press('-'), cursor=cursor),
align=pygame_menu.locals.ALIGN_RIGHT)
self.menu.add.vertical_margin(10)

f5 = self.menu.add.frame_h(299, 54, margin=(10, 0))
b_times = f5.pack(self.menu.add.button('x', lambda: self._press('x'), cursor=cursor))
b_div = f5.pack(self.menu.add.button('/', lambda: self._press('/'), cursor=cursor), align=pygame_menu.locals.ALIGN_CENTER)
beq = f5.pack(self.menu.add.button('=', lambda: self._press('='), cursor=cursor), align=pygame_menu.locals.ALIGN_RIGHT)
b_div = f5.pack(self.menu.add.button('/', lambda: self._press('/'), cursor=cursor),
align=pygame_menu.locals.ALIGN_CENTER)
beq = f5.pack(self.menu.add.button('=', lambda: self._press('='), cursor=cursor),
align=pygame_menu.locals.ALIGN_RIGHT)

# Add decorator for each object
for widget in (b1, b2, b3, b4, b5, b6, b7, b8, b9, b0, beq, b_plus, b_minus, b_times, b_div):
Expand Down
64 changes: 37 additions & 27 deletions pygame_menu/menu.py
Original file line number Diff line number Diff line change
Expand Up @@ -1101,7 +1101,7 @@ def select_widget(self, widget: Optional[Union['Widget', str]]) -> 'Menu':
assert isinstance(widget, Widget)
if not widget.is_selectable:
raise ValueError(f'{widget.get_class_id()} is not selectable')
if not widget.is_visible(): # Considers frame
elif not widget.is_visible(): # Considers frame
raise ValueError(f'{widget.get_class_id()} is not visible')
try:
index = self._widgets.index(widget) # If not exists this raises ValueError
Expand Down Expand Up @@ -1764,7 +1764,7 @@ def _get_depth(self) -> int:
:return: Menu depth
"""
prev = self._top._prev
depth = 0
depth: int = 0
if prev is not None:
while True:
if prev is not None:
Expand Down Expand Up @@ -1907,7 +1907,7 @@ def get_width(self, inner: bool = False, widget: bool = False, border: bool = Fa
"""
if widget:
return int(self._widget_max_position[0] - self._widget_min_position[0])
if not inner:
elif not inner:
bw = 0 if not border else 2 * self._scrollarea.get_border_size()[0]
return int(self._width) + bw
return int(self._width - self._get_scrollbar_thickness()[1])
Expand All @@ -1929,7 +1929,7 @@ def get_height(self, inner: bool = False, widget: bool = False, border: bool = F
"""
if widget:
return int(self._widget_max_position[1] - self._widget_min_position[1])
if not inner:
elif not inner:
bh = 0 if not border else 2 * self._scrollarea.get_border_size()[1]
return int(self._height) + bh
return int(self._height - self._menubar.get_height() - self._get_scrollbar_thickness()[0])
Expand Down Expand Up @@ -2055,15 +2055,16 @@ def draw(self, surface: Optional['pygame.Surface'] = None, clear_surface: bool =
if not self.is_enabled():
self._current._runtime_errors.throw(self._current._runtime_errors.draw, 'menu is not enabled')
return self._current
if self._current._disable_draw:
elif self._current._disable_draw:
return self._current

# Render menu; if True, the surface widget has changed, thus cache should
# change if enabled
render = self._current._render()

# Updates title
if self._current._theme.title_updates_pygame_display and pygame.display.get_caption()[0] != self._current.get_title():
if (self._current._theme.title_updates_pygame_display and
pygame.display.get_caption()[0] != self._current.get_title()):
pygame.display.set_caption(self._current.get_title())

# Clear surface
Expand Down Expand Up @@ -2107,7 +2108,7 @@ def draw(self, surface: Optional['pygame.Surface'] = None, clear_surface: bool =
# Widgets within frames are not drawn as it's frame draw these widgets
if widget.get_frame() is not None:
continue
if widget.is_selected():
elif widget.is_selected():
selected_widget_draw = widget, self._current._widgets_surface
widget.draw(self._current._widgets_surface)

Expand Down Expand Up @@ -2150,12 +2151,14 @@ def _draw_focus_widget(
assert isinstance(widget, (Widget, type(None)))

force = force or (widget is not None and widget.active and widget.force_menu_draw_focus)
if not force and (widget is None
or not widget.active
or not widget.is_selectable
or not widget.is_selected()
or not (self._mouse_motion_selection or self._touchscreen_motion_selection)
or not widget.is_visible()):
if not force and (
widget is None
or not widget.active
or not widget.is_selectable
or not widget.is_selected()
or not (self._mouse_motion_selection or self._touchscreen_motion_selection)
or not widget.is_visible()
):
return
window_width, window_height = self._window_size

Expand Down Expand Up @@ -2375,16 +2378,17 @@ def _handle_joy_event(self, apply_sound: bool = False) -> bool:
Handle joy events.
:param apply_sound: Apply sound on widget selection
:return: ``True`` if widget changed
:return: ``True`` if the widget changed
"""
if self._joy_event & JOY_EVENT_UP:
return self._select(self._index - 1, -1, SELECT_KEY, apply_sound)
if self._joy_event & JOY_EVENT_DOWN:
elif self._joy_event & JOY_EVENT_DOWN:
return self._select(self._index + 1, 1, SELECT_KEY, apply_sound)
if self._joy_event & JOY_EVENT_LEFT:
elif self._joy_event & JOY_EVENT_LEFT:
return self._move_selected_left_right(-1, apply_sound)
if self._joy_event & JOY_EVENT_RIGHT:
elif self._joy_event & JOY_EVENT_RIGHT:
return self._move_selected_left_right(1, apply_sound)
return False

def _up(self, apply_sound: bool = False) -> bool:
"""
Expand Down Expand Up @@ -2703,7 +2707,8 @@ def update(self, events: EventVectorType) -> bool:
pygame.time.set_timer(self._current._joy_event_repeat, 0)

# Select widget by clicking
elif event.type == pygame.MOUSEBUTTONDOWN and self._current._mouse and event.button in (1, 2, 3): # Don't consider the mouse wheel (button 4 & 5)
elif (event.type == pygame.MOUSEBUTTONDOWN and self._current._mouse and
event.button in (1, 2, 3)): # Don't consider the mouse wheel (button 4 & 5)

# If the mouse motion selection is disabled then select a widget by clicking
if not self._current._mouse_motion_selection:
Expand All @@ -2712,7 +2717,8 @@ def update(self, events: EventVectorType) -> bool:
widget = self._current._widgets[index]
if isinstance(widget, Frame): # Frame does not accept click
continue
if widget.is_selectable and widget.is_visible() and widget.get_scrollarea().collide(widget, event):
if (widget.is_selectable and widget.is_visible() and
widget.get_scrollarea().collide(widget, event)):
sel = self._current._select(index, 1, SELECT_MOUSE_BUTTON_DOWN, True)
break

Expand Down Expand Up @@ -2796,15 +2802,16 @@ def update(self, events: EventVectorType) -> bool:
continue

# Check if "rel" exists within the event
if not hasattr(event, 'rel'):
elif not hasattr(event, 'rel'):
continue

# Select if mouse motion
sel = False # Widget has been selected
for index in range(len(self._current._widgets)):
widget = self._current._widgets[index]
if widget.is_visible() and widget.get_scrollarea().collide(widget, event):
if self._current._mouse_motion_selection and widget.is_selectable and not isinstance(widget, Frame):
if (self._current._mouse_motion_selection and widget.is_selectable
and not isinstance(widget, Frame)):
sel = self._current._select(index, 1, SELECT_MOUSE_MOTION, True)
# noinspection PyProtectedMember
widget._check_mouseover(event)
Expand All @@ -2818,7 +2825,8 @@ def update(self, events: EventVectorType) -> bool:
break

# Mouse events in selected widget; don't consider the mouse wheel (button 4 & 5)
elif event.type == pygame.MOUSEBUTTONUP and self._current._mouse and selected_widget is not None and event.button in (1, 2, 3):
elif (event.type == pygame.MOUSEBUTTONUP and self._current._mouse and
selected_widget is not None and event.button in (1, 2, 3)):
self._current._sound.play_click_mouse()
if selected_widget_scrollarea.collide(selected_widget, event):
updated = selected_widget.update_menu([event])
Expand All @@ -2838,7 +2846,8 @@ def update(self, events: EventVectorType) -> bool:
widget = self._current._widgets[index]
if isinstance(widget, Frame): # Frame does not accept touch
continue
if widget.is_selectable and widget.is_visible() and widget.get_scrollarea().collide(widget, event):
elif (widget.is_selectable and widget.is_visible() and
widget.get_scrollarea().collide(widget, event)):
sel = self._current._select(index, 1, SELECT_TOUCH, True)
if not isinstance(widget, Frame):
break
Expand Down Expand Up @@ -2887,7 +2896,8 @@ def update(self, events: EventVectorType) -> bool:
widget = self._current._widgets[index]
if isinstance(widget, Frame): # Frame does not accept touch
continue
if widget.is_selectable and widget.is_visible() and widget.get_scrollarea().collide(widget, event):
elif (widget.is_selectable and widget.is_visible() and
widget.get_scrollarea().collide(widget, event)):
sel = self._current._select(index, 1, SELECT_TOUCH, True)
if not isinstance(widget, Frame):
break
Expand Down Expand Up @@ -3180,7 +3190,7 @@ def full_reset(self) -> 'Menu':
:return: Self reference
"""
depth = self._get_depth()
depth: int = self._get_depth()
if depth > 0:
self.reset(depth)
return self
Expand Down Expand Up @@ -3746,7 +3756,7 @@ def get_selected_widget(self) -> Optional['Widget']:
if not isinstance(self._index, int):
self._index = 0
return None
if self._index < 0:
elif self._index < 0:
return None
try:
return self._widgets[self._index % len(self._widgets)]
Expand Down Expand Up @@ -3949,7 +3959,7 @@ def move_widget_index(
reverse=not to_last_position):
if w.get_menu() is None:
continue
if not to_last_position:
elif not to_last_position:
self.move_widget_index(
w, self._widgets.index(widget) + 1, render=False, depth=depth + 1
)
Expand Down
Loading

0 comments on commit f08e194

Please sign in to comment.