Shane
Shane

Reputation: 313

Is it better to encapsulate UI or pass a pointer to the UI around in QT Creator?

I'm working on a project where I have to GUI-ify a text based game like ZORK. The objective of the project is to learn C++ and event driven programming, whether the game is good or not doesn't matter. We have been given the skeleton of the game code.

So I have a UI class GameWindow and a class that has the game logic in it. I want the game logic class to write some text to the UI from within the class. Is it good design to have the UI public and pass around a UI object to have direct access to the labels on the screen (doesn't this break encapsulation?):

ui->welcomeText->setText("Welcome to the land of the text adventure!");

OR is it better to have lots of getters and setters for a private UI object where you take an object of the gamewindow class and just say:

gamewindow.setWelcomeText("Welcome to the land of the text adventure!");

I'm really new to C++ and in the design stage and I dont want to screw up early on and create more work for myself. Some guidance on this would be appreciated.

Upvotes: 0

Views: 704

Answers (2)

Thomas
Thomas

Reputation: 5138

Seperating UI and Worker is good practice. There are several approaches you can use.

You can use a signal slot communication between game and ui. see boost::signals. If you use Qt then you can also use their signal slot mechanism.

You can use callbacks.

You can use a Java like listeners and events.

class GameEvent{}
class GameListener{
    void event( GameEvent const& );
};
class Game{
    void addListenter( GameListener* );
    void removeListenter( GameListener* );
};

You can pass an interface into the game engine.

class Game {
   void setUI( GameUI & );
}

Upvotes: 1

Zaiborg
Zaiborg

Reputation: 2522

it's allways good to seperate the ui from the workers into different threads. in qt its easy cause you can use the slot/signal concept.

Upvotes: 0

Related Questions