Check for intersection between many missles and enemy? - java

I want to create a class lets say called enemy 1, enemy 2, and enemy 3.
Enemy 1: Very easy to kill, but many.
Enemy 2: Harder to kill, but less of them.
Enemy 3: Boss, super hard to kill, only one.
Lets say that many is going to be 1,000. Less of them will be 100. Boss is of course one.
So it would be stupid to make 1,101 different instances for a game of just enemy. It would require to much code.
Now my fighter, which is sick, can fire a lot of missiles. Lets say 2,000 a minute for the sake of fun.
I need to check for collisions between the enemy and all the missiles. I plan only using 4 different instances. Which would be enemy1, enemy2, enemy3, and a missile.
Any ideas on how to go about this? Obviously I would need threads, but I am not sure how to check for collisions in this instance.

If you've got 1101 enemies wandering around the place then each of them will have their location, their damage, their ammo stock and so on, so you will need 1101 instances. You only need four classes. Then you create a whole array of instances of each class.
You also need an instance for every missile.
Collisions? Well, are you planning on using some 3d graphics gaming library for this? It'll probably handle collision detection. Or are your enemies all spheres? You need geometry...

So it would be stupid to make 1,101 different instances for a game of just enemy. It would require to much code.
Not at all. You may be confusing class with instance because you will in fact have to create 1,101 instances of these objects, but will only need code for 3 Enemy classes (or 1 class perhaps if you can make how hard it is to kill a property of the class). Likely you will have a collection, such as an ArrayList of Enemy.
The other answer handles collisions, but likely you will do this part in your model, not in your view code.

Related

I never know when to make new classes or what to make classes for when I create a new project, and I struggle with organizing my code

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.

Whats the best way to do attack collision in libGDX/Box2D?

I'm trying to make rogue-like game. Now i'm using Box2D to detect collisions with enemies (so i can destroy them when i collide with them), but i don't have any idea how to handle player's attack. I need to attack outside of my box2D player's body, i tried to create sensor's bodies when i'm attacking, but it didnt work for me (
Any suggestions about it ?
p.s sorry for my Indiano english ;D
You can either add/remove Sensor fixtures every time you attack or use Ray-Casting. I use both, depending on the dynamics of the attack (a dagger stab for example could be as simple as one ray-cast ray). I did quite a lot of research on this since I thought it would be ti heavy to add/remove things every time an attack occurs but there is no other feasible way with Box2D.

How Do I Implement SRP Across A Few Classes?

My friend and I are working on a game. Right now the game is very simple but we want to understand how we would go about implementing the Single Responsibility Principle between three objects. We have player, enemy, and bullet classes.
The player and enemy both need to be able attack and move, while the
bullet only needs to be able to move.
They all need to be able to collide with one another.
The player moves and attacks based on user input
The enemy moves and attacks based on predetermined attack patterns.
We're really really struggling with the class structure and how to organize the code - we were debating using objects that just hold state and then big controller classes that each do one thing (manage collisions, manage attacking, etc.). Could someone please provide a suggested architecture that follows SRP?
Thank you!

Destroying multiple references to the same object in Java

Say I have a Citizen class and a Population class. A population contains a set of citizens.
In this simulation, citizens may die. Currently, to represent the death of a citizen, I destroy all references to that citizen object, as a Population may not contain a dead citizen.
I want to be able to create multiple Population objects where citizen overlap is possible. Ex. Citizen C may belong to both Population A and Population B. However, this makes citizen deaths difficult as I would have to remove citizen C from both A and B on the event of a death. Sometimes A and B aren't even in the same scope.
Also, each citizen must belong to at least one population.
Generally speaking, how would I organize my Population and Citizen class to ensure that a citizen is completely removed from all instances of Population upon that citizen's death?
I'm thinking of making Citizen a member class of Population, but I do not know where to go from there.
Thanks.
If you think of it as a real life scenario, if a citizen belongs to few populations, then in case of death those populations need to be informed (lets say, if he is French and American, both countries need to know that to cancel his passport etc.). So the observer pattern here, as #nablex suggested, sounds like the most appropriate solution.
Have a class, like 'MinistryOfDeath' or something, that will inform the relevant populations.
There are a number of solutions to this problem like observer pattern etc but if having a reverse link from citizen to population is already considered too heavy, any solution in that direction is probably too heavy weight.
If you really don't want a reverse link (though probably the best option and memory probably won't suffer that badly), you can always have an isDead() on the citizen.
Any population must then either periodically or upon access prune the dead citizens.
When compared to List<Population, an int[] with numbering all the populations would save half the memory only on machines with above something like 32 GB, where compressed OOPs don't get suffice, otherwise nothing.
Using a short[] saves half the memory when compared to int[]. Using a BitSet saves much more. You could even run your own, e.g., 2 longs for a fixed set of 128 populations and use only 16 bytes per Citizen. This is much much cheaper than the forward links from Populations to Citizens.

