Let's say I'm programming a small RPG game. I have several instances of the Enemy class. They share common properties (they all have a name, an amount of life/strength/dexterity/a weapon, etc), but all these values are different for each enemy. I'm looking for an appropriate way to initiate these instances.
I'm new to programming and Java, so I'm looking for the best practice to properly organize information in my project.
My first idea was, when creating the instance of the game, to instantiate all the occurrences of the required enemies in the constructor of the Game object, and put everything in a vector. Something like Enemy e1 = new Enemy("goblin", 10, 14, 10, a_weapon, ...). But this can get very tedious if there are a lot of enemies, a lot of properties, it gets very hard to maintain, and I don't find very "logical" to put that in the constructor of the Game object.
I just discovered XML files, and it looks promising. So maybe I could put everything in an XML file, and parse it in my program to extract the data and create all the enemies from it. It could look like
<Enemies>
<Enemy>
<Name>"Goblin"</Name>
<Strength>20</Strength>
<Agility>20</Agility>
<Life>20</Life>
<Weapon>
<Name>"Sword"</Name>
<Damage>3</Damage>
</Weapon>
<Enemy>
<Enemy>
...
</Enemy>
</Enemies>
I guess I could write a function that parses the XML file, extract the data and create the vector of enemies automatically, so I just have to edit the XML file to modify the values.
However, and before I dig into this solution, I want to ask if this is the preferred method, and if not, what would be the most common way of managing this kind of situation.
Related
Whenever I start a new java project I always run into the same problem and never ever seem to learn: I never know what to make classes of, and what to put where. I have a hard time organizing my code into different classes.
For instance, I am currently writing a program for an experiment. It involves spaceships, some enemy spaceships and some friendly spaceships, a gun to shoot at them, and so on. I thought about creating a Spaceship class, but then wasn't sure if that should really be two classes (one for enemy spaceships and one for friendly spaceships). But then I was thinking that it should be one class of which friendly and enemy spaceships could be instances of spaceships. However, the enemy and friendly spaceships serve different purposes throughout the experiment, so maybe not. I also know that I need to create JLabels of these spaceships, and don't know if these should be variables of instances of the Spaceship class or if they should be something that are created in the main method. And this goes on an on.
Does anyone have any tips for instantly knowing how code should be organized, what classes should be made of, and so on? Because this never seems to get any easier for me no matter how many programs I write.
The answer for your question depends on how well you understand object oriented concepts.
As per your requirement you need to make Spaceship interface or super class. Make enemy spaceship and friendly spaceship as child class for Spaceship. Similarly you will need to make separate gun class. Depending upon the functionality you need to create object for each. You can make jLabel classes for you spaceships.
Your main method will be in a class which is Entry to your application. You can have different packages depending upon your classes or layers in your application. You should also aware some design pattern before hand for the solution of common problems arising in application development.
I have been coding in java for about a year and a half, and have made some small games and programs that I think turned out very well. The problem is that I am mostly self taught and I most of my code and class structure is not organized or "correctly structured". This didn't matter to me for the smaller things I made, but if I were to take on a larger project I would want to structure it correctly and make it organized.
In a previous mini-RPG game I had
Main Class (Main loop + Main method)
Player Class (containing player position and player stats)
Engine Class (containing map and collision detection between player and map
Map Class (containing map data)
My Main class contained an instance of Player and of Engine, and Engine had an instance of Map. The problem is that Player then could't tell the Engine where it was, and the Engine couldn't adjust Player's position and stats when something happened on the Map. So I ended up having some static variables and methods in both Player and Engine to get them to communicate.
I guess my overall question is is this the correct structure of classes, and is it correct to use static methods and variables here? If not, how would you structure these classes, or would there need to be more or less classes?
My overall objective is to understand how to structure classes in this previous game so I can better structure classes in a bigger project I want to take on.
It is a rather broad question, but the general answer is no.
As a rule you shouldn't use static fields to connect instances. (There are a couple of possible exceptions, but as a rule of thumb it's a useful one.) The basic idea of OOP is that everybody has a reference to whoever they want to send messages to. So if a Player needs to tell the Engine something, it should have a reference to whichever Engine instance it belongs to. Or you can redesign your architecture so only Engine sends messages to Map and Player, it's difficult to tell without more detail about your setup whether that would be appropriate in this case.
Another piece of general advice is to try to sit down with a piece of paper, write down the name of all three of your classes and in a separate column write down all the things the system has to do. And then you should try to figure out who's responsible for what. In a good design this decision is simple, if you find yourself shoehorning different things into one class, that's a sign that you should maybe need a more detailed model with more classes.
I would also suggest you take a look at the observer pattern and the publish-subscribe pattern, as it might be what you need.
Try take take a look at some design-patterns.
Which design pattern you want to use depends on what you prefer. Some can be found here on Wikipedia.
I also take it that you are familiar with OOP? Some more general info can be found here on Wikipedia.
Looking at your specific story, I think a MVC-design would be a nice solution.
MVC meaning Model View Controller.
Here you have your Model, classes holding different forms of data.
Your Controller, controls your Model, contains all the real logic.
And your View, this is the graphic end of your application.
You'd probably want to put and instance of your player in your engine as well. That way your engine will control everything (the player and the map). Hope that helps!
From what you described there a few possible ways to handle this. One would be to use a messaging system. I would look into Java Messaging Service (JMS). Another would be to make your app event drive. Here is a neat little tutorial on how to do this using spring : https://spring.io/guides/gs/messaging-reactor/. Having said that, if your intent is get a better understanding of problem solving using Java, I would first try and mimic these two approaches on your own, without any bulky frameworks.
Im building my own little Opengl Library based on Lwjgl. In the moment im using HashMaps for storing things like render objects, scens or shader programs, because i want to have on Class the user can see, and there create methods to modify, create, i dont know... other objects or classes which are protected.
So, to explain this:
There is a class called "ShaderProgram". But instead to allow the user to create one, with ShaderProgram s = new ShaderProgram(...); , i create a method in my "main class", called "createShaderProgram", give it the params, create a shader program and put it to the hashMap called shaderPrograms, with a name the user decides. for example with MyClass.createShaderProgram("particle_shader", ...) i can create a shader for my particles, and then with MyClass.binShaderProgram("particle_shader") or something like this, i can use it.
BUT: Is this fast enough? Or are there other reasons to change it to int indicies, or, completely allow the user to use all the classes? Because for example im creating the render objects like this, too, and in each frame to do MyClass.getRenderObject("ACube").move(...) ... can i do this? What do you think about this?
Access complexity time for hash table is O(n) in the worst case:
Time Complexity of HashMap methods
So Yes, I would say that if performance accessing your objects collections is so important you should use 1:1 indexed collections like arrays.
This is somewhat of an open question.
I'm in the process of developing a simple game for android and I've gotten to the point where I'm trying to enable thee user to save their progress and return later.
As i'm a beginner, I'm not exactly sure where to start, so I was hoping some of you might have at least some suggestions.
A little info on the setup of the game:
All animation is done in a thread through a canvas and alternation of stored bitmap frames based on a 30 ms loop.
Everything is an object, the characters, the background is simply a 2d array of objects. and each object is generally referenced and created dynamically through a hashmap.
Now how to save? I know I could brute force it, and simply save coordinates and current actions blah blah etc. etc. for each object in each map.
But is there a better way to do this? I've briefly read that in python there's a method of sterilizing objects called "pickle," and there is something similar called "kryo." Am I looking in the right direction?
You should look into Java serialization. It's not perfect, it has problems, but it's the safest, quickest way to turn a complex tree of objects into something that you can save to a file or a db, and load it back when you need.
Else, there's always the possibility to use your own specific serialization using INSERT SQL queries, etc. But be very careful, it's easy to miss parts of what you want to save / restore. One example of that would be to turn your objects tree into XML and save that XML as a file. There are very good 3rd-party libs to map objects to XML and back in Java.
Well.. That's not STERILIZATION, but SERIALIZATION.. Which is a programming technique. And serialization is also the technique you want to use.
Doesn't matter if you use a predefined method or something you write on your own, but the only thing that matters is to loop across the objects and write to the file (or saving structure) the date you need to be later reloaded.
Anyway yes, you're looking the right way.
The best way to do it is implementing a serialization interface. Each object for which the serialize() method is called must save it's data and then call the serialize() method for each child object it owns.
New to OOP, eager to learn good habits.
I want to make a vectorMap class. A vectorMap will have a few properties and contain a number of polyLine objects, which in turn will each will have a few properties and consist of a number of xyPoint objects.
The user will mostly interact with vectorMap objects, but may occasionally want to use polyLine and xyPoint objects outside the context of vectorMap.
Does this mean I should create three separate public classes? Would this mean three separate class modules in VBA, and in Java, three separate .java files?
My procedural gut tells me that it would be untidy to have three separate source code files for three small and simple classes with only a few lines of code each. I'm used to source code files containing packages with many functions. At this rate, a VBA project will contain tens of class modules. But maybe that's just the way it's done in OOP...
The above will be implemented in VBA and Java, so any examples in either/both of these are most welcome.
what do you mean "simple small classes"? My opinion is you should use a fresh file for each class which is testable. if (for instance) XyPoint is just a touple containing 2 elements, it will be a good idea to put it as a subclass of PolyLine.
However, as far as I see it - PolyLine and VectorMap should be in separate files, since you cannot really tell A is important only to B, and both are testable.
also, when using subclasses in java, notice their types (static/non-static,anonymous..) and choose wisely which is preferred.
p.s. a strong convention in Java is that class names start is a capital letters.
p.s.2: I assume this is done for educational purposes, otherwise you should (as #Ingo said) use built in classes, and not to reinvent the wheel...