putting multiple objects into a arraylist and draw them - java

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

Related

Better way to add and remove Objects in game than ArrayCopy

I’m working on a 2D game and using SurfaceView/Canvas to display my Bitmaps on screen. The Bitmaps are constantly added and removed from the canvas. At the moment I store all the Bitmaps that have to be drawn in an ArrayCopy, so I can add and remove objects although the List is iterated almost permanently. This works fine, but I’m not Sure if there might be a better/faster option. Is there?
If you are using Canvas, you can call their createBufferStrategy() method to obtain a BufferStrategy-object and then you can use that to draw on another buffer then the one that is momentarily displayed. See https://docs.oracle.com/javase/7/docs/api/java/awt/image/BufferStrategy.html for reference.

Making a 2D grid of Sprites

I just finished my first coding class (IB Computer Science, if that helps), and I decided I wanted to make my first game.
The game world I have currently is a top-down view of the terrain. Each part of the terrain is made up of squares (it is very similar to the way Dwarf Fortress looks). I have been able to get it to output to console, using characters for stand-in graphics, but my course covered very little on graphics work.
What is the best way to create a grid of sprites or colored squares inside a JPanel? I have been able to display BufferedImages before, but have not been able to align multiple BufferedImages to get a grid.
As of now, I have an '2D' ArrayList, just an ArrayList of an ArrayList, making up my game world. It all works great when I use a double for loop and System.out.print("");
Check the oracle documentaion for Layout Managers. The one you are looking for is Grid Layout.
If you feel fancy, you can upgrade to JavaFX, and use a Grid Pane instead.

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?).

How can I create a simple graphic display of an array in Java?

Over the past few days, I've coded a (horribly patched together) text RPG game in Java. The positioning in the world is pretty much controlled by a simple 100x100 2D array of Strings. I then convert the Strings into actual objects when the player actually comes upon the grid.
What I have in mind is to have a graphic display showing this 100x100 grid with an image in each section of the grid that corresponds with what is in the array.
For example, if the String at block[10][15] is "rock", the graphic display section of the grid at row 10, column 15 would show a picture of a rock.
Ideally, this graphic would refresh every time I loop in my do-while loop. Oddly, what I have in mind is something that looks remarkably similar to the early pokemon games.
I apologize if my description is badly worded or my question too ambiguous. I have only learned java for half a semester in my computer science course, so my knowledge is limited to the basics we learned in the one semester. I do like to pursue various projects outside of class, like the text chess game that I (proudly) coded. I prefer to create everything from scratch so that I can learn the basics before using various libraries.
Could somebody please point me in the right direction for what I am looking for or offer a better way to go after this display?
Thank you very much in advance. Please let me know if a reference to my code would better help answer my question.
Firstly,you can use enums instead of strings as mentioned by Jack above. Eg
private enum Objects{
Rock(1),Coin(8),Med(45)...and so on
}
In your array, you may store these objects as numbers rather than strings.
eg:
boolean stopFlag=false;
do{
//check each element of your world array with the enum and draw it
for(int i=0;i<yourObjectsArray.length;i++)
{
for(int j=0;j<yourObjectsArray[i].length;j++){
switch(yourObjectsArray[i][j])
{
case Objects.Rock: drawRock(i,j);
break;
case Objects.Coin: drawCoin(i,j);
break;
//and so on....
}
}
}
//you can also put this into a separate function as drawWorld() and pass the objects.
//Key press checking logic here. If user presses exit key [esc] then you set the stopFlag as true
if(keypress==KEY_ESC){ stopFlag=true;}
}while(!stopFlag);
An example of Draw Rock:
private void drawRock(int i,int j){
//i and j are the cols and row values so you need to resolve them to coordinates.
//I am assuming u have a 800*600 screen and you mentioned that your world is 100x100 array. Then each of your object is 8*6 units in size so
xCoord=i*8;
yCoord=j*6;
//So if you have to draw a rock on [10][15] it will resolve as
//xCoord=10*8-> 80
//yCoord=15*6-> 90 so it will draw your rock in (80,90) on the screen
//Now you can either open the rock image from your disk now or u maintain one instance of rock at the beginning of the program so that you can use the same image later rather than opening it everytime you encounter a new Rock object in your array.For now I will open it here.
String path = "C:\\YourGameDirectory\\rock.jpg";
URL url = new File(path).toURI().toURL();
BufferedImage rockImg = ImageIO.read(url);
//draw it to the screen now if you have the graphics instance.
yourUIPanel.getGraphics().drawImage(rockImg,xCoord,yCoord,yourUIPanel);
// You may find many resources that teach you how to draw an image on the screen in Java. You may repeat the same for all the objects.
}
I hope the above codes helped you a-bit. If not,its my bad.
You can try this tutorial series to get started. Although its in C , it has concepts that will help u acheive what you have mentioned above.
Easiest thing to use for such tasks in my personal experience is Processing, which is a light framework which is able to provide a simple API to draw things.
There is a reference, and many tutorials so it shouldn't be that hard to get start with even if you are not expert.
As a side node: why do you use strings to store kinds of blocks? Could you use something better like an enum?
You might want to check out the source code of my old roguelike game Tyrant:
https://github.com/mikera/tyrant
Key ideas:
There is a Map class that is responsible for storing the data that represents the map. In Tyrant, the Map encapsulates storage of both the terrain and the objects places on the map.
There is a MapPanel class that shows the Map in the GUI. This is kept separate from the Map itself - it's generally a good idea to separate the GUI from your core engine data.
There is a Thing class that represents objects on the map. This includes everything from monsters, items, trees and clouds of smoke to the player character itself. Basically anything that isn't terrain.
As for refresh, the way this works is that the MapPanel repaints itself on demand, looking at the contents of the map. Check out MapPanel.paint(Graphics g) and the various methods that it calls.

