Separate logic and GUI in Java
I am implementing a game in Java, using the classes shown below to control the game logic When I explain my problem, I will be very clear
> GamePanel
>I use this class to start a threaded game loop (only game loop)
public void run() { init(); //initialize gamePanel components // game loop while (running) { start = System.nanoTime(); gameManager.update(); KeyInput.update(); MouseInput.update(); gameManager.draw(graphic); Graphics g2 = getGraphics(); g2.drawImage(image,null); g2.dispose(); elapsed = System.nanoTime() - start; wait = targetTime - elapsed / 1000000; if (wait < 0) wait = 5; try { Thread.sleep(wait); } catch (Exception e) { e.printStackTrace(); } }
> GameManager
>I control this class in every aspect of the game (updates, graphics)
private void loadState(int state) { if (state == States.MENU.getValue()) gameState = new Menu(this); else if (state == States.GAME.getValue()) gameState = new Game(this); else if (state == States.PATHSELECT.getValue()) gameState = new SelectPath(this); } public void update() { if (gameState != null) gameState.update(); } public void draw(java.awt.Graphics2D graphic) { if (gameState != null) gameState.draw(graphic); else { JOptionPane.showMessageDialog(null,JOptionPane.ERROR_MESSAGE); } }
>Games
>Gamestate is an abstract class that receives gamemanager instances as constructor parameters, and implements abstract methods in each gamestate (menu, game, multiplayer, etc.). > This class has these abstract methods:
>Controller() – > verify state logic > update() – > when currentstate is multyplayer, this method calls the update method of class player... > Draw (graphics g) – > draw to display the object in the current state
I think of an implementation class that implements all draw () of each state individually, but it's annoying to insert them all into a class
Example:
Instead of calling gamestate Draw; I call render getRenderInstance(). draw(graphic,gameState); This solution works, but I don't like it
So how do you separate the draw method from the rest of the logic?
Some advice? thank you.
Solution
The usual approach is to divide the game into two parts:
>Logic, in your case, it seems that you can do > scenes and draw things
Here is how I do the pseudo code:
the main loop: gamestate.update() scene.render();
You should have all the graphic operations on site You should be able to add new shapes to your scene using calls like this:
scene.addObject(SomeGraphic graphic);
Therefore, the scene will render the graph for each main loop iteration
To achieve this, you should keep a list or another collection in the scene class and burn each object together So the actual scene Render () will look like this:
public void render() { for(SomeGraphic graphic : objects) { graphic.draw() } }
You will be able to control the content of the scene from the game logic – you can add and delete objects, etc