M. Simon M. Simon - 3 months ago 31
Java Question

JavaFX game OOP model

I would like to ask for recommendations or links to this kind of info on how should I model my program in JavaFX - it's a very simple game and I'm not using FXML in it.

Thing I can't really grasp is how should I model it. I mean stick it all inside class with

start
method and do only simple objects outside..

thanks for help

Answer

Depending on complexity the models will be different. Since you state that it's a simple game, you can do basic responsibility separation, akin to MVC (classes can be renamed to fit your needs):

GameLogic (Model). This is a pure logical representation of your game. It keeps your game objects, rules, data and access to submodules, e.g. audio, AI, physics.

GameView (View). This is a pure graphical representation of your game. It doesn't do anything apart from displaying your game to the user and possibly capturing input from the user. You can either redraw the game view on every frame manually or use the scene graph and bindings to do the drawing for you.

GameActions (Controller). Generally, this contains a mapping from user input to the game action, i.e. how user input affects GameLogic. In essence this is like a map data structure:

actions.put(KeyCode.ESCAPE, game::openMenu);

Application class is nothing more than just an entry point to your game. So the code will be minimal. Something along these lines:

public void start(Stage stage) {
    Game game = new Game();
    game.attachView(new GameView(stage));
    game.start();
}

While this design suits simple games, for a more complex game, you would need to separate the game framework from the game itself.

Comments