C ++ game and decorator pattern

I am porting a 2D platformer and need a good way to get some extensibility from my levels. I'm not sure what Decorator is here, but nothing comes to mind. Perhaps I need something unique.

Anyway, let's say I have a base tile that has things like an image and whether the player can walk through it (background or foreground). Now I want to add properties to them, like making some tiles act as ladders or hurting or killing the player on contact. Maybe some may disappear. Some properties can be combined.

It sounds like a decorator, but I really don't like how it requires my base class to implement dummy versions of everything, like isLadder()

, isLethal()

etc. Is there a better way? I'm not going to be the guy who changes my design so it looks like something out of a GoF book.

Sorry if this has been asked a million times before, I didn't quite find it in the related questions.

+2


source to share


5 answers


As you are developing methods of a class, you can make a huge change in the way is difficult to realize the Decorator - for example, instead of isLadder()

and isLethal()

, etc., why not use methods based on the ways in which the player can interact with the tile ( enter(from_dir)

, exit(to_dir)

), etc. .d.? The death tile can override the method enter()

to signal that the player should be killed; stair tiles can override either enter()

or exit()

depending on the desired functionality.



+4


source


David is right. It could be something like this:



class Tile
{
    public bool allowsPassThrough()
    {}

    // couldn't find a better name for this method
    public void passThrough(Player player)
    {}
}

class LethalTile extends Tile
{
    public void passThrough(Player player)
    {
        player.kill();
    }
}

      

+2


source


I would introduce something like the TileTraits class. Each tile can return its traits via the well ..., getTraits () method. TileTraits can be extended to support as many tiling functions as possible. Something like:

class TileTraits
{
public: 
   enum TileTrait{ Walkable  = 1, 
                   Climbable = 1 << 1, 
                   Lethal    = 1 << 2 };
private:
   TileTrait m_TraitSet;
};

class BaseTile
{
public:
   virtual TileTraits getTraits() const;
};

class LadderTile : public BaseTile
{
public:
   TileTraits getTraits() const { 
      return TileTraits( TileTraits::Walkable | TileTraits::Climbable); 
    }
};

      

+2


source


Well, if it's about a bunch of functions is*()

, you can go for something like a function isIt(what)

, returning oh no!

a default implementation that will be used as a fallback in derived classes.

+1


source


Perhaps you should look at component based objects. Here's an example: http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/

+1


source







All Articles