refactor: use 1 log file

This commit is contained in:
Kristofers Solo 2024-01-07 19:03:53 +02:00
parent bdb785303d
commit 442feac0cb
20 changed files with 130 additions and 179 deletions

47
main.py
View File

@ -1,5 +1,6 @@
#!/usr/bin/env python #!/usr/bin/env python
import argparse import argparse
import sys
from loguru import logger from loguru import logger
from utils import BASE_PATH, CONFIG, GameMode from utils import BASE_PATH, CONFIG, GameMode
@ -27,28 +28,46 @@ parser.add_argument(
help="Run app with GUI [Default]", help="Run app with GUI [Default]",
) )
logger.add(
BASE_PATH / ".logs" / "teris.log", def setup_logger(level: str = "warning") -> None:
format="{time} | {level} | {message}", logger.remove()
level="WARNING", logger.add(
rotation="10 MB", sink=sys.stdout,
compression="zip", format="<green>{time}</green> | <level>{level}</level> | <level>{message}</level>",
) level=level.upper(),
colorize=True,
)
logger.add(
BASE_PATH / ".logs" / "teris.log",
format="{time} | {level} | {message}",
level="DEBUG" if level.upper() == "DEBUG" else "INFO",
rotation="10 MB",
compression="zip",
)
@logger.catch @logger.catch
def main(args: argparse.ArgumentParser) -> None: def run() -> None:
if args.debug:
CONFIG.log_level = "debug"
elif args.verbose:
CONFIG.log_level = "info"
import game import game
game.log.debug("Running the game") logger.debug("Launching the game")
game.Main(GameMode.PLAYER).run() game.Main(GameMode.PLAYER).run()
def main(args: argparse.ArgumentParser) -> None:
if args.debug:
level = "debug"
elif args.verbose:
level = "info"
else:
level = "warning"
setup_logger(level)
run()
if __name__ == "__main__": if __name__ == "__main__":
args = parser.parse_args() args = parser.parse_args()
main(args) main(args)

View File

@ -1,4 +1,3 @@
from .log import log
from .screens import Game, Main, Preview, Score, Tetris from .screens import Game, Main, Preview, Score, Tetris
__all__ = ["Main", "Game", "Preview", "Score", "Tetris", "log"] __all__ = ["Main", "Game", "Preview", "Score", "Tetris"]

View File

@ -1,14 +0,0 @@
from loguru import logger
from utils import BASE_PATH, CONFIG
log = logger.bind(name="game")
log.add(
BASE_PATH / ".logs" / "game.log",
format="{time} | {level} | {message}",
level=CONFIG.log_level.upper(),
rotation="10 MB",
compression="zip",
filter=lambda record: record["extra"].get("name") == "game",
)

View File

@ -1,9 +1,9 @@
from typing import Any from typing import Any
import pygame import pygame
from loguru import logger
from utils import CONFIG, Figure, GameMode from utils import CONFIG, Figure, GameMode
from game.log import log
from game.sprites import Tetromino from game.sprites import Tetromino
from .base import BaseScreen from .base import BaseScreen

View File

