| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- import os
- from typing import Tuple
- import pygame
- from jogai import settings, utils, videogame
- from jogai._globals import _window
- from jogai.translations import gettext as _
- class Scene:
- """
- A videogame scene with background color and an optional image.
- """
- _image = None
- _rect = None
- filename = ''
- background = settings.SCENE_DEFAULT_BACKGROUND
- def __init__(
- self,
- image_filename: str = '',
- background: Tuple[int, int, int] = settings.SCENE_DEFAULT_BACKGROUND,
- ):
- if not isinstance(image_filename, str):
- raise TypeError(_('The image filename must be a string'))
- self.change_background(background)
- if image_filename:
- self.change_image(image_filename)
- @property
- def height(self):
- return self._rect.height
- @property
- def width(self):
- return self._rect.width
- @property
- def x(self):
- return self._rect.x
- def change_background(self, background: Tuple[int, int, int]):
- """
- Change the background color.
- Parameters:
- background: A tuple with the R,G,B components.
- Examples:
- >>> sc = Scene()
- >>> sc.change_background((255, 255, 255))
- """
- match background:
- case r, g, b if (
- isinstance(r, int)
- and isinstance(g, int)
- and isinstance(b, int)
- and 0 <= r <= 255
- and 0 <= g <= 255
- and 0 <= b <= 255
- ):
- self.background = (r, g, b)
- case _:
- raise ValueError(
- _(
- 'The background color must be a tuple with three integers (r,g,b) between 0 and 255.'
- )
- )
- def change_image(self, filename: str) -> bool:
- """
- Change the scene image.
- Parameters:
- filename: The image filename to be changed.
- Examples:
- >>> sc = Scene()
- >>> sc.change_image('test.png')
- """
- self._image, self._rect = utils._load_image(
- settings.SCENES_DIR, filename
- )
- self.filename = filename
- def set_position(self, x: int):
- """
- Set the scene abscissa position.
- The scene painted will never exceed the edges of the image.
- The x coordinate is a non-positive number (scene is moving to the left).
- Parameters:
- x: coordinate in horizontal axis
- Examples:
- >>> sc = Scene('test_large.png')
- >>> sc.set_position(300)
- """
- if not isinstance(x, int):
- raise TypeError(_('The x coordinate must be an integer.'))
- # Set x in range to prevent the scene from being outside the window.
- # The minus sign is essential to correctly position the scene.
- self._rect.x = -min(
- max(0, x), self._rect.width - settings.WINDOW_WIDTH
- )
|