Calling all Experienced Java Programmers....

Just have a keen few questions I have been thinking about posting for a while now, I’ve been learning Java on and off for a few years now and lately bang on it hours on end as I’m looking for a career with the language itself eventually. Its really good fun learning… Anyway… I’m learning Java game development for practice and need some tips on what projects to start work with, I know theres pong, I need really simple ideas really… What steps should I take when learning basic animation with keyboard input (obviously using the KeyListener class as I know about this).

The thing is, I struggle with making something move, I can make an JFrame window so far coding from scratch and implementing JButtons, JSliders with the ActionListener etc. But if someone could be so kind and give me some examples, from different people if possible… So I’ve got some confidence that there is multiple ways of doing something when it comes to OOP…

Like example of a bouncing ball in lets say, setSize(600,480) JFrame window or something, then (OPTIONAL) some keyboard input with a second drawn box if you could be so kind to share the knowledge! It is something I am really stuck with, I’m always thinking its as easy as just setting up some method or class, but when I’m looking at tutorials for bits like this it goes into x,y,vel,gravity etc etc which is some logic side of Java 2D Graphics side of it I’m struggling with like I say.

Thanks fellow programmers! :slight_smile:

Use Libgdx. Bin Java2D.

/thread

Edit : I probably should elaborate why. Speed for one, it is also much simpler to work with.

You can use what you need from it, had everything you need to get a game up and running in the shortest time possible. I recommend from personal experience that you do pong or space invaders.

I totally agree. Java2D is deprecated, and uses a thing called ‘software rendering’. It’s when the CPU is used to generate raster graphics (pixels). OpenGL allows information to be sent to your graphics card, and let it do the work using programs called ‘shaders’ that run on your GPU (Graphics Card). LibGDX uses a Java OpenGL wrapper named LWJGL (Light Weight Java Game Library), but simplifies the OpenGL functions and techniques down to a higher level that’s SUPER easy to learn. And when you know some of that, you can work your way down to lower level LWJGL/OpenGL work.

Here’s a good tutorial on how to make a platformer in LibGDX. Also teaches you some basic logic and the stuff you’d run into when making a game in Java.

Thanks for the quick responses. I know about OpenGL, I’ve got loads of books on it C++ etc. I know about Slick2D, LibGDX, LWJGL (as we all know Notch implemented with minecraft). I must have over 100GB of tutorials on them downloaded from youtube etc from when I got cut offline to keep myself busy. Among other game theory books on other engines, unity, udk, cryengine

But my question was more aimed towards my peoples way of just creating a moving animation as described as my original post using pure java’s ‘Software Renderer’, how do you know I’m not interested for future entrys for the Java4K comps? I mentioned that my interest in Gaming was to add more skill to possible future Java careers where I live and there is many. I don’t mean to be fussy or come across cocky here but I really wanted answers and example code of simple things like described - peoples coding techniques of what I mentioned… For instance I was watching a tutorial today which was very different as they used collections for storing objects for there game and I’ve only just started studying collections in Java and got lost, I know about Vectors and Iterators in C++ 11 though when I’ve been using QT but Java is fasinating

Also, thanks for the Pong and Space Invaders ideas, but if anyone could please demo the code I’ve mentioned plus some other ideas on some swing gui mini game ideas or whatever that’d be great !! ;D

Java2D is not deprecated. It just isn’t ideal for games because it doesn’t take advantage of the graphics card. Although I think that JavaFX is aimed at replacing it? I’m not too sure on that though.

@OP If you’re just talking about a general Java career (not gaming oriented), then don’t worry about LibGDX. Instead, learn Swing (Others who are in the profession can tell you much more about what you should learn than I can). Also, keep learning about Collections no matter what route you take!

Yes, there pushing JavaFX more to replace swing so I’ve read numerous places and quiet official as well…

Yes, This is what I am doing from my ‘OP’

Are you saying that you are struggling with the basics of animation? We have several decent tutorials on ‘game loops’ on the site, if you check out our Resources or Tutorials links (just below the mast head).

Simple example (nothing is simple the first time?), using Swing: place a JPanel in the JFrame. (Or use a JComponent, if you don’t plan to put any other components in the area.)

