Question

I am trying to program a Battleship game with different states depending on user input. I am implementing the State Design Pattern for the different types of game types, the instructions panel and other features it is going to have. My question is, when I make the JFrame for my game, should the logic be invoked during construction, or should it be during the update of the window?

For example:

public class BattleshipGui extends JFrame
{
  public BattleshipGui()
  {
    initizalizeFrame();
    executeLogic();
  }
}

The execute logic contains the game loop that changes according to the game events.

Was it helpful?

Solution

The GUI should only be responsible for rendering. All actual game logic should be handled on your main thread, while the EDT is painting for you (repaint posts events to the EDT). As for "invokingGameLogic", this should first never be done in the constructor (considering that method contains the loop thats updating your game). You should initFrame then start your loop dedicated to updating/rendering your game. Create an interface between updating and rendering; have variables that both rendering code and updating code can access. That way, your render code renders whatever the current state is, while update code changes it.

class Game extends Canvas {
    //the items used between render and update
    Player player;
    Enemy player;

    //render values
    public void paint(Graphics g) {
        super.paint(g);

        g.setColor(Color.BLUE);
        g.fillRect(player.x, player.y, 50, 50);

        g.setColor(Color.RED);
        g.fillRect(enemy.x, enemy.y, 50, 50);
    }

    //affect values
    public void update() {
         player.x++;
    }
}

Keep your game logic away from your rendering. It makes programming a game easier, since you'll be able to easily find code that handles graphics, and what code handles moving players and what not.

If you are using Component#paint(Graphics), then you REALLY want to seperate the game logic from rendering. Code within the paint method executes om the Event Dispatch Thread, meaning issues with updating will cause very apparent issues in GUI.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top