@ -2,19 +2,17 @@ import sys
from typing import Optional from typing import Optional
import pygame import pygame
from loguru import logger
from utils import CONFIG, GameMode, read_settings from utils import CONFIG, GameMode, read_settings
from game.log import log
from .base import BaseScreen, SceenElement, TextScreen from .base import BaseScreen, SceenElement, TextScreen
from .button import Button from .button import Button
from .game import Game from .game import Game
from .settings import Settings
class Main(BaseScreen, SceenElement, TextScreen): class Main(BaseScreen, SceenElement, TextScreen):
def __init__(self, mode: GameMode) -> None: def __init__(self, mode: GameMode) -> None:
log.info("Initializing the game") logger.info("Initializing the game")
self._initialize_pygame() self._initialize_pygame()
self._initialize_surface() self._initialize_surface()
self._initialize_rect() self._initialize_rect()
@ -24,7 +22,6 @@ class Main(BaseScreen, SceenElement, TextScreen):
self.settings = read_settings() self.settings = read_settings()
self.game: Optional[Game] = None self.game: Optional[Game] = None
self.game_mode = mode self.game_mode = mode
self.settings_screen: Optional[Settings] = None
def draw(self) -> None: def draw(self) -> None:
"""Update the display.""" """Update the display."""
@ -66,7 +63,7 @@ class Main(BaseScreen, SceenElement, TextScreen):
def exit(self) -> None: def exit(self) -> None:
"""Exit the game.""" """Exit the game."""
log.info("Exiting the game") logger.info("Exiting the game")
pygame.quit() pygame.quit()
sys.exit() sys.exit()
@ -75,16 +72,11 @@ class Main(BaseScreen, SceenElement, TextScreen):
self.game = Game(self.game_mode, self.settings) self.game = Game(self.game_mode, self.settings)
return self return self
def open_settings(self) -> "Main":
self._draw_background()
self.settings_screen = Settings()
return self
def _set_buttons(self) -> None: def _set_buttons(self) -> None:
self.buttons: list[Button] = [ self.buttons: list[Button] = [
Button("Play", self.play), Button("Play", self.play),
Button("AI", None), Button("AI", None),
Button("Settings", self.open_settings), Button("Settings", None),
Button("Quit", self.exit), Button("Quit", self.exit),
] ]

View File

@ -1,4 +1,5 @@
import pygame import pygame
from loguru import logger
from utils import CONFIG, Figure, Size from utils import CONFIG, Figure, Size
from .base import BaseScreen, SceenElement from .base import BaseScreen, SceenElement

View File

@ -1,8 +1,7 @@
import pygame import pygame
from loguru import logger
from utils import CONFIG, GameMode, Size from utils import CONFIG, GameMode, Size
from game.log import log
from .base import BaseScreen, SceenElement, TextScreen from .base import BaseScreen, SceenElement, TextScreen

View File

@ -1,99 +0,0 @@
import pygame
from utils import CONFIG, Size
from game.log import log
from .base import BaseScreen, SceenElement, TextScreen
from .button import Button
class Settings(BaseScreen, SceenElement, TextScreen):
def __init__(self) -> None:
self._initialize_surface()
self._initialize_rect()
self._initialize_font()
self._set_buttons()
self._initialize_increment_height()
def draw(self) -> None:
"""Update the display."""
self._draw_background()
self._draw_text()
def run(self) -> None:
self.draw()
def update(self) -> None:
pass
def _draw_text(self) -> None:
"""Draw the text on the score surface."""
for idx, text in enumerate(self.text):
x = self.surface.get_width() / 2
y = self.increment_height / 2 + idx * self.increment_height
self._display_text(text, pygame.Vector2(x, y))
def _display_text(self, text_value: tuple[str, int], pos: pygame.Vector2) -> None:
"""
Display a single text element on the score surface.
Args:
text_value: A tuple containing the label and value of the text element.
pos: The position (x, y) where the text should be displayed.
"""
text, value = text_value
if len(text) >= 10:
text_surface = self.font.render(f"{text}:", True, CONFIG.colors.fg_sidebar)
value_surface = self.font.render(f"{value}", True, CONFIG.colors.fg_sidebar)
value_rect = value_surface.get_rect(center=(pos.x, pos.y + 40))
self.surface.blit(value_surface, value_rect)
else:
text_surface = self.font.render(
f"{text}:{value}", True, CONFIG.colors.fg_sidebar
)
text_rect = text_surface.get_rect(center=pos)
self.surface.blit(text_surface, text_rect)
text_rect = text_surface.get_rect(center=pos)
self.surface.blit(text_surface, text_rect)
def _draw_border(self) -> None:
"""Draw the border of the score surface."""
pygame.draw.rect(
self.display_surface,
CONFIG.colors.border_highlight,
self.rect,
CONFIG.game.line_width * 2,
CONFIG.game.border_radius,
)
def _draw_background(self) -> None:
"""Fill the background of the score display."""
self.surface.fill(CONFIG.colors.bg_sidebar)
def _initialize_surface(self) -> None:
"""Initialize the score surface."""
self.surface = pygame.Surface(CONFIG.sidebar.score)
self.display_surface = pygame.display.get_surface()
def _initialize_rect(self) -> None:
"""Initialize the score rectangle."""
self.rect = self.surface.get_rect(
bottomright=CONFIG.window.size - CONFIG.window.padding
)
def _initialize_font(self) -> None:
"""Initialize the font used to display the score."""
self.font = pygame.font.Font(CONFIG.font.family, CONFIG.font.size)
def _initialize_increment_height(self) -> None:
"""Initialize the increment height for positioning text elements."""
self.increment_height = self.surface.get_height() / len(self.text)
def _update_display_surface(self) -> None:
"""Update the display surface."""
self.display_surface.blit(self.surface, self.rect)

