0
\$\begingroup\$

I am currently programming my first game in Java and I'm having trouble structuring it. My biggest concern is regarding the game loop. Currently I have implemented a class with only a main function which first initializes all of the variables and then goes into a game loop. Here is the structure of the code:

public static void main(String args[])

//Initializing all the variables

//Main game loop

while(true)
{
  if (mouse is pressed)
  {
    do something
  }

  if (mouse is released)
  {
    do something
  }
  ......
}

The problem is that the "do something" parts are quite lengthy and my code looks quite messy. I would like to turn them into methods, however I am not really sure how to do it.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ With the level of detail you've shown us here, all we can really suggest is make a DoSomething() method. Can you edit your question to go a bit more into the specifics of what kind of mess you want help cleaning up, and what obstacle you've found to putting related code into their own methods? \$\endgroup\$
    – DMGregory
    May 20, 2021 at 11:08
  • \$\begingroup\$ Should it be a GUI based game? \$\endgroup\$
    – convert
    Feb 14, 2022 at 20:44

1 Answer 1

0
\$\begingroup\$

A common way to break down a long update loop is by creating a separate method for each individual feature of the game. For example:

while(!isGameOver()) {
    updatePlayer();
    updateEnemies();
    updateProjectiles();
    updateUi();
    render();
}

If any method gets too long, consider to break it down into more methods based on the sub-problem they solve. This is called the "Single Responsibility Principle" in software architecture. Every modularization unit (like a method) should be responsible for one single thing. When you can not explain what its responsibility is in one sentence, or if that sentence contains the word "and", then you might want to consider to break it into two.

For example, when the responsibility updatePlayer() would be described as "reads the input state from the controls and applies it to the player", then you might want to consider to break it down like this:

input = readInput();
updatePlayer(input);

And if the responsibilities of updatePlayer(Input input) now would be described as "makes the player walk and jump and shoot based on the current input state", then it could be broken down further like this:

input = readInput();
playerWalk(input);
playerJump(input);
playerShoot(input);
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .