Design: an array of "enemy" objects for game AI - java

I made shoot em up like game.But I have only one ememy which fallows me on screen.But I want to make lots of enemys like each 10 second they will across on screen together 5 or 10 enemys.
ArrayList<Enemies> enemy = new ArrayList<Enemies>();
for (Enemies e : enemy) {
e.draw(g);
}
is it good creating array list and then showing on screen?
And Do I have to make some planing movements thoose enemies in my code ? I want that they vill appear not on same pozition.Like First 5 enemies will come top of screen then the other 5 or 10 enemies will come from left side.. so on.What is best solution for this?
And I have problem where to fullfiel this array like
enemy.add(new Enemies(750,60))
But this doesnt work ((

Use for example a random property and onScreen property. And set them when you show them on the screen.

Yes you can create an ArrayList for enemies, it's a common solution.

You can randomize the starting position ofthe enemies using the Random class. At the point where you create the enemy select Random coordinates for each.
You may want to have each enemy run in its own thread so that they move independent of each other too.

Related

Best way to draw collectibles in a game?

I want my game to draw coins from a sprite and then my main character would be able to pick them up. I'm trying to use array list for this but i have no idea how to implement this feature. Do I make an array list of Sprites I need to draw and then reuse it ? If so , how ?
Or do I use some other function ? I'm a begginer , so sorry if this question seems odd .
I recommend using Libgdx's Array class instead of a Java ArrayList, as it is optimized for game performance.
Create an Array to hold all the active coins.
Array<Sprite> activeCoins = new Array<Sprite>();
Then create a coin pool. A pool is a helper for creating copies of something without causing garbage collection hiccups. You need to make a subclass of Pool to use. It describes how to create a new coin when one is needed.
public class CoinPool extends Pool<Sprite> {
TextureRegion coinTextureRegion;
public CoinPool(TextureRegion coinTextureRegion){
this.coinTextureRegion = coinTextureRegion;
}
protected Sprite newObject(){
return new Sprite(coinTextureRegion);
}
}
Then create an instance of CoinPool to use in your game.
Now whenever you want a new coin, pull one from the pool. It will only instantiate a new one if necessary. Otherwise, it will hand you a recycled one from earlier. And once you get it, set it's position and other parameters wherever you want it. Keep in mind it might still have old values attached to it, so if you are rotating your coins and moving them around or changing color, you'll want to be sure you reset position and rotation, and color.
Sprite newCoin = coinPool.obtain();
newCoin.setPosition(x,y,z); //as desired
newCoin.setRotation(0); //if you are rotating them
newCoin.setColor(Color.WHITE); //if you have been changing their color
activeCoins.add(newCoin); //Add your new coin to the list of active coins
And whenever you are done with a coin (when it has been collected), you need to remove it from the active coins list and return it to the pool:
for (Sprite coin : activeCoins){
boolean grabbed = isCoinGrabbed(coin); //however you want to do this
if (grabbed){
coinGrabbed(); //whatever you want to happen when a coin is grabbed
activeCoins.remove(coin);
coinPool.free(coin); //return it to the pool
}
}
And to draw them, you can just submit all the sprites currently in the activeCoins list to the sprite batch.
I recently designed a game in Java that was a 2D side scrolling role playing game. Part of the game was to walk around and pick up items like swords and armor.
The way that I accomplished loading the sprites to my game was to give a JLabel my image (which was retrieved locally on start of the game) by setting it's icon to the image.
Next I would randomly place my JLabel on the game map. I didn't use an array list, although you could if you had multiple types of swords, or coins, etc.
The array list could contain types of swords (JLabel's with their icon set to a sprite) such as a bronze, silver, and a gold sword.
Once your JLabel('s) is loading to your map you can give them a hit box and if your character moves inside the hit box then remove the JLabel from the map and into the players backpack (or whatever it is, maybe append a coin amount?).

putting multiple objects into a arraylist and draw them

I have just learned to use arraylist so be nice :P .
I wonder how i can put a few objects (like a circle or a square) into the arraylist and draw them out on a jpanel so all of them stay. I know how to draw one thing but i'm trying to make a game and would like to have multiple things drawn at the same time.
All answers appreciated!
I dont femiliar with JPanel and swing but a bsic algorithm will be:
add all the wanted objects to arraylist (or an other data stracture)
Start Loop
for every item on the data stracture - item.Draw
update all locations
return to loop start

Random actions in Java

I'm writing my first own chess game in Java.
My code already works for two players, manually playing from the keyboard, and I would like to expand it to a player against the computer game.
My problem is that I've never dealt with random actions.
The method which is moving a piece on the board, needs to receive 4 inputs:
two integers for the piece location, and two integers for the destination on the board.
Choosing the wrong inputs is OK since the movePiece method already checks if the integers are not out of the board's bounds, that they really reach a piece of the current player's color, that there's a piece in the coordination and its not empty, etc.
But how do I get these 4 integerss randomly? And how do I make them as closest as possible to "real" inputs (so I don't spend a lot of time disqualifying bad inputs)?
Java provides at least two options to generate random values:
http://docs.oracle.com/javase/6/docs/api/java/util/Random.html
http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#random()
E.g. to get random int values bounded by 4:
int x = new Random().nextInt(4);
int y = (int) (Math.random() * 4);
System.out.println(x + " " + y);
>> 2 3
If you really would like to create a computer player who just moves about randomly, I think it would be better to do it it like this:
Randomly select one of the existing chess pieces on the board
Compute all legal destinations to which that chess piece could move
If there are no legal destinations, choose a new piece amongst the previously not selected pieces
Randomly select one of the computed legal destinations
However, letting a computer player move about randomly is rather silly. A computer player would need to have some form of logic to compare which out of two moves is better. Implementing such logic is probably rather complex, and you're probably better off using a chess library as someone suggested in the comments.
You don't need 4 ints. You only need 1.
A way of doing this:
Iterate the pieces on the board.
For each piece, determine its available moves and stick all the available moves in a list.
Pick one move from the list at random (or at non-random, if you feel so-inclined).

Java Collision Detection Not Working

I have made threads in the past about similar questions but because of my lack of detail the answers have not really been related to what I needed so I am going to try explain my question in as much detail as I can and hopefully it will be easier for you to understand what I require.
I watched Bucky's slick game tutorials on youtube and made a 2D Java game, the game is basically a 2D player viewed from above (birds eye view) can move around a 2D map with user key input (up, down, left, right). The map the player moves around is very small so that meant boundaries had to be set so that the player could not walk off of the map, to give you a better idea of how this was done, here is the tutorial for setting up the voundries:
http://www.youtube.com/watch?v=FgGRHId8Fn8
The video will also show you exactly what the game is like.
The problem is, these boundaries only require one axis meaning that if the player is walking down you say something like "if player gets to the coordinate (number) on the X axis change the player movement to the opposite direction so that he can not go any further."
Now this creates a problem for me because this only requires one axis so it easy to set up and understand but if you look on the video, on the map there is a house and I want my player not to be able to walk over that also but this deals with 2 dimensions, I have looked at things like rectangle collisions and have seen things relating to them in the other posts but I get confused because I am new to Java and havent really done much with it at the moment apart from watching Bucky's tutorials.
My code at the moment for my game class has got the following methods: init, render and update. So to sum it up I really just want to set up a way of not letting my player walk through the house, I will mention also (I should have mentioned it in my other threads) as I am very new to Java, could you please take a step by step method of showing me how to set up the collisions, I mean even the basics of things like making the rectangle if required.
If my code is required please tell me and I will post it as soon as possible.
Thank you in advance.
You can set up the board as a 2x2 grid of a class that has has property such as 'isBlocked'. By default the edges of the board would have this property set to true to prevent the character from walking off the edge. When you add other obstacles such as a house or a wall the grid position(s) the object occupies would also have the property set to true. Then when moving a character you just check if the grid position the character moves to has the property set to false to see if it's an allowable move. This also makes it quite trivial to save the level data so you can just load them from disk later on.
Two possible options:
Extend Shape or Rectangle or the relevant Slick objects (they should exist IMO) and just check for intersect()
Look for (x1,y1) and (x2,y2) values such that it starts outside and ends up inside.
Assuming you have intersect() methods:
//Grab the previous position
prevPosX = movingobject.X;
prevPosY = movingobject.Y;
//Update the position
movingobject.update();
//Test for collision
if(movingobject.intersects(targetobj)) {
//If it collided, move it back
movingobject.X = prevPosX;
movingobject.Y = prevPosY;
//And reverse the direction
//(might want to do other stuff - e.g. just stop the object)
movingobject.speed *= -1; //Reverse the speed
}
in this case your update class should also add one more condition to look for the house. let say the cooridnates of house(assuming rectanglular house here for other shape just change x and y values) are (x1,y1)(x1,y2)(x2,y2)(x3,y1) you have to add a condition to make sure
x value is not between x1 and x2 and at the same time y value cannot between y1 and y2.

Randomly Generating Enemies Android

I am making a game in android in which enemies are randomly spawned at the top of the screen and move down. I am able to create 1 enemy that does this, but I can't think of a good way to create many enemies that are all drawn on the same canvas. I have tried many things, and I could really use some help.
Thanks!
The easiest way to do this is to create a class Enemy (name it whatever you like) and instantiate as many as you need using a for loop. You could use an array to store each instance.
An example could be the following:
Enemy[] arrayOfEnemies = new Enemy[sizeOfArray];
for(int i = 0; i < arrayOfEnemies.length; i++) {
arrayOfEnemies[i] = new Enemy();
}
Then you can use an enhanced for (or for each) loop to display them wherever you'd like on your canvas.

Categories