mardi 6 septembre 2016

instantiate draft (i.e. prototype) of an object (e.g. turret) from factory without duplicating code

By depicting it with a game, it will make the problem most describable.

In a tower-defense game that the player can build many types of turret, here is a code of turret factory :-

Entity* createTurret(EnumTurretType turretType){
    Entity* turret = ...;
    switch(turretType){
        case FIRE_TURRET:{
            GraphicObject* fireCG=graphicFactory()->create(FIRE);
            //.... initialize a few mesh, and a few physic solid objects
            turret->attachComponent(GraphicObject);
        }break;
        case ICE_TURRET:{
            //......
        }break;
        //.... 20-30 types
    }
    return turret;
}

Everything is good so far. Game is playable, and everyone is happy.

Now it is the step to let players build turret by using mouse, and it would be cool if the player can see silhouette (e.g. fade hologram) of turret while the mouse is moving around.

Question: How should it be implemented without duplicating the code?



My poor approaches

1. Create a real turret, then move the turret along with mouse

The turret will function like the real one, crash with other turret and shoot - even it is just a prototype that is dragging around by the player.

An alleviation is to create a magic flag that make the turret as "prototyped" (aka. disabled).

This cure have to propagate among many game logic part - to check whether a certain turret was disable or not .... whether a bullet is collide with a "disabled" turret ... so on.

It is tedious, induces bug, and reduce code readability and a bit of maintainability.

2. Duplicate the above code, then remove non-relate stuff

Copy-paste only Graphic's part. If there is any graphic that is related to game-logic, it have to be re-hardcoded in graphic style. For example :-

//pseudo-code
Physical gun will be 3 meter above the turret's base;
Draw graphical gun at the physical gun position;

... must be converted to ...

A graphical gun will be 3 meter above the turret's base;    

I have to do it for every type of turret, and when turret's design change, I will have to update the other one too.

It will cause maintainability problem.

Aucun commentaire:

Enregistrer un commentaire