View File

@ -2,9 +2,9 @@ from typing import Any, Callable, Optional
import numpy as np import numpy as np
import pygame import pygame
from loguru import logger
from utils import CONFIG, Direction, Figure, GameMode, Rotation from utils import CONFIG, Direction, Figure, GameMode, Rotation
from game.log import log
from game.sprites import Block, Tetromino from game.sprites import Block, Tetromino
from game.timer import Timer, Timers from game.timer import Timer, Timers
@ -195,13 +195,13 @@ class Tetris(BaseScreen):
""" """
for block in self.tetromino.blocks: for block in self.tetromino.blocks:
if block.pos.y <= 0: if block.pos.y <= 0:
log.info("Game over!") logger.info("Game over!")
return True return True
return False return False
def restart(self) -> None: def restart(self) -> None:
"""Restart the game.""" """Restart the game."""
log.info("Restarting the game") logger.info("Restarting the game")
self._reset_game_state() self._reset_game_state()
self._initialize_field_and_tetromino() self._initialize_field_and_tetromino()
self.game_over = False self.game_over = False

View File

@ -2,10 +2,9 @@ from typing import Any, Optional
import numpy as np import numpy as np
import pygame import pygame
from loguru import logger
from utils import CONFIG, Rotation, Size from utils import CONFIG, Rotation, Size
from game.log import log
class Block(pygame.sprite.Sprite): class Block(pygame.sprite.Sprite):
""" """

View File

@ -2,10 +2,9 @@ from typing import Any, Callable, Optional
import numpy as np import numpy as np
import pygame import pygame
from loguru import logger
from utils import CONFIG, Direction, Figure, Rotation, Size from utils import CONFIG, Direction, Figure, Rotation, Size
from game.log import log
from .block import Block from .block import Block

View File

