Pergunta

I am making a game in C++ using SFML (although that doesn't matter) and am struggling to come up with a good design. Right now I have a game class that holds level objects. When you click a button in the level, it needs to change the current game level. The only way I can figure is to pass a pointer of the game and store it in each level so I can call functions from within the level, but this seems like extremely bad structure and organization. Is this bad or not and what might be a better structure to use instead?

Here is the game class:

    #include "SFML/Graphics.hpp"
    #include "mainMenu.h"
    #include "levelMenu.h"
    class Level;

    class Game {
    public:
       Game() { mainMenu = MainMenu(this); }
       void input();
       void setLevel(Level* level);
       LevelMenu& getLevelMenu() { return levelMenu; }
    private:
       Level* currLevel;
       MainMenu mainMenu;
       LevelMenu levelMenu;
    };

And in my mainMenu class I want to make the game class's current class change to levelMenu:

    #include "game.h"

    class MainMenu {
    public:
       MainMenu(Game* game) { this->game = game; }
       void input(sf::Event event) {
          if (event.type == sf::Event::MouseButtonReleased) {
             game->setLevel(game->getLevelMenu());
          }
       }
    private:
       Game* game;
    };
Foi útil?

Solução

I think that looks decent, just some general suggestions:

  • An abstract base class Menu that handles the Game-variable for you.
  • Learn to use references and shared pointers of various types.
  • Keep interface, game mechanics and objects fairly seperate, look up the basics of MVC, model view controller.

I'd suggest that you don't worry too much about design like this, it's highly likely that you will realize that your design doesn't work or is suboptimal down the line after building the rest of the game, and then you can rewrite it at that point having learnt a lot more when building the other subsystems.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top