From e6a2b474e6a40b1f4657fc5a6b5a9fcfd054aadb Mon Sep 17 00:00:00 2001 From: Kristofers Solo Date: Mon, 8 Jan 2024 18:39:03 +0200 Subject: [PATCH] chore: remove unnecessary imports --- pyproject.toml | 4 +++ src/game/screens/base.py | 14 ++++++---- src/game/screens/base_button.py | 9 ++++--- src/game/screens/button.py | 15 +++++------ src/game/screens/game.py | 18 ++++++------- src/game/screens/main.py | 23 ++++++++-------- src/game/screens/preview.py | 7 ++++- src/game/screens/score.py | 8 ++---- src/game/screens/tetris.py | 47 +++++++++++--------------------- src/game/sprites/block.py | 18 ++++++------- src/game/sprites/tetromino.py | 48 ++++++++++++++------------------- src/game/timer.py | 5 +++- src/utils/config.py | 13 +++++---- src/utils/figure.py | 10 +++---- src/utils/settings.py | 7 +++-- src/utils/tuples.py | 5 +++- 16 files changed, 124 insertions(+), 127 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index c742f2e..905b468 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -69,6 +69,7 @@ extend-select = [ "TID", "YTT", ] +ignore = ["E741"] show-fixes = true line-length = 120 indent-width = 4 @@ -86,3 +87,6 @@ skip-magic-trailing-comma = false line-ending = "auto" docstring-code-format = true docstring-code-line-length = 40 + +[tool.black] +line-length = 120 diff --git a/src/game/screens/base.py b/src/game/screens/base.py index 467714b..ad2f9c4 100644 --- a/src/game/screens/base.py +++ b/src/game/screens/base.py @@ -1,19 +1,23 @@ from abc import ABC, ABCMeta, abstractmethod +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from typing import Any class BaseScreen(ABC, metaclass=ABCMeta): """Base screen class.""" @abstractmethod - def update(self, *args, **kwargs) -> None: + def update(self, *args: Any, **kwargs: Any) -> None: """Update the screen.""" @abstractmethod - def draw(self, *args, **kwargs) -> None: + def draw(self, *args: Any, **kwargs: Any) -> None: """Draw the screen.""" @abstractmethod - def run(self, *args, **kwargs) -> None: + def run(self, *args: Any, **kwargs: Any) -> None: """Run the screen.""" @@ -31,7 +35,7 @@ class SceenElement(ABC, metaclass=ABCMeta): """Initialize the surface.""" @abstractmethod - def _initialize_rect(self, *args, **kwargs) -> None: + def _initialize_rect(self, *args: Any, **kwargs: Any) -> None: """Initialize the rectangle.""" @abstractmethod @@ -51,5 +55,5 @@ class TextScreen(ABC, metaclass=ABCMeta): """Draw the text on the surface.""" @abstractmethod - def _display_text(self, *args, **kwargs) -> None: + def _display_text(self, *args: Any, **kwargs: Any) -> None: """Display the text.""" diff --git a/src/game/screens/base_button.py b/src/game/screens/base_button.py index 4737989..231e19f 100644 --- a/src/game/screens/base_button.py +++ b/src/game/screens/base_button.py @@ -1,5 +1,8 @@ from abc import ABC, ABCMeta, abstractmethod -from typing import Any, Callable, Optional +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from typing import Any, Callable, Optional import pygame @@ -7,9 +10,7 @@ import pygame class BaseButton(ABC, metaclass=ABCMeta): """Base button class.""" - def __init__( - self, text: str, action: Optional[Callable[[], Optional[Any]]] - ) -> None: + def __init__(self, text: str, action: Optional[Callable[[], Optional[Any]]]) -> None: self.action = action self.text = text diff --git a/src/game/screens/button.py b/src/game/screens/button.py index acf36b2..0d86ec4 100644 --- a/src/game/screens/button.py +++ b/src/game/screens/button.py @@ -1,4 +1,4 @@ -from typing import Any, Callable, Optional +from typing import TYPE_CHECKING import pygame from utils import CONFIG @@ -6,11 +6,12 @@ from utils import CONFIG from .base import BaseScreen, SceenElement, TextScreen from .base_button import BaseButton +if TYPE_CHECKING: + from typing import Any, Callable, Optional + class Button(BaseButton, BaseScreen, SceenElement, TextScreen): - def __init__( - self, text: str, action: Optional[Callable[[], Optional[Any]]] - ) -> None: + def __init__(self, text: str, action: Optional[Callable[[], Optional[Any]]]) -> None: super().__init__(text, action) self._initialize_surface() self._initialize_font() @@ -19,11 +20,7 @@ class Button(BaseButton, BaseScreen, SceenElement, TextScreen): def on_click(self, event: pygame.Event) -> None: """Handle click event.""" - if ( - event.type == pygame.MOUSEBUTTONDOWN - and self.rect.collidepoint(event.pos) - and self.action - ): + if event.type == pygame.MOUSEBUTTONDOWN and self.rect.collidepoint(event.pos) and self.action: self.action() def on_hover(self, event: pygame.Event) -> None: diff --git a/src/game/screens/game.py b/src/game/screens/game.py index 518d002..f374ec3 100644 --- a/src/game/screens/game.py +++ b/src/game/screens/game.py @@ -1,13 +1,18 @@ -from typing import Any +from typing import TYPE_CHECKING import pygame -from utils import CONFIG, Figure, GameMode +from utils import CONFIG, GameMode from .base import BaseScreen from .preview import Preview from .score import Score from .tetris import Tetris +if TYPE_CHECKING: + from typing import Any + + from utils import Figure + class Game(BaseScreen): """ @@ -71,9 +76,7 @@ class Game(BaseScreen): self.clock = pygame.time.Clock() self.next_figure: Figure = self._generate_next_figure() - self.tetris = Tetris( - self._get_next_figure, self._update_score, self.game_mode, self.settings - ) + self.tetris = Tetris(self._get_next_figure, self._update_score, self.game_mode, self.settings) self.score = Score(self.game_mode) self.preview = Preview() @@ -110,10 +113,7 @@ class Game(BaseScreen): def _start_background_music(self) -> None: """Start playing background music.""" - if ( - self.game_mode is GameMode.PLAYER - and self.settings["Volume"]["Music"]["enabled"] - ): + if self.game_mode is GameMode.PLAYER and self.settings["Volume"]["Music"]["enabled"]: self.music = pygame.mixer.Sound(CONFIG.music.background) self.music.set_volume(self.settings["Volume"]["Music"]["level"]) self.music.play(-1) diff --git a/src/game/screens/main.py b/src/game/screens/main.py index a2fe10a..3e98147 100644 --- a/src/game/screens/main.py +++ b/src/game/screens/main.py @@ -1,14 +1,19 @@ import sys -from typing import Optional +from typing import TYPE_CHECKING import pygame from loguru import logger -from utils import CONFIG, GameMode, read_settings +from utils import CONFIG, read_settings from .base import BaseScreen, SceenElement, TextScreen from .button import Button from .game import Game +if TYPE_CHECKING: + from typing import Optional + + from utils import GameMode + class Main(BaseScreen, SceenElement, TextScreen): """ @@ -45,9 +50,7 @@ class Main(BaseScreen, SceenElement, TextScreen): if event.type == pygame.QUIT: self.exit() elif event.type == pygame.KEYDOWN: - if event.key in [ - pygame.key.key_code(key) for key in self.settings["General"]["quit"] - ]: + if event.key in [pygame.key.key_code(key) for key in self.settings["General"]["quit"]]: self.exit() if not self.game: @@ -126,9 +129,9 @@ class Main(BaseScreen, SceenElement, TextScreen): def _initialize_increment_height(self) -> None: """Initialize the increment height for positioning text elements/buttons.""" - self.increment_height: float = ( - self.display_surface.get_height() - CONFIG.window.size.height / 2 - ) / len(self.buttons) + self.increment_height: float = (self.display_surface.get_height() - CONFIG.window.size.height / 2) / len( + self.buttons + ) def _display_text(self, text: str, pos: tuple[float, float]) -> None: """ @@ -156,8 +159,6 @@ class Main(BaseScreen, SceenElement, TextScreen): for idx, button in enumerate(self.buttons): x = self.display_surface.get_width() / 2 y = ( - self.increment_height / 4 - + idx * self.increment_height - + CONFIG.window.size.height / 4 + self.increment_height / 4 + idx * self.increment_height + CONFIG.window.size.height / 4 ) # TODO: tweak a bit more button.draw(self.display_surface, (x, y)) diff --git a/src/game/screens/preview.py b/src/game/screens/preview.py index 3a761dc..6a766ef 100644 --- a/src/game/screens/preview.py +++ b/src/game/screens/preview.py @@ -1,8 +1,13 @@ +from typing import TYPE_CHECKING + import pygame -from utils import CONFIG, Figure +from utils import CONFIG from .base import BaseScreen, SceenElement +if TYPE_CHECKING: + from utils import Figure + class Preview(BaseScreen, SceenElement): """ diff --git a/src/game/screens/score.py b/src/game/screens/score.py index 9042e4e..cc93c97 100644 --- a/src/game/screens/score.py +++ b/src/game/screens/score.py @@ -118,9 +118,7 @@ class Score(BaseScreen, SceenElement, TextScreen): self.surface.blit(value_surface, value_rect) else: - text_surface = self.font.render( - f"{text}: {value}", True, CONFIG.colors.fg_sidebar - ) + 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) @@ -148,9 +146,7 @@ class Score(BaseScreen, SceenElement, TextScreen): def _initialize_rect(self) -> None: """Initialize the score rectangle.""" - self.rect = self.surface.get_rect( - bottomright=CONFIG.window.size - CONFIG.window.padding - ) + 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.""" diff --git a/src/game/screens/tetris.py b/src/game/screens/tetris.py index ff06a2a..3e6277f 100644 --- a/src/game/screens/tetris.py +++ b/src/game/screens/tetris.py @@ -1,15 +1,20 @@ -from typing import Any, Callable, Optional +from typing import TYPE_CHECKING import numpy as np import pygame from loguru import logger from utils import CONFIG, Direction, Figure, GameMode, Rotation -from game.sprites import Block, Tetromino +from game.sprites import Tetromino from game.timer import Timer, Timers from .base import BaseScreen +if TYPE_CHECKING: + from typing import Any, Callable, Optional + + from game.sprites import Block + class Tetris(BaseScreen): """ @@ -161,9 +166,7 @@ class Tetris(BaseScreen): """ return self.tetromino.drop() - def create_new_tetromino( - self, shape: Optional[Figure] = None - ) -> Optional[Tetromino]: + def create_new_tetromino(self, shape: Optional[Figure] = None) -> Optional[Tetromino]: """Create a new tetromino and perform necessary actions.""" self._play_landing_sound() self._check_finished_rows() @@ -377,19 +380,13 @@ class Tetris(BaseScreen): def _initialize_sound(self) -> None: """Initialize game sounds.""" - if ( - self.game_mode is GameMode.PLAYER - and self.settings["Volume"]["SFX"]["enabled"] - ): + if self.game_mode is GameMode.PLAYER and self.settings["Volume"]["SFX"]["enabled"]: self.landing_sound = pygame.mixer.Sound(CONFIG.music.landing) self.landing_sound.set_volume(self.settings["Volume"]["SFX"]["level"]) def _play_landing_sound(self) -> None: """Play the landing sound effect.""" - if ( - self.game_mode is GameMode.PLAYER - and self.settings["Volume"]["SFX"]["enabled"] - ): + if self.game_mode is GameMode.PLAYER and self.settings["Volume"]["SFX"]["enabled"]: self.landing_sound.play() def _update_display_surface(self) -> None: @@ -411,14 +408,10 @@ class Tetris(BaseScreen): See `settings.toml` for the default key bindings. """ - right_keys: list[int] = [ - pygame.key.key_code(key) for key in self.settings["Movement"]["right"] - ] + right_keys: list[int] = [pygame.key.key_code(key) for key in self.settings["Movement"]["right"]] right_key_pressed = any(keys[key] for key in right_keys) - left_keys: list[int] = [ - pygame.key.key_code(key) for key in self.settings["Movement"]["left"] - ] + left_keys: list[int] = [pygame.key.key_code(key) for key in self.settings["Movement"]["left"]] left_key_pressed = any(keys[key] for key in left_keys) if not self.timers.horizontal.active: @@ -435,14 +428,10 @@ class Tetris(BaseScreen): See `settings.toml` for the default key bindings. """ - cw_keys: list[int] = [ - pygame.key.key_code(key) for key in self.settings["Rotation"]["cw"] - ] + cw_keys: list[int] = [pygame.key.key_code(key) for key in self.settings["Rotation"]["cw"]] cw_key_pressed = any(keys[key] for key in cw_keys) - ccw_keys: list[int] = [ - pygame.key.key_code(key) for key in self.settings["Rotation"]["ccw"] - ] + ccw_keys: list[int] = [pygame.key.key_code(key) for key in self.settings["Rotation"]["ccw"]] ccw_key_pressed = any(keys[key] for key in ccw_keys) if not self.timers.rotation.active: @@ -460,9 +449,7 @@ class Tetris(BaseScreen): See `settings.toml` for the default key bindings. """ - down_keys: list[int] = [ - pygame.key.key_code(key) for key in self.settings["Movement"]["down"] - ] + down_keys: list[int] = [pygame.key.key_code(key) for key in self.settings["Movement"]["down"]] down_key_pressed = any(keys[key] for key in down_keys) if not self.down_pressed and down_key_pressed: self.down_pressed = True @@ -478,9 +465,7 @@ class Tetris(BaseScreen): See `settings.toml` for the default key bindings. """ - drop_keys = [ - pygame.key.key_code(key) for key in self.settings["Action"]["drop"] - ] + drop_keys = [pygame.key.key_code(key) for key in self.settings["Action"]["drop"]] drop_key_pressed = any(keys[key] for key in drop_keys) if not self.timers.drop.active and drop_key_pressed: diff --git a/src/game/sprites/block.py b/src/game/sprites/block.py index 747b88f..2076cac 100644 --- a/src/game/sprites/block.py +++ b/src/game/sprites/block.py @@ -1,9 +1,13 @@ -from typing import Any, Optional +from typing import TYPE_CHECKING -import numpy as np import pygame from utils import CONFIG, Rotation +if TYPE_CHECKING: + from typing import Any, Optional + + import numpy as np + class Block(pygame.sprite.Sprite): """ @@ -24,7 +28,7 @@ class Block(pygame.sprite.Sprite): self, /, *, - group: pygame.sprite.Group, + group: pygame.sprite.Group, # type: ignore pos: pygame.Vector2, color: str, phantom: bool = False, @@ -42,9 +46,7 @@ class Block(pygame.sprite.Sprite): self.pos.y * CONFIG.game.cell.width, ) - def vertical_collision( - self, x: int, field: np.ndarray[Optional["Block"], Any] - ) -> bool: + def vertical_collision(self, x: int, field: np.ndarray[Optional["Block"], Any]) -> bool: """ Checks for vertical collision with the game field. @@ -57,9 +59,7 @@ class Block(pygame.sprite.Sprite): """ return not 0 <= x < CONFIG.game.columns or field[int(self.pos.y), x] - def horizontal_collision( - self, y: int, field: np.ndarray[Optional["Block"], Any] - ) -> bool: + def horizontal_collision(self, y: int, field: np.ndarray[Optional["Block"], Any]) -> bool: """ Checks for horizontal collision with the game field. diff --git a/src/game/sprites/tetromino.py b/src/game/sprites/tetromino.py index 0c0ca6a..acf25f6 100644 --- a/src/game/sprites/tetromino.py +++ b/src/game/sprites/tetromino.py @@ -1,10 +1,14 @@ -from typing import Any, Callable, Optional +from typing import TYPE_CHECKING -import numpy as np import pygame from utils import CONFIG, Direction, Figure, Rotation -from .block import Block +if TYPE_CHECKING: + from typing import Any, Callable, Optional + + import numpy as np + + from .block import Block class Tetromino: @@ -28,7 +32,7 @@ class Tetromino: def __init__( self, - group: pygame.sprite.Group, + group: pygame.sprite.Group, # type: ignore create_new: Optional[Callable[[Optional[Figure]], Optional["Tetromino"]]], field: np.ndarray[Optional[Block], Any], shape: Optional[Figure] = None, @@ -98,9 +102,7 @@ class Tetromino: pivot: pygame.Vector2 = self.blocks[0].pos for _ in range(3): - new_positions: list[pygame.Vector2] = [ - block.rotate(pivot, rotation) for block in self.blocks - ] + new_positions: list[pygame.Vector2] = [block.rotate(pivot, rotation) for block in self.blocks] if self._are_new_positions_valid(new_positions): self.update_block_positions(new_positions) @@ -142,13 +144,11 @@ class Tetromino: True if there is a collision, False otherwise. """ - return self._check_horizontal_collision( + return self._check_horizontal_collision(self.blocks, direction) or self._check_vertical_collision( self.blocks, direction - ) or self._check_vertical_collision(self.blocks, direction) + ) - def _check_vertical_collision( - self, blocks: list[Block], direction: Direction - ) -> bool: + def _check_vertical_collision(self, blocks: list[Block], direction: Direction) -> bool: """ Checks for vertical collision. @@ -159,14 +159,9 @@ class Tetromino: Returns: True if there is a vertical collision, False otherwise. """ - return any( - block.vertical_collision(int(block.pos.x + direction.value), self.field) - for block in self.blocks - ) + return any(block.vertical_collision(int(block.pos.x + direction.value), self.field) for block in self.blocks) - def _check_horizontal_collision( - self, blocks: list[Block], direction: Direction - ) -> bool: + def _check_horizontal_collision(self, blocks: list[Block], direction: Direction) -> bool: """ Checks for horizontal collision. @@ -177,10 +172,7 @@ class Tetromino: Returns: True if there is a horizontal collision, False otherwise. """ - return any( - block.horizontal_collision(int(block.pos.y + direction.value), self.field) - for block in self.blocks - ) + return any(block.horizontal_collision(int(block.pos.y + direction.value), self.field) for block in self.blocks) def update_block_positions(self, new_positions: list[pygame.Vector2]) -> None: """ @@ -209,7 +201,10 @@ class Tetromino: for pos in new_positions ) - def _initialize_blocks(self, group: pygame.sprite.Group) -> list[Block]: + def _initialize_blocks( + self, + group: pygame.sprite.Group, # type: ignore + ) -> list[Block]: """ Initializes Tetromino blocks. @@ -219,10 +214,7 @@ class Tetromino: Returns: List of initialized blocks. """ - return [ - Block(group=group, pos=pos, color=self.color, phantom=self.phantom) - for pos in self.block_positions - ] + return [Block(group=group, pos=pos, color=self.color, phantom=self.phantom) for pos in self.block_positions] def _generate_figure(self, shape: Optional[Figure]) -> Figure: """ diff --git a/src/game/timer.py b/src/game/timer.py index 1df5ce1..60d9603 100644 --- a/src/game/timer.py +++ b/src/game/timer.py @@ -1,8 +1,11 @@ -from typing import Any, Callable, NamedTuple, Optional +from typing import TYPE_CHECKING import pygame from attrs import define, field +if TYPE_CHECKING: + from typing import Any, Callable, NamedTuple, Optional + @define class Timer: diff --git a/src/utils/config.py b/src/utils/config.py index 20c3874..e2cc182 100644 --- a/src/utils/config.py +++ b/src/utils/config.py @@ -1,7 +1,6 @@ -from pathlib import Path +from typing import TYPE_CHECKING from attr import define -from pygame import Vector2 as Vec2 from .colors import COLOR_DICT, TokyoNightNight from .colors.tokyonight.base import Color @@ -9,6 +8,12 @@ from .path import BASE_PATH from .settings import read_settings from .tuples import Size +if TYPE_CHECKING: + from pathlib import Path + + from pygame import Vector2 as Vec2 + + PADDING = 20 @@ -139,9 +144,7 @@ class Config: window: Window = Window() font: Font = Font() music: Music = Music() - colors: Color = COLOR_DICT.get( - read_settings()["General"]["colorscheme"], TokyoNightNight - )() + colors: Color = COLOR_DICT.get(read_settings()["General"]["colorscheme"], TokyoNightNight)() CONFIG = Config() diff --git a/src/utils/figure.py b/src/utils/figure.py index c4029fd..fb6b8fc 100644 --- a/src/utils/figure.py +++ b/src/utils/figure.py @@ -1,13 +1,15 @@ import random from enum import Enum -from typing import NamedTuple +from typing import TYPE_CHECKING, NamedTuple import pygame -from pygame import Vector2 as Vec2 from .colors import TokyoNightNight from .path import BASE_PATH +if TYPE_CHECKING: + from pygame import Vector2 as Vec2 + class FigureConfig(NamedTuple): """ @@ -23,9 +25,7 @@ class FigureConfig(NamedTuple): def _load_image(filename: str) -> pygame.Surface: - return pygame.image.load( - BASE_PATH / "assets" / "figures" / filename - ) # TODO: add `.convert_alpha()`` + return pygame.image.load(BASE_PATH / "assets" / "figures" / filename) # TODO: add `.convert_alpha()`` # TODO: change colors of images diff --git a/src/utils/settings.py b/src/utils/settings.py index b59b9f2..a349bce 100644 --- a/src/utils/settings.py +++ b/src/utils/settings.py @@ -1,11 +1,14 @@ -from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING import toml from loguru import logger from .path import BASE_PATH +if TYPE_CHECKING: + from pathlib import Path + from typing import Any + def save_settings(settings: dict[str, Any], file_path: Path) -> None: """ diff --git a/src/utils/tuples.py b/src/utils/tuples.py index 27e6e0a..1ca516a 100644 --- a/src/utils/tuples.py +++ b/src/utils/tuples.py @@ -1,4 +1,7 @@ -from typing import NamedTuple, Union +from typing import TYPE_CHECKING, NamedTuple + +if TYPE_CHECKING: + from typing import Union class Size(NamedTuple):