1
0
Fork 0

Redraw only when something could have changed - save CPU usage

This commit is contained in:
Michał Rudowicz 2024-09-10 16:37:34 +02:00
parent abbaec38da
commit 1fc3a01413
3 changed files with 18 additions and 11 deletions

View File

@ -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

15
menu.py
View File

@ -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):
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,7 +129,8 @@ class MenuBoard(IBoard):
for b in self.buttons:
b.handle_event(event)
def draw(self, screen: pygame.Surface):
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)
@ -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()

View File

@ -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())