OO vs Simplicity when it comes to user interaction

As a project over summer while I have some downtime from Uni I am going to build a monopoly game. This question is more about the general idea of the problem however, rather than the specific task I'm trying to carry out.
I decided to build this with a bottom up approach, creating just movement around a forty space board and then moving on to interaction with spaces. I realised that I was quite unsure of the best way of proceeding with this and I am torn between two design ideas:
Giving every space its own object, all sub-classes of a Space object so the interaction can be defined by the space object itself. I could do this by implementing different land() methods for each type of space.
Only giving the Properties and Utilities (as each property has unique features) objects and creating methods for dealing with the buying/renting etc in the main class of the program (or Board as I'm calling it). Spaces like go and super tax could be implemented by a small set of conditionals checking to see if player is on a special space.
Option 1 is obviously the OO (and I feel the correct) way of doing things but I'd like to only have to handle user interaction from the programs main class. In other words, I don't want the space objects to be interacting with the player.
Why? Errr. A lot of the coding I've done thus far has had this simplicity but I'm not sure if this is a pipe dream or not for larger projects. Should I really be handling user interaction in an entirely separate class?
As you can see I am quite confused about this situation. Is there some way round this? And, does anyone have any advice on practical OO design that could help in general?
EDIT: Just like to note that I feel I lost a little focus on this question. I am interested in the general methodology of combining OO and any external action(command line, networking, GUI, file management etc) really.
In the end, it is up to you. That is the beauty of OO, in that it is subject to interpretation. There are some patterns that should usually be adhered to, but in general it is your decision how to approach it.
However, you should carefully consider what each actor in the system should know about the rest of it. Should a property really know about the player, his account balance, and the other players? Probably not. A property should know what it costs, how much its rent is, etc.
On the other hand, should the main playing thread be concerned about trivial matters such as paying rent? Probably not. Its main concern should be the state of the game itself, such as dice rolling, whether each player wants to trade or buy or unmortgage/mortgage, things like that.
Think for a moment about the action of landing on a square. Once landed, the player has 3 options:
Buy the property
Ignore the property
Pay rent
Now, which actor in the system knows all the information required to complete that. We have the Game class, which isn't concerned with such tedium. We have the Property, which doesn't really care about the players. But the Player object knows all this information. It keeps a record of what each player owns, and can easily access the proper data.
So, if it were me, I would make a Player.performMove(Die d) method. It has easy access to the accounts. This also allows for the least coupling among classes.
But in the end, it's up to you. I'm sure people have created Monopoly clones in perfect OO, as well as Functional or Procedural languages too. In the end, use what you know and keep refactoring until you're happy with the end design.
I agree option #1 seems better.
As for "user interaction" - it all depends. You could leave some of your code in another class. For example,
// in main class
user.landOn(space);
if (space.containsProperties()) doSomething(); // Option #1 for some user-interaction code
// in User.java
public void landOn(Space s) {
// do some checks
s.land(this);
if (s.containsProperties()) {...} // Option #2
// something else?
}
// in GetMoneySpace.java
#Override
public void land(User u) {
u.awardCash(200);
// Option #3 - no properties so nothing here
}
This is far more OOP-y (and better, in my opinion) than something like
if (space.isCashAwardSpace()) {
user.awardCash(space.getAward());
}
if (user.something()) doSomething(); // Some user-interaction code
I am not entirely sure if I understand it correctly. You have always such choice when designing software. I would personally go for the first choice. One argument is personal experience with small games (Scrabble), which prooved to me that good design matters for smaller projects as well. The point of OOP is that you can think differently about your design and you get some design benefits. For example imagine how hard it will be to add new field, change existing one, reuse behaviour of one field in multiple fields.
Your first approach is the one I'd go for. It encapsulates the behaviour where it's needed. So, you'd have Space subclasses for Utilities, Properties, GotoJail, FreeParking - basically all the different cateogires of spaces. What groups a category is it's common behaviour.
Your properties spaces may themselves have a group object as a member, e.g. to group all the dark blue properties together.
As to interaction with the user, you pass a Board (or better a GameController) instance to each space, so it knows which Game it is part of and can influence the game. The Space can then invoke specific actions on the board, such as, moving a piece, asking the user a question etc. The main point is that there is separation - the user interaction is not happening inside each Space - but the space is allowed to request that some interaction happens, or that a piece is moved. It's up to your GameController to actually do the interaction or move pieces etc. This separation makes it easy to test, and also provide alternative implementations as the need may arise (E.g. different game rules in different editions/countries?)
Go with the first design. You'd have a Property class, and subclass the special properties, overriding the default behavior.
As far as interaction, you could have a Token class, and move an instance of that around the board. You have to give the user some options, but yes, from the responses, you should be calling methods on objects, not putting complex logic in the user events.
Sample classes:
Property
name
price
baseRent
houseCount
hotelCount
mortgaged
getCurrentRent()
RailRoad extends Property
Utility extends Property
Board
properties
User
token
playerName
currentProperty
ownedProperties
buyProperty()
payRentOnProperty()
mortgageProperty()
move()
Option 2 doesn't make much sense, or at least it's not as clear to me as option 1. With option 1 you don't need to handle user interaction inside your space object. You could have in your main class or a separate class dedicated to handle user interaction:
public void move(Player p, int spaces){
Space landingSpace = board.getLandingSpace(p,spaces);
landingSpace.land(p); //apply your logic here
}
As you can see, the Space class is responsible for checking the Player p that intends to land on that space. It applies any custom logic, checks if it has enough money, if it's something that the player owns, etc. Each subclass of Space will have its own set of rules, as you described in option 1.
Part of the point of object-oriented design is to simplify the representation of the problem within the solution space (i.e., modeling the system in the computer). In this case, consider the relationships between objects. Is there enough functionality in a Space to warrant abstracting that into a class, or does it make more sense for there to be discrete Property and Utility classes unrelated to Space because of the unique features of both? Is a Property a special kind of Space, or merely a field within Space? These are the kinds of problems you probably will need to grapple with in designing the game.
As far as interaction, it's generally bad news for a design when you have a 'god class' that does all the work and merely asks the other classes for information. There are plenty of ways to fall into this trap; one way to determine whether you are dealing with a god class is to look for a class name including Manager or System. Thus, it's probably not the best idea to have some sort of "game manager" that asks all the other objects for data, makes all the changes, and keeps track of everything. Eliminate these as much as possible.
God classes violate the concept of encapsulation, which involves more than data hiding (though that's certainly a big part of it). Good encapsulation means that related methods and data are part of a single object. For example, a Property doesn't need to make requests of its owner, so a field containing a reference to the Player could violate encapsulation. Some of these encapsulation violations aren't obvious at all, and can be hard to spot. When designing the object, try to determine the smallest amount of information about the object that needs to be shared with external objects. Trim out anything unnecessary.
You can obviously go about this in a lot of ways, but my design would be something like this (iteration could certainly prove it wrong):
Space class that contains basic data and methods that are common to all spaces (such as their position on the board, occupied or not, etc.).
Subclasses moving from most common (Property and Utility) to most unique (Go, Jail, FreeParking, and so on; probably singletons) with fields and methods related to each.
Player class to contain player information.
GameState class that is concerned with game state; whose turn it is, how many houses are left in the bank, and so on.
Good luck with the game and your continued studies.
Naturally, Google is your friend, but here's a sampling of things I would recommend reading:
ATM simulation (this idea is
also discussed in Rebecca
Wirfs-Brock's book below)
Object-Oriented Design Heuristics - Arthur Riel
How Designs Differ (PDF), Designing Object-Oriented Software - Rebecca Wirfs-Brock

Categories