refactor(game): broke Main into smaller methods

This commit is contained in:
Kristofers Solo 2024-01-04 06:51:03 +02:00
parent 7f9b1fb266
commit 918e832862

View File

@ -12,36 +12,16 @@ from .tetromino import Tetromino
class Main: class Main:
def __init__(self) -> None: def __init__(self) -> None:
pygame.init() self._initialize_pygeme()
pygame.display.set_caption(CONFIG.window.title) self._initialize_game_components()
self.display_surface = pygame.display.set_mode(CONFIG.window.size) self._start_background_music()
self.display_surface.fill(CONFIG.colors.bg)
self.clock = pygame.time.Clock()
self.next_figures = self._generate_next_figures()
self.game = Game(self._get_next_figure, self._update_score)
self.score = Score()
self.preview = Preview()
self.music = pygame.mixer.Sound(CONFIG.music.background)
self.music.set_volume(CONFIG.music.volume)
self.music.play(-1)
def draw(self) -> None: def draw(self) -> None:
pygame.display.update() pygame.display.update()
def run(self) -> None: def run(self) -> None:
while True: while True:
self.draw() self._run_game_loop()
self.handle_events()
self.game.run()
self.score.run()
self.preview.run(self.next_figures)
pygame.display.update()
self.clock.tick(CONFIG.fps)
def _update_score(self, lines: int, score: int, level: int) -> None: def _update_score(self, lines: int, score: int, level: int) -> None:
self.score.update(lines, score, level) self.score.update(lines, score, level)
@ -65,3 +45,33 @@ class Main:
next_shape = self.next_figures.pop(0) next_shape = self.next_figures.pop(0)
self.next_figures.append(Figure.random()) self.next_figures.append(Figure.random())
return next_shape return next_shape
def _initialize_pygeme(self) -> None:
pygame.init()
pygame.display.set_caption(CONFIG.window.title)
self.display_surface = pygame.display.set_mode(CONFIG.window.size)
self.display_surface.fill(CONFIG.colors.bg)
self.clock = pygame.time.Clock()
def _initialize_game_components(self) -> None:
self.next_figures = self._generate_next_figures()
self.game = Game(self._get_next_figure, self._update_score)
self.score = Score()
self.preview = Preview()
def _start_background_music(self) -> None:
self.music = pygame.mixer.Sound(CONFIG.music.background)
self.music.set_volume(CONFIG.music.volume)
self.music.play(-1)
def _run_game_loop(self) -> None:
self.draw()
self.handle_events()
self.game.run()
self.score.run()
self.preview.run(self.next_figures)
pygame.display.update()
self.clock.tick(CONFIG.fps)