I am working on a small game based on Gudradain basic game code and as i doesn’t have much experience with Java(done some c++) so i know my way around the coding bit so I’m not asking for the code but as this is my first real “game” I’m trying to make a way for it to render images when it is needed, so far I’ve just managed to make it render trough a predefined array which says how many it should render and the image’s stats, but when making a game I can’t have a set amount of images at all time(for example when enemies appear at random) So how would I go about doing that? Should i for example make a rendering class which receives input from the games objects with the image, x and y coordinates and so on, or is it a better way to do this?
Check tutorials forum, I think there is very nicely explained topic about simple game creation.
It is as far as I know only one “real” tutorial in the tutorials section which is the Basic game tutorial, which is not a full tutorial but more of a code to get you started, it doesn’t explain anything about rendering more then one picture at once or stuff like key listening, so I’m gonna reshape my question. Anyone know of any good simple java game tutorial or source code?
http://javaboutique.internet.com/tutorials/Java_Game_Programming/
Its by no means the correct way to do it, but heres some quick little tutorials thatll get you started,
move onto more sophisticated tutorials after youve mastered everything here.
That link is actually my hand me down, cause I used it. 
New problem, when using my current rendering method it causes extreme lag. Is there a better way? Look for the I THINK THE FAULT MIGHT BE HERE in the comments.
The code is based on Gudradain’s code as said earlier(Thanks Gudradain, wouldn’t get into Java programming if it wasn’t for that.)
And yes i know it is a giant abomination of code, ill fix it later.
(I’ll post all the code of requested.)
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.image.BufferStrategy;
import java.awt.image.ImageObserver;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
import java.lang.Math;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Game implements Runnable{
final int WIDTH = 400;
final int HEIGHT = 300;
//Game area in game units
final int WIDTH_UNITS = WIDTH/10;
//ditto
final int HEIGHT_UNITS = HEIGHT/10;
//Total units in game area
final int TOTAL_UNITS = WIDTH_UNITS*HEIGHT_UNITS;
//Stores Keys Pressed
int PressedKey;
static int sysin;
//Used by terrain renderer
int CurRenderGround;
//Creates Player object
Player pl = new Player();
//Creates the level array
int[] lvl_1 = new int[TOTAL_UNITS];
JFrame frame;
Canvas canvas;
BufferStrategy bufferStrategy;
boolean first = true;
public Game() {
frame = new JFrame("Basic Game");
JPanel panel = (JPanel) frame.getContentPane();
panel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
panel.setLayout(null);
canvas = new Canvas();
canvas.setBounds(0, 0, WIDTH, HEIGHT);
canvas.setIgnoreRepaint(true);
panel.add(canvas);
canvas.addMouseListener(new MouseControl());
canvas.addKeyListener(new KeyControl());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
canvas.createBufferStrategy(2);
bufferStrategy = canvas.getBufferStrategy();
canvas.requestFocus();
}
private class MouseControl extends MouseAdapter{
}
//Key Listener
private class KeyControl extends KeyAdapter{
public void keyPressed(KeyEvent e) {
PressedKey = e.getKeyCode();
System.out.println(e.getKeyCode());
if(e.getKeyCode() == 68) pl.MoveX(1);
if(e.getKeyCode() == 65) pl.MoveX(-1);
if(e.getKeyCode() == 83) pl.MoveY(1);
if(e.getKeyCode() == 87) pl.MoveY(-1);
}
}
long desiredFPS = 60;
long desiredDeltaLoop = (1000*1000*1000)/desiredFPS;
boolean running = true;
public void run(){
long beginLoopTime;
long endLoopTime;
long currentUpdateTime = System.nanoTime();
long lastUpdateTime;
long deltaLoop;
while(running){
beginLoopTime = System.nanoTime();
render();
lastUpdateTime = currentUpdateTime;
currentUpdateTime = System.nanoTime();
try {
update((int) ((currentUpdateTime - lastUpdateTime)/(1000*1000)));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
endLoopTime = System.nanoTime();
deltaLoop = endLoopTime - beginLoopTime;
if(deltaLoop > desiredDeltaLoop){
//Do nothing. We are already late.
}else{
try{
Thread.sleep((desiredDeltaLoop - deltaLoop)/(1000*1000));
}catch(InterruptedException e){
//Do nothing
}
}
}
}
private void render() {
Graphics2D g = (Graphics2D) bufferStrategy.getDrawGraphics();
g.clearRect(0, 0, WIDTH, HEIGHT);
render(g);
g.dispose();
bufferStrategy.show();
}
/**
* Overwrite this method in subclass
*
*/
public void update(int deltaTime) throws IOException{
}
//Do all the first stuff cuz doing it in run() caused errors
public void init() {
if(first) {
pl.Speed = 10;
RandomGenLvl();
System.out.println("Init Ran");
first = false;
}
}
//Gets the image's used but the program I THINK THE FAULT MIGHT BE HERE!
private Image getIMG(String path1)
{
Image img = null;
try {
img = ImageIO.read(new File(path1));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return img;
}
//Generates a random level
public void RandomGenLvl() {
for(int i = 0; i < TOTAL_UNITS; i++) {
Random gen = new Random();
int lool = gen.nextInt(2);
lvl_1[i] = lool;
System.out.println(lool);
}
}
//Unused Random method
private int random()
{
Random generator = new Random();
int ret = generator.nextInt(1);
return ret;
}
protected void render(Graphics2D g){
init();
//Render Terrain------------------------------------------
int CurLine = 1;
int CurSprite = 1;
String Sprite;
for(int i = 1; i < WIDTH_UNITS&&CurLine < HEIGHT_UNITS; i += 1) {
CurSprite += 1;
CurRenderGround = lvl_1[CurSprite];
if(CurRenderGround == 0) {
Sprite = "res/grass1.png";
}
else Sprite = "res/rock.png";
g.drawImage(getIMG(Sprite), i*10, CurLine*10, canvas);
if(i==WIDTH_UNITS-1) {
CurLine += 1;
i = 0;
}
//-----------------------------------------------
g.drawImage(getIMG(pl.GetCurSprite()), pl.PosX, pl.PosY, canvas);
System.out.println(pl.PosX);
}
}
public static void main(String [] args) throws IOException{
Game ex = new Game();
new Thread(ex).start();
}
}
You’re loading the images from the desk every single frame!
That’s very very very slow.
Load them once at startup, store them somewhere, and then reference them from there.
Ok really noob question here; I have two classes one called Player and one called Main, I want to run a method that is defined in Main in the player class, so it would be like this:
public class Main {
int x = 0,y = 0;
//Turns X and Y coords into My own game Coords
public int CoordsToUnits(int x, int y) {
int Unit = x/10-1+12*y/10-12;
return Unit;
}
}
public class Player {
int XPos = 10, YPos = 20;
int GamePos = CoordsToUnits(XPos,YPos)// <- Want this to run in Player class or a method in Player class which gets the var from a method in the Main class.
}
Forget i figured it out.
New problem, I’m now loading my level data from a text file, which means I have to create a way to read each int(which for now consists of 1’s and 0’s) into my level array, so the first number in the file should go to lvl_1[1] second into lvl_1[2] etc. How do i do this?
Also when trying to load the file I have to surround it with try or a throws FileNotFound but when I add this to that method and now all the classes using this method needs to have try around them, is there any way to avoid this?
Really appreciate all the help I could get. 
I don’t understand your first question.
As for the second, you should only need one try/catch.
try
{
BufferedReader br = new BufferedReader(new FileReader("my/file/dir/thing.txt"));
String line = br.readLine();
while (line != null)
{
parseLine(line);
line = br.readLine();
}
br.close();
}
catch (Exception e)
{
e.printStackTrace();
}
Do it like that (not necessarily using a BufferedReader, etc.), pretty much put all file access in the try/catch and then you shouldn’t need to worry about anything else.
Code like that is causing the most nasty/unexpected resource leaks.
The sad thing is that Java makes File (or network) I/O really verbose:
InputStream in = null;
try
{
in = new FileInputStream(file);
}
catch(IOException exc)
{
// do your normal exception handling
}
finally
{
try
{
if(in != null)
in.close();
}
catch(IOException exc)
{
// very rare, but: implicit call to in.flush() inside in.close() might have failed, do NOT ignore, alarm!
throw new IllegalStateException("failed to close channel", exc);
}
}
Huh, that’s good to know - what I put is how I was originally taught to do it and have been doing so ever since. What do you recommend doing if there’s an IllegalStateException? If you’ve got a game you can’t actually have it crash - you need to ignore the Exception and soldier on. Anyway to free those leaking resources?
It depends.
If it’s network I/O, ignore it. If it’s file I/O, ask the user to reinsert their usb-stick/warn them about data loss.
Anyway, the point is that you always must close a stream in a finally block, how you handle the rare close() screwups is up to you. It’s not always advisable to ‘soldier on’ when something is clearly broken. Actually, I try to make my applications crash as soon as possible. Hard crashes, no trying to recover. That’s how I find, and fix most bugs. Once my app is in an unexpected/undetermined state, I wouldn’t trust it, and my users are better of if the application terminates right there.
How often do you see people posting applets on this forum, and then the thread fills with stacktrace after stacktrace. That’s only because those exceptions aren’t actually handled properly or the applet tries to ‘soldier on’, which quite often seems to work, but it does more harm than good, especially if it’s not just a game, but you’re handling user-data which must not get corrupted.
Silent errors are among the worst, right along side with on-the-fly fixing of invalid state of code:
public void render()
{
if(!this.inited)
this.init();
// render stuff
}
this should be replaced with:
public void render()
{
if(!this.inited)
throw new IllegalStateException("engine error");
// render stuff
}
and that exception should never be caught, it should crash the application, right there, for a quick fixy fixy
What I mean is that I have for example a file that contains something like “1000111010111010101010” so the 1’s means grass and 0’s are rock. Now I have a game that is grid based so it got small squares that each contain ether grass or rock. The game loads the data about what material goes in which square by checking an array that contains the level data.
Example:
the level array contains “01011110101” each of these numbers are in their own int in the array so
[1] = 0
[2] = 1
[3] = 0
[4] = 1
[5] = 1
and so on.
So the level is made by squires so it looks something like this:
|------------|
|1|2|3|4|5|
|------------|
|6|7|8|9|10|
|------------|
|11|12|etc.| | |
|------------|
So to check what material squire 1 contains i check what is in the level [1] int, so since in the example [1] = 0 it is made of rock
Ops, got carried away.
Anyway, what i’m asking is how to make the text file which contains 00101001110 to take each number and but them into their corresponding int in the array so the first number which is 0 will go into the level[1] and the next which is a 0 will go into level[2] and the next which is a 1 will go into level[3].
I don’t know any way i can explain it any better then that.
Well yeah, you obviously don’t want to force a loop if something didn’t work. I usually print a stack trace of the exception, show an error popup, and that’s it. But obviously it depends on the application - if there’s a problem saving your game, it should show the error but otherwise do nothing. If there’s a problem loading it, same thing. Now if it’s something that is necessary for the game to work (like loading the next level), obviously you show an error and quit.
So basically you ignore the exception in your example just as often as you would ignore any other exception. 
BufferedInputStream in = null;
try
{
in = new BufferedInputStream(new FileInputStream(file));
int num = in.read();
ArrayList<Integer> numbers = new ArrayList<Integer>();
while (num >= 0)
{
numbers.add(new Integer(num));
num = in.read();
}
myNumberArray = numbers.toArray(new int[0]);
}
catch(IOException exc)
{
// do your normal exception handling
}
finally
{
try
{
if(in != null)
in.close();
}
catch(IOException exc)
{
// very rare, but: implicit call to in.flush() inside in.close() might have failed, do NOT ignore, alarm!
throw new IllegalStateException("failed to close channel", exc);
}
}
Thanks for all the help btw, but I’ve got a new problem; if all the entities in the game are classes, how do I get a specific class without having to pre program it in the game. ex: Player shoots an arrow, the arrow detects it has hit something, for example another character, now i want the arrow’s class to find the name of the object it is hitting and run a method called “KillMe()” or something in the hit class to remove it from the game. Is there any way to run a method in a class you don’t know the name if like:
if(this.GetCollision == true) {
hit = getClass(EntAtPos(30,23));
hit.KillMe();
}
If you know it’s a specific type of class, you can always cast it to that type and then call the method.
ex.
for (int i = 0; i < entities.size(); i++)
{
Entity e = entities.get(i);
if (e instanceof CombatEntity)
{
((CombatEntity)e).attack();
}
}
However, I would recommend only doing that in the rarest cases, the reason being that you should be smart about your class hierarchy rather than having a bunch of instanceof calls all over the place. e.g. don’t think about everything being “classes,” give everything that might need to get killed a common superclass, and have a list of that superclass when you’re iterating through. This way you know they all can be killed. Typically the way I do it is to have a superclass Entity that has position, size, velocity, etc. as well as the ability to perform a “safe” delete (mark a flag for deletion that will cause it to get removed at the beginning of the next timestep, instead of during the current timestep), can check for collisions with other Entity’s, can be drawn, can perform an update, etc. Then I have a subclass (CombatEntity) that has combat variables, like hit points, damage, speed, etc. If you tell a CombatEntity to markForDeletion() (perform the safe delete), it overrides Entity’s function by playing a death animation and then actually deleting itself when the animation is complete.
Does all that make sense? Typically functionality should be determined within the class, not outside of it. Instead of calling CombatEntity.attack() outside, it would automatically decide to do that according to its state when update() gets called on it.
Another stupid problem, when you hold in a key it has a small delay before starting to repeat the keypress infinitly. So when you hold down the y key, it will look like this(space is time)
y yyyyyyyyyyyyyyyy
Is there any way to stop this, it’s hard to make a game when you can’t make your character move without moving stopping then starting to move again.
public void onKeyPressed(KeyEvent e)
{
this.keysPressed[e.getKeyCode()] = true;
}
public void onKeyReleased(KeyEvent e)
{
this.keysPressed[e.getKeyCode()] = false;
}
public boolean isKeyDown(int keycode)
{
return this.keysPressed[keycode];
}