MESLewis MESLewis - 1 year ago 90
Java Question

How do you structure a java program?

For quite awhile I have been trying to make a simple "game" in Java that is really just an applet with a square and a grid. What I want it to do in the end is the user clicks and the square will move to where the user clicked rounded to the nearest grid square.

The problem is I am a self taught beginner and I am having a hard time figuring out how to actually structure the program, some examples:

  • should I have a separate class listening for mouse clicks?

  • When I receive a click should I send it to some other object that represents the box and let it decide what it wants to do or just call some function that makes the box move?

I really want to learn all this "when to use what" stuff for myself so any links or general advice is appreciated.

Answer Source

What you're really asking is how to develop a game, which is notably different from a typical Java application. However, I'll give you a few ideas to at least point you in the right direction.

  • Take advantage of the fact that Java is an object-oriented language. That is, objects should each have their own responsibility.
  • Separate your game into three key layers: the application layer, the game logic layer, and the presentation layer.

    • The application layer should contain all of your helpers and generic subsystems, things like random number generators, text parsers, file access modules, mesh loaders, etc.
    • The game logic layer should implement all of the rules of your game, and be responsible for maintaining canonical state. Basically, when you press the "W" on the keyboard to move forward, the game logic layer should receive MOVE_FORWARD_REQUEST from the UI.
    • The presentation layer should be responsible for two things: getting input, and rendering your world. When it gets input, like the "W" key, it should map that to an action, and send that to the game logic layer to be processed. Then, it should render the world based on whatever the game logic told it to do.

Game development is obviously an entire realm with many books dedicated to it. One of my favorites is Game Coding Complete, which does focus on C/C++, but should give you a good idea about how you ought to structure your game.

Good luck!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download