Search code examples
javaoptimizationgraphicsgame-loop

Avoiding unnecessary checks


I have a game that has two modes: timed limited and stock limited (kinda like smash bros). In my game loop, a method called renderGame() is called which updates moving objects display coordinates and then calls repaint().

@Override
public synchronized void paint(Graphics g) {
   super.paintComponent(g);

   Graphics2D g2d = (Graphics2D) g;

 //Background Image
   g2d.drawImage( displayBackground, 0, 0, null );

 //Stage Image
   g2d.drawImage( displayMap, 0, 0, null );

 //Players Images
   for( Player p: players ){
      if( p.getPlayerNumber() == 1 )
         g2d.drawImage( displayMario, p1XDisplayCoord, p1YDisplayCoord, null);
      else
         g2d.drawImage( displayLuigi, p2XDisplayCoord, p2YDisplayCoord, null);
    }

 //Not implemented yet  
   drawHUD( g2d );

   g2d.dispose();
}

My question is: how can I make it so that the drawHUD() method will draw different things based on the current progression within the match without having to test for the conditions that define that state every time I call renderGame() in my game loop? Kinda like a railway switch.

For example: It should draw a 'ready-set-go' sequence during startup, player stats during gameplay, and it should indicate a match winner once the match has ended. It should also be game type dependent. ex: display a timer that will increment during a stock match, but decrement during a timed match.


Solution

  • Big issues:

    • You're overriding paint and yet calling the super.paintComponent -- that is a very dangerous thing to do. Instead paintComponent and call the same super's method.
    • You're disposing of a Graphics object given to you by the JVM, another very dangerous thing to do since it completely breaks the graphics chain. Don't do this, but instead only dispose of a Graphics object that you yourself create.
    • Swing is single threaded and so there's no reason to synchronize paint or paintComponent, and risk if you do.

    Re:

    My question is: how can I make it so that the drawHUD() method will draw different things based on the current progression within the match without having to test for the conditions that define that state every time I call renderGame() in my game loop? Kinda like a railway switch.

    Most state checks shouldn't be expensive, but if any are, you can use a boolean switch of some kind that is set if the state changes, which the painting method can test and then reset.