mardi 21 juillet 2015

What is the best way to break circular dependency between GameFlow and Controller in a game?

For example, I want to create a game, which has a GameFlow to control the game event flow, also I have some controllers (e.g.:PlayerAttackController,EnemyControllerController) for different flow.

GameFlow used to switch controllers, controllers notify GameFlow to change state:

to simple the code I don't use .cpp and use public property only:

GameFlow.h

class GameFlow{
public:
    int state;
    IController* controller;
    void changeState(){
        if(controller!=NULL){
            delete controller;
        }
        if(state==0){
            controller=new PlayerAttackController();
            controller->gameFlow=this;
        }else if(state==1){
            controller=new EnemyAttackController();
            controller->gameFlow=this;
        }
        .
        .
        .
    }
};

IController.h

class IController{
};

PlayerAttackController.h

class PlayerAttackController : public IController{
public:
    GameFlow* gameFlow;
    void buttonPressed(){
        //some player attack code
        .
        .
        .
        gameFlow->state=1;
        gameFlow->changeState();
    }
};

(other controllers are similar)

Now it is clear that GameFlow contains Controller, each controller contains GameFlow, is there any method to break the circular dependency between GameFlow and Controller?

Aucun commentaire:

Enregistrer un commentaire