r/javahelp • u/r416alex • Apr 03 '19
How do I structure a 2d Java game?
Is there a proper way to set up the classes, packages, and such, or does everyone figure it out on their own. I've created two small games before, but they seem to be completely different with number of classes being more on the more in-depth game. For example, in my first game, I had the player have an array of his inventory saved to a variable in the player class, but in my other game I had a class called inventory that was an object of the player. It just seems like there are so many different ways of doing things and at times I feel like I'm just throwing things together.
I've learned from my computer science class about interfaces and abstract classes, but I've never once felt the need to use them in my code. One game used just one package with all the classes in there and the other I tried splitting them up into logic, graphics, and internal packages and it worked out just as well albeit with a lot more confusion.
Today I ran into this problem. I have a main game class with the main loop calling an update and a render function that both call functions in other classes. Some of these need to only be called when the game is in a specific state. Should I make a new renderer class and just call that one objects function once and have it deal with deciding the game state or do I put the if else statement and all the functions in the main game class.
Honestly, I feel like I could write an entire simple game in a single class. Are there any resources out there that could help me get better at this?
4
u/User1539 Apr 03 '19
Check out LibGDX. Lots of great examples and the library is really featured.
1
u/r416alex Apr 03 '19
I'm currently working on it now and I'm trying to figure out the best way of doing it. There seems to once again be many ways to go it such as using screens or not.
2
u/james_otter Apr 05 '19
Check the game design patterns book http://www.gameprogrammingpatterns.com maybe start with the components chapter for your question
A lot info about how to structure code to make it flexible and maintainable.
You can read the online version for free.
1
2
7
u/firsthour Profressional developer since 2006 Apr 03 '19
For your inventory example, better to break Inventory off into its own class. Think about this: your game may start with just your player having an inventory, but what if enemies can have an inventory too, or an NPC? Creating a separate class allows your game to grow more organically. This would be true for a lot of systems.