Code Monkey home page Code Monkey logo

supermariobros.3-pygame's Introduction

illustration-TitleScreen


Sommaire


Developers

This game is developed by Naulan CHRZASZCZ, with on collaboration of Antoine BOUCHE

supermariobros.3-pygame's People

Contributors

naulan-chrzaszcz avatar

Watchers

 avatar

supermariobros.3-pygame's Issues

Find how to load correctly images on `loader.py`

I created image_data.py

@dataclass
class ImageData(object):
    type_of_block: TypeOfBlock
    type_of_image: TypeOfImage

    x: int
    y: int
    name: str
    data: Surface
  • Render all oriented object
  • Simplify loading in a directory (thanks to listdir())
  • delete pathIndex.json file
  • replace data variable to a more simple way

Improve the game framerate management

Old code

class Fps(object):
    def __init__(self):
        self.prev_time = time.time()
        self.clock = Clock()
        self.font = Font()

        self.benchmark = True

        self.get()

        self.t = 0
        self.dt = self.manage(fps=120)

        fps = round(self.clock.get_fps())
        self.countFps = 1
        self.sumFps = 0
        self.avg = fps//self.countFps
        self.max = fps
        self.min = 1_000_000

    def manage(self, fps):
        """ Manage the delta time (Time between two frame) """
        self.clock.tick(fps)     # Cadence the clock of the game
        self.dt = float(time.time() - self.prev_time)     # The time between old frame and the new frame
        self.prev_time = time.time()     # Previous frame
        return self.dt * 60     # 60 is fps we need to have in game

    def average(self):
        """ 
           Make a average of fps getted
           @return average of fps, max fps, min fps
        """
        fps = round(self.clock.get_fps())
        self.sumFps += fps
        self.countFps += 1
        self.avg = self.sumFps//self.countFps

        if fps > self.max:
            self.max = fps
        if self.min > fps > 0:
            self.min = fps

        return self.avg,self.max,self.min

    def get(self):
        """ get the framerate in game """
        return round(self.clock.get_fps())

    def draw(self,surface):
        """ Display on a surface all informations about the framerate in game """
        msg = [self.font.font.render(f'{self.get()} Fps',0,(255,255,255)),self.font.font.render(f'avg:  {self.avg} Fps',0,(255,255,255)),self.font.font.render(f'max: {self.max} Fps',0,(255,255,255)),self.font.font.render(f'min: {self.min} Fps',0,(255,255,255)),self.font.font.render(f'var: {round(self.dt,3)} ms',0,(255,255,255))]
        self.font.outline(surface,msg[1],(5,5))
        self.font.outline(surface,msg[0],(5,msg[0].get_height() + 7))
        self.font.outline(surface,msg[2],(msg[0].get_width() * 2.5,5))
        self.font.outline(surface,msg[3],(msg[0].get_width() * 2.5,msg[2].get_height() * 1.5))
        self.font.outline(surface,msg[4],(5,msg[1].get_height() * 2.5))
        surface.blit(msg[1],(5,5))
        surface.blit(msg[0],(5,msg[0].get_height() + 7))
        surface.blit(msg[2],(msg[0].get_width() * 2.5,5))
        surface.blit(msg[3],(msg[0].get_width() * 2.5,msg[2].get_height() * 1.5))
        surface.blit(msg[4],(5,msg[1].get_height() * 2.5))

We need to improve the code of Fps class when #7 #19 is done

I suppose wrong things

  • The Fps class must be a Singleton. Why ? Because we need to have dt variable on many class like Entity object or Scene class
  • The code style not correspond with actual code
  • The draw function is maybe on a wrong place.
  • The average function return also a min value and max value (Weird)
  • Unknow self.t variable ?

Find a way to simplify how to get an image on sprite sheet

@staticmethod
def position_platform_on_sheet(type_of_block) -> tuple:
    match type_of_block:
        case TypeOfBlock.TOP:
            return 1, 1
        case TypeOfBlock.BOTTOM:
            return 7, 1
        case TypeOfBlock.LEFT:
            return 8, 1
        case TypeOfBlock.RIGHT:
            return 5, 1
        case TypeOfBlock.CORNER_LEFT_TOP:
            return 0, 1
        # ...

I wrote this function but i'm going to think is dirty

Refractor the `save.json` and the code which come with him

before

{
    "PowerUpInventory": {
        "1": null,
        "2": null,
        "3": null
    },
    "Position": [
        16,
        128
    ],
    "GraphicsDriver": "AMD Radeon(TM) Vega 8 Graphics",
    "ResolutionsAvailable": [
        [
            1920,
            1080
        ], ...
    ],
    "ResolutionEdited": true,
    "Score": 0,
    "State": "little",
    "Coins": 0,
    "Life": 4,
    "Who": "MARIO",
    "ControllerCalibrate": false,
    "Resolution": [
        1280,
        720
    ]
}

After

