How to make sprites in Java possibly using Arrays?

Sorry if this has been asked numerous times, I’m quiet new to java and I don’t know exactly what to search for when it comes to this subject.

But please, if someone could give me a basic example on how to make a sprite using an array. Similar to how they do it on them Java4k Games. There is a game by Notch(Minecraft) where he did a lemming type clone and did something using multiple arrays when it came to animation. But if I start with ‘still’ arrays for now and work from that. I have been trying to learn off source code like notch’s game and other programmers but when I’m copying bits and bobs I get lost and frustrated.

So if anyone could just give me some demo Java Applet/Application code to display, lets say, a smiley face or a green blob if you dont have time

I hope I make sense hear… I really want to have a go at doing sprites the old fashioned way rather than using photoshop and importing images.

Thanks

Well, this question is rather broad and that is why it is so hard to come up with a direct answer for it. The truth is, there is a lot of ways to draw sprites, and a good number of them use an array somewhere in the process.

In Meg4Man, sprites were produced by taking a very small bitmap and stuffing it into the jar. (has pictures)
In Sorcerer4K, sprites are produced using voxels.
In my own game, Ringvibe4K, I used a mixture of the Java2D Graphics classes, arrays, & bit-shifts to come up with every art and font used in the game.

As for writing the code responsible, every game I mentioned has the source code available on the Java4K site. Just a bit of digging and playing around, and you should be able to quickly create sprites in Java4K. (At least, I hope this is what you are trying to achieve this for.)

Thanks for the reply

I checked out your games source ‘Ringvibe’, I must say I’m pretty baffled… There seems to be more maths than methods, this is exactly how I want to learn to program properly other than just external files chucked in using methods and a few keywords if this makes sense… How do you go about learning this kind way of using all this math to create things of the screen? Sorry if this comes across lame but I know what I mean in my head when I’m viewing all the numbers n what not on the source code, normally when you view a game source you just see methods of game/sound java / third party API’s