@ -1,7 +1,6 @@
from .config import CONFIG from .config import CONFIG
from .enum import Direction, GameMode, Rotation from .enum import Direction, GameMode, Rotation
from .figure import Figure, FigureConfig from .figure import Figure, FigureConfig
from .log import log
from .path import BASE_PATH from .path import BASE_PATH
from .settings import read_settings, save_settings from .settings import read_settings, save_settings
from .tuples import Size from .tuples import Size
@ -9,7 +8,6 @@ from .tuples import Size
__all__ = [ __all__ = [
"BASE_PATH", "BASE_PATH",
"CONFIG", "CONFIG",
"log",
"Size", "Size",
"Figure", "Figure",
"FigureConfig", "FigureConfig",

View File

@ -0,0 +1,63 @@
from abc import ABC, ABCMeta
from attrs import define
class Color(ABC, metaclass=ABCMeta):
bg: str
bg_dark: str
bg_float: str
bg_highlight: str
bg_popup: str
bg_search: str
bg_sidebar: str
bg_statusline: str
bg_visual: str
black: str
blue: str
blue0: str
blue1: str
blue2: str
blue5: str
blue6: str
blue7: str
border: str
border_highlight: str
comment: str
cyan: str
dark3: str
dark5: str
delta_add: str
delta_delete: str
diff_add: str
diff_change: str
diff_delete: str
diff_text: str
error: str
fg: str
fg_dark: str
fg_float: str
fg_gutter: str
fg_sidebar: str
git_add: str
git_change: str
git_delete: str
git_ignore: str
git_signs_add: str
git_signs_change: str
git_signs_delete: str
green: str
green1: str
green2: str
hint: str
info: str
magenta: str
magenta2: str
orange: str
purple: str
red: str
red1: str
teal: str
terminal_black: str
warning: str
yellow: str

View File

@ -1,8 +1,10 @@
from attr import define from attr import define
from .base import Color
@define @define
class TokyoNightDay: class TokyoNightDay(Color):
bg = "#e1e2e7" bg = "#e1e2e7"
bg_dark = "#e9e9ec" bg_dark = "#e9e9ec"
bg_float = "#e9e9ec" bg_float = "#e9e9ec"

View File

@ -1,8 +1,10 @@
from attr import define from attr import define
from .base import Color
@define @define
class TokyoNightMoon: class TokyoNightMoon(Color):
bg = "#222436" bg = "#222436"
bg_dark = "#1e2030" bg_dark = "#1e2030"
bg_float = "#1e2030" bg_float = "#1e2030"

View File

@ -1,8 +1,10 @@
from attr import define from attr import define
from .base import Color
@define @define
class TokyoNightNight: class TokyoNightNight(Color):
bg = "#1a1b26" bg = "#1a1b26"
bg_dark = "#16161e" bg_dark = "#16161e"
bg_float = "#16161e" bg_float = "#16161e"

View File

@ -1,8 +1,10 @@
from attr import define from attr import define
from .base import Color
@define @define
class TokyoNightStorm: class TokyoNightStorm(Color):
bg = "#24283b" bg = "#24283b"
bg_dark = "#1f2335" bg_dark = "#1f2335"
bg_float = "#1f2335" bg_float = "#1f2335"

View File

@ -3,7 +3,8 @@ from pathlib import Path
from attr import define from attr import define
from pygame import Vector2 as Vec2 from pygame import Vector2 as Vec2
from .colors import COLOR_DICT from .colors import COLOR_DICT, TokyoNightNight
from .colors.tokyonight.base import Color
from .path import BASE_PATH from .path import BASE_PATH
from .settings import read_settings from .settings import read_settings
from .tuples import Size from .tuples import Size
@ -85,14 +86,14 @@ class AI:
@define @define
class Config: class Config:
log_level: str = "warning"
game: Game = Game() game: Game = Game()
sidebar: SideBar = SideBar() sidebar: SideBar = SideBar()
window: Window = Window() window: Window = Window()
font: Font = Font() font: Font = Font()
music: Music = Music() music: Music = Music()
colors = COLOR_DICT[read_settings()["General"]["colorscheme"]]() colors: Color = COLOR_DICT.get(
read_settings()["General"]["colorscheme"], TokyoNightNight
)()
ai = AI() ai = AI()
fps: int = 60 fps: int = 60

View File

@ -1,15 +0,0 @@
from loguru import logger
from .config import CONFIG
from .path import BASE_PATH
log = logger.bind(name="utils")
log.add(
BASE_PATH / ".logs" / "utils.log",
format="{time} | {level} | {message}",
level=CONFIG.log_level.upper(),
rotation="10 MB",
compression="zip",
filter=lambda record: record["extra"].get("name") == "utils",
)

View File

@ -2,6 +2,7 @@ from pathlib import Path
from typing import Any, Optional from typing import Any, Optional
import toml import toml
from loguru import logger
from .path import BASE_PATH from .path import BASE_PATH
@ -25,10 +26,10 @@ def read_settings(
""" """
try: try:
with open(file_path, "r") as file: with open(file_path, "r") as file:
return toml.load(file) return dict(toml.load(file))
except FileNotFoundError: except FileNotFoundError:
log.error(f"Error: The file '{file_path}' does not exist.") logger.error(f"Error: The file '{file_path}' does not exist.")
return {} return {}
except toml.TomlDecodeError as e: except toml.TomlDecodeError as e:
log.error(f"rror decoding TOML file: {e}") logger.error(f"rror decoding TOML file: {e}")
return {} return {}