Then, you can draw in the JPanel or JComponent by overwriting the method “paintComponent(Graphics g)”. There are many methods of drawing using the Graphics variable g, such as g.drawRect() or g.drawImage(), or even more drawing methods if you cast the Graphics variable into a Graphics2D variable. There is a Java tutorial on Java2D worth checking out: http://docs.oracle.com/javase/tutorial/2d/index.html

Once you have a feel for drawing, check out the “game loop” tutorials. In a game loop, we calculate something, such as the location of a bouncing ball, then draw it, in a loop. One key is calling the repaint() method of the JPanel or JComponent. This will automatically call the paintComponent() method mentioned above.

That is the basic idea, anyway. There are a couple different ways to get the loop going. It can be a while loop, or it can be a Timer’s “TimerTask” that is scheduled to repeat. (See util.Timer for more info on that.)

EDIT - I just read the OP again to make sure I was not posting useless shite and I noticed this:

If you are learning, the last thing you want to do is get caught up in “good practices”, there are things you should be doing but when they start to prevent you from coding you need to reconsider your approach. You should worry less about OOP structure/design and just code, OOP design is not something you really learn by specifically practising it hours on end, it comes from experience and time.

My OOP is still a bit rubbish and I have trouble coming up with a decent structure, but it is 10x better than what it was a year ago. Code, code, code and code some more, look back at it in a few month time and you will see that somehow, by complete magic that your code structure and organization has dramatically improved :p. Looking online at code snippets helps speed this process up.


I might be reading into this wrong but I think you might be over-thinking things.

Bare in mind positioning and moving is all just numbers, all you have to do is change the numbers in order to simulate movement. So all you have to do is move things over-time in a stable loop, you can read more about loops HERE.

So if you have the X and Y coordinates in a variable you can easily change these values, such as:

x += speed * 1f/60f

What this basically does it take the X value, add speed onto it and multiply it by a fixed time step (0.0166ms). In LibGDX the loop is locked to 60 updates per second (60FPS) so this number is roughly right, when you make your own game loop or use LibGDX you can use a “delta” value. Delta is the time that has passed since the last frame. I merely put the fixed 0.0166ms value just for explanation purposes.

Space invaders is a good example for basic movement code, as there are 2 ways of doing it. The invaders jump spot to spot and your laser base/laser/enemy laser all move smoothly.

Here is my invader move code:

	/** Move the invader left by 1 unit */
	public void moveLeft() {
		bounds.x -= speed;
	}

	/** Move the invader right by 1 unit */
	public void moveRight() {
		bounds.x += speed;

	}

Since here we do not want to move the aliens smoothly, we simply just add the speed onto the current X value which causes them to jump to the next spot on my virtual little grid.

For the laser base we are doing the following:


if (Gdx.input.isKeyPressed(Keys.A) || Gdx.input.isKeyPressed(Keys.LEFT)) {
			velocity.set(-speed, 0);
		} else if (Gdx.input.isKeyPressed(Keys.D)
				|| Gdx.input.isKeyPressed(Keys.RIGHT)) {
			velocity.set(speed, 0);
		} else {
			velocity.set(0, 0);
		}


Velocity is a Vector2, as you are familar with. We basically set the velocity of the target to the max speed instantly and then later in the loop we add these values onto the current X and Y coordinate of the laser base, which is also a Vector2. Then multiply by delta to get smooth movement.

		
/* Apply a velocity to our entity */
		bounds.x += velocity.x * delta;
		bounds.y += velocity.y * delta;

The same principle can be used for Animation. An animation is basically a collection of still images that are played in sequence using some sort of timing mechanism in order to change the frame appropriately. This can be applied to any code, all of the code I have posted thus far is generic, as long as you have some sort of game loop.

