I am trying to write code to make a simple game.
Assuming that there is a class called Level in which it manages the functionalities for the level.
For example, there are some methods like spawnHero() and spawnEnemies(), start(), finish() and etc in the class.
if I put a private String method called PrettyTimeFormat that converts the game duration time into a nicely arranged format and uses it in the finish() method, would this violate the SRP?
If so, should I make a class called TimeManager and put the PrettyTimeformat method in that class in order to avoid SRP?
It looks like you are missing a Game object. Game has Level, Hero, Enemies, and GameTime. Game can be start()-ed and finish()-ed.
When you architect the solution think about real objects. Objects exist in real life, are living things that do real things and don't create objects that end with -er.
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.
So basically my question is the same as this one:
Card game with huge amount of cards and complex actions
But I don't "speak or understand a word" of C++.
It's my very first big java project and I want to implement a Trading Card Game component.
My problem is: I plan on using 100+ different cards, with different actions. There'll be 4 main types. Within those types, the card's actions are similar but still different.
I thought about making an extra class like
public class CardActionDatabase {
public void card1Action(){}
public void card2Action(){}
....
}
But the problem is, I can't invoke/call them within the actual code like
(playedcard.getName())Action()
since that's impossible in a compiled language.
So basically I'd have to "if" the recent played card with all existing ones, which would be inefficient.
How can I accomplish this?
I've been messing around with card games myself, and there are a few options here. A simple way to do it (though perhaps not the most efficient) is thusly:
First, create an abstract class Card that contains common variables and methods, such as String name and public void onPlay(). Then you might make another abstract subclass for each of your four types.
Then, create subclasses of Card for each unique card in your game. These subclasses define onPlay() in their own way. Then in your player turn logic, when a player chooses a card, that card's onPlay method is called. You can even add stuff like onDiscard, onDestroy, or onTurnStart.
You might also consider creating controller classes between the "Cards" and the "Field/Play Area". For example, you might have a HandController class that has public methods DiscardRandom(), Discard(int index) and Draw() which the Cards can use to manipulate the gameplay as they should.
It can become troublesome and complex to manage the chain of calls needed to perform actions appropriately, but strong documentation goes a long way.
I am currently creating a dungeon crawler. I handle all of the dungeon generation, collision box generation, treasures and enemy generation, and player generation in one class called Dungeon. Each of the objects created in the dungeon class has a getter.
In the Main class, I am using an animation timer to handle all of the updates from the player moving, opening treasures, etc. This requires access to many of the objects created in the Dungeon class.
I am trying to better understand the use and benefit of object references in Java. My question is: What is the more efficient method to access the variables in the Dungeon class (or any other class for that matter) since I am accessing them hundreds or thousands of times?
For example, all of the treasures in the dungeon are in an ArrayList variable that is a member variable of the Dungeon class. So, I can retrieve that array list in my Main class like this: dungeon.getTreasureList(). If I need to get a specific item in that ArrayList I could use: dungeon.getTreasureList().get(i) where i is the index of the treasure object I want. This is fine for short calls (organizationally speaking) but it gets really messy with longer calls like so: dungeon.getPlayer().topIntersects(dungeon.getCollisions().getWalls())
Alternatively, I could create a reference to the treasureList in my Main like this: ArrayList<Treasure> treasure = dungeon.getTreasureList(). Then, if I need a specific object in the ArrayList I can call: treasure.get(i). This can clean up the long call above to something more like this: player.topIntersects(collisions.getWalls());. This is much easier to read and, as a result, I favor this method a bit more.
Disregarding the organizational benefits, is it a better practice to create a reference to access a variable to access information, or use the longer form and getters (like thisdungeon.getTreasureList().get(i))?
It would seem, that by creating a reference for player and collisions in the call dungeon.getPlayer().topIntersects(dungeon.getCollisions().getWalls()) I am saving two function calls by using player.topIntersects(collisions.getWalls());. Namely, one function call to dungeon.getPlayer()and one call to dungeon.getCollisions().
Since this is being called thousands of times while the game is running, it seems safe to assume I am saving many thousand function calls to dungeon.getPlayer()and dungeon.getCollisions(), resulting in a more efficient code. Am I right in this assumption?
EDIT: Trying to make the question more objective and less opinion based and corrected misleading phrasing
My opinion is that this question will be closed soon, because it's too opinion-based.
But if I did offer my opinion I'd say that letting classes access private collections and then operating with them is poor encapsulation.
Better to hide those details and provide methods to give the information you want without giving away the private details.
I know it's not efficient, but I don't really know why.
Most of the time, when you implement your game you got a main class which has a loop and updates every frame and creates certain objects.
My question is why it's not considered efficient to pass the main class to every object in its constructor?
In my case, I developed my game in Java for Android, using LibGDX.
Thank you!
It increases coupling (how much objects depend on each other) and therefore reduces re-usability and has the tenancy to produce 'spaghetti code'. I don't really understand what you mean by not being 'efficient', but this is why you shouldn't do it.
You should also consider why you need that main class in every single object. If you really think you do, you might need to reconsider your system design. Would you mind elaborating on why you think you need it?
Mostly, it is a matter of coupling the code and making proper design decisions.
You should avoid dependencies between classes whenever possible. It makes the code easily maintainable and the whole design clearer.
Consider the case: you are creating a simulation racing game. You have a few classes for such entities: wheel, engine, gearshift knob, etc... and non-entities: level, player...
Let's say, you have some main point (i.e. GameEngine class where you create instances).
According to you're approach you want to pass GameEngine's instance in entities constructors (or related mutator methods). It's not the best idea.
You really want to allow wheels or breaks to have the knowledge about the rest of the world (such as player's informations, scores, level etc.) and give them access to it's public interface methods?
All classes should have at small level of responsibility (and knowledge about other items) as possible.
If you really need reference to some kind of main point object in you're classes consider using dependency injection tools, such as Dagger.
It won't make you're game design better, but, at least, forces you to favor composition over inheritance - what leads to create better code.
It's not entirely inefficient, since (afiak in the general case) passing a reference to a method is quite cheap when you consider the number of JVM opcodes required, however, a possibly more efficient way of doing this would be to make a static instance of the game class and access that static field from the other classes. You would have to test these two options yourself.
In addition, passing a reference to the methods could make maintaining the code harder, as you have ultimately added a dependency.
I'm part of a team designing the server for a client/server model naval warfare video game (University course). We have a fairly concrete (well, I think) system design, but there is one aspect that bothers me.
The basic layout of the system is:
Server [thread] (handles incoming connections)
|
Game [thread] (deals with game events in it's work queue and sending messages to clients)
|--Environment (holds environment variables, deals with collision)
|--Client(s) [thread] (handles incoming messages from client sockets and adds events to the Game's work queue)
|--Ship (holds game data, eg: hit points, fire power, etc)
|--Parser (parses client messages and creates game event objects)
|--GameEvent (event objects held in a queue that can preform appropriate work and send appropriate responses to clients)
Now, my issue is that both Client and GameEvent (and probably Environment, once we get to it) need a reference to the Game object that they belong to.
Clients need to add GameEvent's to the Game's work queue.
GameEvent's need to access other game data (other Client's Ships, Environment).
Is there a better/more conventional method instead of having these objects store a local reference to their Game? What about declaring all of Game's methods as static? We only need to handle one game at a time, so there wouldn't ever be more than one instance of Game...
I'm sure there is a convention for a system with one central object that has many helper objects that need to reference it.
Did you consider using a Dependency Injection framework like Guice? There you have config classes called "modules", where you bind your interface Game to an implementation (you can decide if you want a singleton or new instances). A Client class would look like
public class Client {
private final Game game;
#Inject
public Client(Game game) {
this.game = game;
}
...
}
You can construct this class as usual, providing a Game instance (e.g. for testing, using a mock Game class). But if you let Guice create this instance for you (which doesn't need to be directly, it works as well if another class injects Client), you get automatically the instance specified in your Guice module.
I know it takes some time to wrap your head around that concept, but I can confirm that this leads to cleaner, more flexible code.
If there's really only logically ever one instance, you can use a singleton. The canonical form of a singleton is:
public enum Singleton {
INSTANCE;
// fields and methods here
}
That way, you don't have to shoehorn everything into static methods (though, if you want to write static methods that reference INSTANCE, that's fine too). Any code that wants to access the singleton just uses Singleton.INSTANCE, and you don't have to pass it around if you don't want to.
Passing the reference around will keep your options open, it can still be a reference to an actual static object. Also the concept of a request context might be useful, an object that holds all references needed to process a single request, and you pass that around.
Check out Inversion of Control (IOC) and containers.
That way, in your Client and GameEvent classes, whenever you need access to the Game, you just do something like:
var game = IoC.Resolve<Game>();
And then use the game instance methods...
I would strongly advise not using a singleton or a static class in your design. There are lots of reasons for this, but the one that will probably affect you most immediately is that it makes things very hard to test. At testing time, there will probably be more than one instance of Game.
A common convention to ameliorate having one big central object with lots of helper objects is to try to avoid one big central object. You note that there are different clients of 'Game' with different needs. Maybe your interface on Game is too wide.
There's nothing wrong with passing references to a constructor and storing them. You should also introduce an interface that will mediate access between your Game and your client and environment objects.