mirror of https://git.sr.ht/~michalr/menu
Redraw only when something could have changed - save CPU usage
This commit is contained in:
parent
abbaec38da
commit
1fc3a01413
|
@ -8,7 +8,7 @@ from pygame.event import Event
|
|||
|
||||
class IBoard:
|
||||
@abstractmethod
|
||||
def draw(self, screen: Surface):
|
||||
def draw(self, screen: Surface, force_redraw: bool):
|
||||
raise NotImplementedError()
|
||||
|
||||
@abstractmethod
|
||||
|
|
25
menu.py
25
menu.py
|
@ -86,13 +86,16 @@ class MessageBoard(IBoard):
|
|||
(screen_rect.top + (screen_rect.height - text_rect.height)/2),
|
||||
text_rect.width, text_rect.height)
|
||||
self.bg_color = bg_color
|
||||
self.was_drawn_already = False
|
||||
|
||||
def handle_event(self, _):
|
||||
pass
|
||||
|
||||
def draw(self, screen: pygame.Surface):
|
||||
screen.fill(self.bg_color)
|
||||
self.font.render_to(screen, self.text_pos, self.text, fgcolor="black")
|
||||
def draw(self, screen: pygame.Surface, force_redraw: bool):
|
||||
if not self.was_drawn_already or force_redraw:
|
||||
screen.fill(self.bg_color)
|
||||
self.font.render_to(screen, self.text_pos, self.text, fgcolor="black")
|
||||
self.was_drawn_already = True
|
||||
|
||||
|
||||
class MenuBoard(IBoard):
|
||||
|
@ -126,10 +129,11 @@ class MenuBoard(IBoard):
|
|||
for b in self.buttons:
|
||||
b.handle_event(event)
|
||||
|
||||
def draw(self, screen: pygame.Surface):
|
||||
screen.fill(self.bg_color)
|
||||
for b in self.buttons:
|
||||
b.draw(screen)
|
||||
def draw(self, screen: pygame.Surface, force_redraw: bool):
|
||||
if force_redraw:
|
||||
screen.fill(self.bg_color)
|
||||
for b in self.buttons:
|
||||
b.draw(screen)
|
||||
|
||||
|
||||
class App:
|
||||
|
@ -208,6 +212,7 @@ class App:
|
|||
|
||||
def loop(self):
|
||||
self.running = True
|
||||
needs_redrawing = True
|
||||
while self.running:
|
||||
try:
|
||||
self.task_q.get_nowait()()
|
||||
|
@ -219,12 +224,14 @@ class App:
|
|||
if self.screensaver_ticks != 0:
|
||||
self.board.handle_event(event)
|
||||
self.screensaver_ticks = self.TICKS_UNTIL_SCREENSAVER
|
||||
needs_redrawing = True
|
||||
|
||||
if self.screensaver_ticks == 0:
|
||||
self.screensaver.draw(self.screen)
|
||||
self.screensaver.draw(self.screen, False)
|
||||
else:
|
||||
self.board.draw(self.screen)
|
||||
self.board.draw(self.screen, needs_redrawing)
|
||||
self.screensaver_ticks -= 1
|
||||
needs_redrawing = False
|
||||
|
||||
pygame.display.flip()
|
||||
|
||||
|
|
|
@ -20,7 +20,7 @@ class ClockScreensaver(Screensaver):
|
|||
self.dy = 1
|
||||
self.text_xy: Tuple[int, int] = (0, 0)
|
||||
|
||||
def draw(self, screen: pygame.Surface):
|
||||
def draw(self, screen: pygame.Surface, _):
|
||||
text = strftime("%H:%M:%S")
|
||||
screen.fill("black")
|
||||
pygame.Rect(0, 0, screen.get_width(), screen.get_height())
|
||||
|
|
Loading…
Reference in New Issue