After #14 done, we need to rewrite how to save the player data.
We need to store the file into %AppData% for Windows environment and ~/.SuperMarioBros.3 for Linux environment because before the save.json is stored into res of game code source and we don't have the possibility to had different save between computer or between user (It do to delete the save.json into res, not really user friendly)
As the MapsGenerator, maybe the json format is to heavy.

inventory=null,null,null
position=16,128
...

Had a text file is better to fast read.

Render save.json to oriented object

  • inventory.py
  • state.py
  • position.py
  • save.py

Edit the current dirty design pattern to a gretter for remove all `isinstance` into the main game loop

# ...
for sprite in self.sprites:
  if isinstance(sprite, Block):
      sprite.update(maps=self.maps, display=display)
  
  if isinstance(sprite, Floor):
      if all([self.maps.camera.rect.left + 16 >= -sprite.rect.left,
              (TILE_WIDTH - self.maps.camera.rect.left + 390) >= sprite.rect.left]):
          display.blit(sprite.image, self.maps.camera.apply(sprite))
  
  if isinstance(sprite, LootBlock):
      if len(sprite.mushrooms) != 0:
          for mush in sprite.mushrooms:
              if all([self.maps.camera.rect.left + 16 >= -mush.rect.left,
                      (TILE_WIDTH - self.maps.camera.rect.left + 390) >= mush.rect.left]):
                  display.blit(mush.image, self.maps.camera.apply(mush))
      if all([self.maps.camera.rect.left + 16 >= -sprite.rect.left,
              (TILE_WIDTH - self.maps.camera.rect.left + 390) >= sprite.rect.left]):
          display.blit(sprite.image, self.maps.camera.apply(sprite))
  
  if isinstance(sprite, Vegetable) or isinstance(sprite, Coin) or isinstance(sprite, Cloud):
      if all([self.maps.camera.rect.left + 16 >= -sprite.rect.left,
              (TILE_WIDTH - self.maps.camera.rect.left + 390) >= sprite.rect.left]):
          display.blit(sprite.image, self.maps.camera.apply(sprite))
  
  if isinstance(sprite, Goomba) or isinstance(sprite, Koopa) or isinstance(sprite, Coin):
      if sprite.step == 1:
          self.sprites.remove(sprite)
      if all([self.maps.camera.rect.left + 16 >= -sprite.rect.left,
              (TILE_WIDTH - self.maps.camera.rect.left + 390) >= sprite.rect.left]):
          display.blit(sprite.image, self.maps.camera.apply(sprite))
# ...

`MapsGenerator` as a `list`

I've a code something like this

class MapsGenerator(list):
    def __init__(self, iterable: List[Map]) -> None:
        super().__init__(item for item in iterable)

    def __setitem__(self, index: int, item: Map) -> None:
        super().__setitem__(index, item)

    def insert(self, index: int, item: Map) -> None:
        super().insert(index, str(item))

    def append(self, item: Map) -> None:
        super().append(item)

    def extend(self, other) -> None:
        if isinstance(other, type(self)):
            super().extend(other)
        else:
            super().extend(item for item in other)

So, the MapGenerator have comportement of a list but the name of this class is weird with the list which is herited by the class
What do you think @TheblackReaper060303 ?

sources:

The `Game` class must be on a `Singleton` pattern

The game class must be a Singleton

class Game(object):
    """ 
        Environment where everything will works together. 
        This class have only one instance (Singleton Patern)
    """
    __instance = None    # Private variable

    def __new__(cls, *args, **kwargs):
        """ 
            Return only one instance of this class.
            @return Game instance into __instance variable
        """
        if cls.__instance is None:
            cls.__instance = super(Game, cls).__new__(cls, *args, **kwargs)
        return cls.__instance
   
    @staticmethod
    def get_instance():
        """ 
            Return only one instance of this class.
            @return Game instance into __instance variable
        """
        if Game.__instance is None:
            Game.__instance = Game()
        return Game.__instance

Finding how to create properly a scene (without shenanigans)

Old code

class Scene0(object):
    """ Scene n°0
            Qu'es-ce qu'il se passe ?
                1. Debut = Fade in sur "intro-bg.png" pendant 1.5s
                2. Reste static pendant Stage1Msc
                3. Fade out sur "intro-bg.png" pendant 1.5s
                4. Fin = Passe à la Scene n°1
    """

    def __init__(self):
        self.step = [True, False]
        self.finish = False
        self.background = pg.image.load("res/sheets/intro-bg.png")
        self.alpha = 0
        self.t = 0

    def getFinish(self) -> bool:
        return self.finish

    def start(self, surface: Surface, dt: float) -> None:
        """ Demarre l'animation.
            (Fade in par default)
                :param dt: DeltaTime """
        surface.fill((0, 0, 0))

        # Timer
        if int(self.t) == 100:
            # Disable fade in and enable fade out
            self.step = [False, True]
        elif int(self.t) == 200:
            # Pass to scene n°1
            self.finish = True

        self.background.set_alpha(self.alpha)
        self.alpha += (5 * dt) if self.step[0] else 0
        self.alpha -= (5 * dt) if self.step[1] else 0
        surface.blit(self.background, (0, 0))
        self.t += (1*dt)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.