The simplest way to do animation is to store each frame in an array and shift through it has time passes. Like so (I wrote this specially for you <3:


public class AnimatorExample {

	// All the textures we want to use, depending on what library you use this
	// will be different, e.g BufferedImage
	Texture[] keyFrames;
	// The actual frame we are on
	Texture currentFrame;
	// The current frame number we are on
	int currentFrameNumber;
	// This is the total time the animation has been in the current frame
	float stateTime;
	// The total time in milliseconds each frame lasts for, you can use seconds, nanoseconds or whatever but delta time usually
   // usually works in milliseconds
	float frameDuration;
	// The total duration of the entire animation, this can be used to check if
	// the animation is finished
	float animDuration;

	/**
	 * We basically state the animation duration and pass in an array of frames,
	 * from this data we can setup the rest of the class
	 * 
	 * @param frameDuration
	 * @param frames
	 */
	public AnimatorExample(float frameDuration, Texture... frames) {
		frames = new Texture[frames.length];
		for (int i = 0; i < frames.length; i++) {
			keyFrames[i] = frames[i];
		}
		currentFrameNumber = 0;
		currentFrame = keyFrames[currentFrameNumber];
		this.frameDuration = frameDuration;
		animDuration = frameDuration * keyFrames.length;
	}

	/**
	 * This method is a little specific to LibGDX but you might know what a
	 * sprite batch is anyway. In Java2D this would be Graphics2D I think, the
	 * delta time is just the time since the last frame.
	 * <p>
	 * 
	 * Usually you want to separate the updating from the drawing code but I put
	 * it in one place for convenience.
	 * <p>
	 * Now all you have to do is call this is a loop (which you have to anyway
	 * to get it to draw) and pass in the delta time, you can just pass 1f/60f
	 * if you don't have a loop that calculates delta
	 * 
	 * @param batch
	 * @param delta
	 */
	public void draw(SpriteBatch batch, float delta) {
		// Here we increase the state time so we can decide when to switch frame
		stateTime += delta;

		// Check if the state time is more than the frame duration
		if (stateTime > frameDuration) {
			// Make sure we stay within the bounds of the array, ideally we use
			// a
			// method for this but whatever
			if (currentFrameNumber != keyFrames.length) {
				// Increase the current frame number and set the current frame
				// to the correct one
				currentFrameNumber++;
				currentFrame = keyFrames[currentFrameNumber];
			} else {
				// The animation is finished, reset it. We can do something
				// different here if you want, like stop it, repeat etc. For now
				// I just repeat
				currentFrameNumber = 0;
				currentFrame = keyFrames[currentFrameNumber];
			}
			stateTime = 0;
		}
		// Just draw the current frame, same goes for Java2D like graphics.paint(currentFrame), I am rusty with Java2D so
       //forgive me :p
		batch.draw(currentFrame, 50, 50);
	}

}


I hope this has helped clear things up a little, you might just be having trouble realising that all these things are numbers that you change using other numbers :stuck_out_tongue: Nothing fancy going on here, even when you simulate real physics and/or use fancy mathematics, the code remains simple but the logic becomes complicate. If that makes sense.

You can see all my Space Invaders code here, take it with a grain of salt though as this project was rushed in a week to gain entry to a Games Development course at college. The code is not bad and it has some good examples but hell, it probably has more bad ones than anything. It got to the point I literally chucked OOP design out the window and started coupling code horribly all over the place.

Source
Official Thread

Thanks peeps - and thanks especially for that long previous post Gibbo, philfrei was inspiring and a bit of a kick for swing- just what I needed. I have actually read the Game Loop Topic before - Like I say I just wanted some response from it, some views. I’ve been signed up for a while now and not made many posts, I don’t know anyone locally to hook up with to talk about stuff like Java with so had this in mind. So apologises if the questions have been asked numerous times before, I have checked things like this up, but its just what I said really ^^^

We have rockstar games where we live in this town but Gaming isnt something I 100% want for a career, I wouldnt mind if its applications but Ive read places that learning game programming is a bonus if your wanting to get into applications/web (tomcat etc)

If theres anything anyone else would like to share regarding Graphics2D, Graphics g, paint() etc with loops for animation that’d be wicked. I basically have Java4K on my head, its so fasinating! Plus the pure Java on lundum dare. And no, as much as Notch is inspiring its not something I’m trying to copy just incase your wondering why because of the subjects I’ve chosen :slight_smile:

Little off-topic, Edinburgh? I can literally see the building from my street.

Naa mate, Lincoln UK - I think its more a test than dev though. I know there were some jobs going advertising for experienced gamers who can finish a game on hard settings when GTAVI was in development. I didn’t bother applying though, I’m not really good with games I’m just fascinated by the technical side of it. Nice to see your from the UK though (and ‘off topic’ I thoughts are the votes were rigged!!) I thought it would be mostly american on here but I guess thats just me being steretypical in a sense, probably because I started off on Java Ranch!!