How can I split up paint swing method in java?

I'm developing a fair sized hospital simulation game in java.
Right now, my pain method is starting to look a little big, and I need a way to split it up into different sections...
I have an idea, but I'm not sure if this is the best way.
It starts by painting the grass, then the hospital building, then any buildings, then people, then any building previews when building. The grass and hospital building will not change, so I only need to paint this once. The buildings themselves won't change very often, only when new ones are built.
I was thinking, use boolean values to determine which sections need repainting?
Ideal, id like to be able to split up the paint method, and then call each one when needed, but I'm unsure how to physically split it up.
I am still quite new to java, and learning on the go.
Thanks in advance.
Rel
Another idea is to create a super class or interface for all items that must be drawn on the screen. Lets cvall this class ScreenObject. You can then have a draw(Graphics2d g) method specified in the ScreenObject class. Next, each object that must be drawn implements the draw() method and is only concerned about drawing itself. You can even consider creating a variable that determines whether this draw method should be run at all.
In the main class that paints the screen you can have a reference to all ScreenObjects in an ArrayList and your paint() method will simply iterate over this calling draw() on each object.
I'm assuming from your description that your scene is split up into tiles. Keeping an array of booleans is a good way to keep track of which tiles need redrawn on the next update. A LinkedList might perform a little better in some situations. (I'm thinking of a Game of Life simulation where there are tons of tiles to redraw and you need to check each neighbor, so you may not need to go this route.)
Without seeing your code I can't give very specific advice on splitting up your paint method. I can tell you that in sprite animations, each sprite object typically has its own draw method that takes the main Graphics object (or more likely a buffer) as a parameter. Since the sprite should know its own image and location, it can then draw itself into the main image. Your paint method can then just loop through your list of sprites that need to be redrawn and call their draw method.
You might look to Killer Game Programming in Java for more detailed information.
Well I am not really an expert at programming but to split up my paint method Ive always just made a new method that takes a Graphics object and call that from paint, it has always helped me to keep my code organized but I have never had a big project like it sounds you are working on so it might not work for your situation.

Categories