Please put me in the right direction, here is something I’ve just copied quick but how would I draw this as a sprite…

		private final String[] levels = new String[] {"66111111111111"+
			"36a21111b11111"+
			"00000111000111"+
			"11111711111111"+
			"1111577f11111d"+
			"77770000111110"+
			"1e11000011c110"+
			"10000000000110"+
			"10000000000110"+
			"10000000000110"+
			"10000000000110"+
			"44444444444444",

A couple of people chimed in here on different techniques for J4K:

Although really it depends on the game. Some games need to use images, others are handling everything per-pixel and can make up their own encodings, others might be using g.drawLines everywhere.

Of course, do not attempt this sort of stuff if you’re not building a J4K game.

Well, a sprite, after all, is a collection of color values to be drawn to the screen, so it is easy to store said values as an array.

Maybe these help:



/** Packs Red, Green and Blue values into a single Integer.
 *@param Red Value of the Red component (0-255)
 *@param Green Value of the Green component (0-255)
 *@param Blue Value of the Blue component (0-255)
 *@returns Color value as an Integer
 */
public static int makeRGBValue(int Red, int Green, int Blue)
{
	return (Red << 16) | (Green << 8) | Blue;
}

/**Returns the Red component of an Integer RGB value
 *@param RGB Integer RGB value
 *@returns Color component as an Integer value in the range 0-255
 */
public static int getRED(int RGB) 	{ return (RGB >> 16) & 0xFF; }

/**Returns the Green component of an Integer RGB value
 *@param RGB Integer RGB value
 *@returns Color component as an Integer value in the range 0-255
 */
public static int getGREEN(int RGB) 	{ return (RGB >> 8) & 0xFF; }

/**Returns the Blue component of an Integer RGB value
 *@param RGB Integer RGB value
 *@returns Color component as an Integer value in the range 0-255
 */
public static int getBLUE(int RGB) 	{ return RGB & 0xFF; }


So, a 1-pixel thick 5-pixel wide green square would look something like this:


public final int[] square = new int[]{ 
							0x00FF00,	0x00FF00,	0x00FF00,	0x00FF00,	0x00FF00, 
							0x00FF00,	0x000000,	0x000000,	0x000000,	0x00FF00,
							0x00FF00,	0x000000,	0x000000,	0x000000,	0x00FF00,
							0x00FF00,	0x000000,	0x000000,	0x000000,	0x00FF00,
							0x00FF00,	0x00FF00,	0x00FF00,	0x00FF00,	0x00FF00	};

Afterwards it’s a matter of writing the values into a BufferedImage to be drawn on the screen.

Hope this helps.

Thanks for the replys, I’m starting to understand apart from the last post made - the code looks familiar but how would I put this to action so I can how it works on something like JFrame?

Here is some code I’ve found on another forum, basically it was 1 small moving blue box animated and I’ve added a class section called Spooky to add my own to render/animate with that but I cant seem to make them fit together because of getContentPane and adding them twice if this makes sense, How could I make 2 different shapes move around the screen differently…

I’m getting there slowly but very frustrating, I’m spending hours learning and feels I’m not getting anywhere sometimes. If anyone can help with this code I basically started with adding the Spooky class like I say then went to the top of the code and got stuck on the getContentPane which isn’t allowing me to add 2 lines of that to add 2 of the shapes to animated

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class test extends JFrame {

	public Gunman g = new Gunman();
	public Spooky j = new Spooky();

	public static void main(String[] args) {
		test t = new test();
		t.setSize(800, 600);
		t.setVisible(true);
		t.getContentPane().add(t.g);
		t.setBackground(Color.DARK_GRAY);

		while (true) {
			t.g.x = t.g.x + 1;
			t.g.y = t.g.y + 1;
			t.repaint();
			try {
				Thread.sleep(50);
			} catch (InterruptedException e) {
			}
		}
	}

	public void paintComponent(Graphics g) {
		g.clearRect(0, 0, 800, 600);
	}
}

class Gunman extends JComponent {

	// private static final long serialVersionUID = 1L;
	public int x = 20;
	public int y = 20;
	public int width = 20;
	public int height = 20;

	public void paintComponent(Graphics g) {
		g.setColor(Color.blue);
		g.fillRect(x, y, width, height);
	}
}
	class Spooky extends JComponent {
		public int x = 30;
		public int y = 30;
		public int width = 40;
		public int height = 50;

		public void paintComponent(Graphics g) {
			g.setColor(Color.RED);
			g.fillOval(x, y, width, height);
		}
	}

---- ORIGINAL CODE COPIED FROM ANOTHER FORUM — (HOPEFULLY YOU CAN SEE WHERE IVE GONE WITH IT…

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class Test extends JFrame {

    public Gunman g = new Gunman();

    public static void main( String[] args ) {
        Test t = new Test();
        t.setSize( 800, 600 );
        t.setVisible( true );
        t.getContentPane().add( t.g );

        while ( true ) {
            t.g.x = t.g.x + 1;
            t.g.y = t.g.y + 1;
            t.repaint();
            try {
                Thread.sleep( 100 );
            } catch ( InterruptedException e ) {
            }
        }
    }

    public void paintComponent( Graphics g ) {
        g.clearRect( 0, 0, 800, 600 );
    }
}


class Gunman extends JComponent {

    private static final long serialVersionUID = 1L;
    public int x = 10;
    public int y = 10;
    public int width = 8;
    public int height = 10;

    public void paintComponent( Graphics g ) {
        g.setColor( Color.red );
        g.fillRect( x, y, width, height );
    }
}

Oh don’t use AWT to create your graphics! That’s not a good way to do it… At least use a JFrame and just paint directly to it with g.*

If you’re new to programming, Java4K might be a bit of a challenge. First you might want to get acquainted with general programming and Java2D graphics before jumping right into such a challenging competition. :slight_smile:

Anyways… if you’re still keen… Here is a little template I made for last year:
http://www.java-gaming.org/?action=pastebin&id=321

It includes procedural music and a 3D lambert sphere… Have fun.

EDIT: There are some other old templates in this thread:

Not sure how many of those will still work with today’s JVMs.

EDIT 2:

Also, don’t use any extra classes if you’re writing J4K. Just keep everything in a single method; avoid objects and imports where possible, etc.

here is basically minicraft’s code simplified and explained.

People say it is bad way to do it, but if you’re just starting out, it can give you a pretty cool idea of how stuff works. It is also pretty easy to implement.

Thanks for the replys everyone, I’ve been spending the last few days on these links you’ve gave me and I’m benefiting a lot - this forums ace!

Btw, could someone please help me with my code I’ve pasted above and possibly answer that question, maybe tweak the code and explain how I’d have 2 animated dots/square in different colors moving, this way I’d be understanding on move on to adding like a bat to bounce off…

Thanks…

Well if you are using a buffered image then the colors are stored using a hex format up to 16^2 They also contain an alpha. for example 0xFFFFFF It is seperated into pairs so 0x is the alpha , ff is the first pair for RED the second ff pair is GREEN the final ff is for BLUE. Say I wanted a 2 by 2 square with different colors in the corners I would write this.

image = new image []
{0xFF0000 , 0x00FF00 ,
 0x0000FF , 0xFFFF00

putting it into the rows is to show the ordering , say I am the render function and I read this code I do not percieve it as a 2 axis matrix I percieve it as a single axis array as we have created. so I read by adding 1 to the array pointer each time. So if I wanted to render my new shape I would have to right according to this rule. I need to know the length of the array to avoid any issues with out of bounds exceptions. We need the width and the height of the object and the x and y it will be drawn to , however I will leave the x and y for you.


]//We have our image array containing colors.
//Lets start by creating a new method for rendering our object we will make it work for any rectangular object (for simplicity)
Public void Renderrectangle(int boundx , int boundy , int[] image, int[] pixels){//boundx is the width boundy is the height , int[] image is the object we //created and int[] pixels is the array we will be drawing to (the screen)
int cx,cx = 0; //create two new variables to store our current screen position
for(int ix = 0; ix < boundx;ix++){
    for(int iy = 0; iy < boundy;iy++){
        if(ix*iy < pixels.length){//check if we are inside the array bounds
            pixels[cx + (cy * screen.width)] = image[ix + (iy * width)]; //we set the pixel at cx +(cy * width) (because it runs accross) to our pixel that we are looking at
            cx++;
            }
       }
       cx =0;
       cy++;
}
//So how does this code work? what it does is it creates two iterrations for our x and y position on the image[] array. It then runs through them, when we //reach the point at which we hit the bottom of our array image (when iy = boundy) we increase the value of the current screen y and reset our x position.
     

Hope this helps , sorry if the code is a bit messy and has errors I dont have access to a JDK on this computer so its (attempted) in the

 tabs.

@ Lcass…

Could you give me code above that I could actually run? Its ok explaining things in code but theres no example to run for me to understand… Thanks for trying though. You must be good no doubts, i can kind of understand it but if i cant see what its doing im never gunna learn from ur efforts of explaining…

Rule 1: Do not try to ‘learn’ by copy and pasting others code. When it comes to writing out your own code, you will simply not be able to. Coding is a skill that involves creativity, both in the design and implementation of a solution to a problem. Game development requires creativity, as you will face many problems in which you need to find solutions. By copying a snippet of code, you aren’t learning a thing. You may be able to understand how it works, however you will not understand how to write it, and most importantly how to edit/improve it.

Rule 2: Do not ask for a snippet of code that you can copy and paste directly. No-one wants to spend their time creating you a game. Your comment pretty much proves the point that I made above: “When it comes to writing out your own code, you will simply not be able to”. Although the naming conventions used in the code that lcass provided make the want to throw up (maybe I’m over-reacting), anyone who has spent a week or two properly learning Java should be able to translate that in to working code. All it takes is some thought and a couple of extra lines and letters.


I suggest you forget game development for now and start from the beginning. Start off like the professionals did; making simple programs such as calculators. Oh, and please don’t try to copy and paste some code to make these programs. Instead, learn Java. Find as many resources which you can learn from: articles, blogs, forum posts, tutorials; you name it. Another persons code is NOT a resource in which you can learn from.

Once you have learnt everything on the hyperlink above, except for maybe generics and/or inheritence (it’s a good idea to learn at least a little inheritence), and you are able to create simple programs without the need for using Google, then you are ready to start to explore game development. However, more advanced topics such as pixel data manipulation should be avoided at first. Learn the basics like: the game loop, collision detection, etc. as you will develop a much greater understanding of what you’re doing and how a game is structured.

Don’t expect to be able to write fluent Java code overnight. In total it took me 5 months to learn the full language and to be able to fluently write it. In the end though it’s worth it. Just don’t give up.