Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Game problem: java.lang.IndexOutOfBoundsException

  1. #1
    Member
    Join Date
    Jan 2013
    Posts
    39
    My Mood
    Relaxed
    Thanks
    1
    Thanked 1 Time in 1 Post

    Post Game problem: java.lang.IndexOutOfBoundsException

    So i am recreating space invaders to teach myself some game programming.
    For the first time i have started to use ArrayLists.
    But every time i run it i get an java.lang.IndexOutOfBoundsException when the last bullet that you have shot hits a target.

    Thanks for your intrest and help.

    Here a full error message :
    Exception in thread "Thread-2" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(Unknown Source)
    at java.util.ArrayList.get(Unknown Source)
    at com.spaceinvader.Main.colision(Main.java:172)
    at com.spaceinvader.Main.update(Main.java:165)
    at com.spaceinvader.Main.run(Main.java:108)
    at java.lang.Thread.run(Unknown Source)

    My source Code :

    Main.java
    package com.spaceinvader;
     
    import com.spaceinvader.render.Render;
    import com.spaceinvader.entity.*;
     
    import javax.swing.JFrame;
     
    import java.awt.Canvas;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.image.BufferStrategy;
    import java.util.ArrayList;
     
    public class Main extends Canvas implements Runnable, KeyListener {
    	private static final long serialVersionUID = 1L;
     
    	static Main main;
    	static Render render;
     
    	static public JFrame frame;
    	Thread thread;
     
    	private final static int WIDTH = 400;
    	private final static int HEIGHT = 600;
    	boolean running = false;
    	static String Titel = "Space Invader";
     
    	private boolean[] keys = new boolean[65536];
    	public boolean left, right, use, back;
     
    	public static EntityPlayer player;
    	public static EntityBullet bullet;
     
    	public static ArrayList<EntityBullet> bullets;
    	public static ArrayList<EntityAlien> aliens;
     
    	public int timer = 0;
    	public int timed = 30;
     
    	public static void main(String[] args) {
    		frame = new JFrame();
    		main = new Main();
    		render = new Render();
    		frame.setResizable(false);
    		frame.setTitle(Titel);
    		frame.add(main);
    		frame.pack();
    		frame.setLocationRelativeTo(null);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setVisible(true);
    		main.start();
    	}
     
    	public Main() {
    		Dimension size = new Dimension(WIDTH, HEIGHT);
    		setPreferredSize(size);
    		setMinimumSize(size);
    		setMaximumSize(size);
    		addKeyListener(this);
     
    		player = new EntityPlayer();
    		player.setAlive(true);
    		player.setWidth(40);
    		player.setHeight(20);
    		player.setX(WIDTH / 2 - player.getWidth() / 2);
    		player.setY(HEIGHT - 50);
    		player.setVelX(5);
     
    		bullets = new ArrayList<EntityBullet>();
    		aliens = new ArrayList<EntityAlien>();
    	}
     
    	public void start() {
    		if (running)
    			return;
    		thread = new Thread(this);
    		thread.start();
    		running = true;
    	}
     
    	public void stop() {
    		if (!running)
    			return;
    		running = false;
    		try {
    			thread.join();
    		} catch (InterruptedException e) {
    			e.printStackTrace();
    		}
    	}
     
    	public void run() {
    		int frames;
    		long lastTime = System.nanoTime();
    		long lastTimer = System.currentTimeMillis();
    		double ns = 1000000000.0 / 60.0;
    		double delta = 0;
    		frames = 0;
    		int updates = 0;
    		requestFocus();
    		while (running) {
    			long now = System.nanoTime();
    			delta += (now - lastTime) / ns;
    			lastTime = now;
    			if (delta >= 1) {
    				update();
    				updates++;
    				delta--;
    				timer++;
    			}
    			render();
    			frames++;
    			while (System.currentTimeMillis() - lastTimer > 1000) {
    				lastTimer += 1000;
    				frame.setTitle("Space Invader " + updates + " ups, " + frames + " fps");
    				frames = 0;
    				updates = 0;
    			}
    		}
    	}
     
    	private void render() {
    		BufferStrategy bs = getBufferStrategy();
    		if (bs == null) {
    			createBufferStrategy(3);
    			return;
    		}
    		Graphics g = bs.getDrawGraphics();
     
    		render.render(g);
     
    		g.dispose();
    		bs.show();
    	}
     
    	public void updateKey() {
    		left = keys[KeyEvent.VK_LEFT];
    		right = keys[KeyEvent.VK_RIGHT];
    		use = keys[KeyEvent.VK_SPACE] || keys[KeyEvent.VK_ENTER];
    		back = keys[KeyEvent.VK_ESCAPE];
    	}
     
    	public void keyPressed(KeyEvent e) {
    		keys[e.getKeyCode()] = true;
    	}
     
    	public void keyReleased(KeyEvent e) {
    		keys[e.getKeyCode()] = false;
    	}
     
    	public void keyTyped(KeyEvent e) {
    	}
     
    	public void releaseAll() {
    		left = right = use = back = false;
    	}
     
    	private void update() {
    		updateKey();
    		MovementPlayer();
    		Shooting();
    		SpawnAliens();
    		colision();
    	}
     
    	private void colision() {
    		if (aliens.size() > 0 && bullets.size() > 0) {
    			for (int i = 0; i < bullets.size(); i++) {
    				for (int i2 = 0; i2 < aliens.size(); i2++) {
    					if (bullets.get(i).getBounds().intersects(aliens.get(i2).getBounds())) {
    						System.out.println("collision");
    						bullets.remove(i);
    						aliens.remove(i2);
    					}
    				}
    			}
    		}
    	}
     
    	private void SpawnAliens() {
    		int ALIENSWIDTH = 8;
    		int ALIENSHEIGHT = 4;
    		if (timer >= timed) {
    			if (back) {
    				timer = 0;
    				for (int i = 0; i < ALIENSWIDTH; i++) {
    					for (int i2 = 0; i2 < ALIENSHEIGHT; i2++) {
    						aliens.add(new EntityAlien());
    						aliens.get(aliens.size() - 1).setHeight(10);
    						aliens.get(aliens.size() - 1).setWidth(10);
    						aliens.get(aliens.size() - 1).setX(i * 30 + 100);
    						aliens.get(aliens.size() - 1).setY(i2 * 30 + 100);
    					}
    				}
    			}
    		}
    	}
     
    	private void Shooting() {
    		if (timer >= timed) {
    			if (use) {
    				timer = 0;
    				bullets.add(new EntityBullet());
    				bullets.get(bullets.size() - 1).setHeight(10);
    				bullets.get(bullets.size() - 1).setWidth(10);
    				bullets.get(bullets.size() - 1).setX(player.getX() + player.getHeight() / 2 + bullets.get(bullets.size() - 1).getWidth() / 2);
    				bullets.get(bullets.size() - 1).setY(player.getY() - bullets.get(bullets.size() - 1).getHeight());
    				bullets.get(bullets.size() - 1).setVelY(3.0);
    			}
    		}
    		if (bullets.size() > 0) {
    			for (int i = 0; i < bullets.size(); i++) {
    				bullets.get(i).incY(-bullets.get(i).getVelY());
    			}
    			for (int i = 0; i < bullets.size(); i++) {
    				if (bullets.get(i).getY() < 0 - bullets.get(bullets.size() - 1).getHeight()) {
    					bullets.remove(i);
    				}
    			}
    		}
    	}
     
    	private void MovementPlayer() {
    		if (left && player.getX() > 0) {
    			player.incX(-player.getVelX());
    		}
    		if (right && player.getX() + player.getWidth() < WIDTH) {
    			player.incX(player.getVelX());
    		}
    	}
    }

    Render.java
    package com.spaceinvader.render;
     
    import com.spaceinvader.Main;
     
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics;
     
    public class Render {
     
    	Main main;
     
    	Font font = new Font("Verdana", Font.BOLD, 22);
     
    	public Render() {
    		main = new Main();
    	}
     
    	public void render(Graphics g) {
    		g.setColor(Color.black);
    		g.fillRect(0, 0, Main.frame.getWidth(), Main.frame.getHeight());
     
    		g.setColor(Color.red);
    		g.fillRect((int)Main.player.getX(), (int)Main.player.getY(), (int)Main.player.getWidth(), (int)Main.player.getHeight());
     
    		if (Main.bullets.size() > 0) {
    			for (int i = 0; i < Main.bullets.size(); i++) {
    				g.setColor(Color.blue);
    				g.fillRect((int)Main.bullets.get(i).getX(), (int)Main.bullets.get(i).getY(),(int) Main.bullets.get(i).getWidth(), (int)Main.bullets.get(i).getHeight());
    			}
    		}
     
    		if (Main.aliens.size() > 0) {
    			for (int i = 0; i < Main.aliens.size(); i++) {
    				g.setColor(Color.green);
    				g.fillRect((int)Main.aliens.get(i).getX(), (int)Main.aliens.get(i).getY(),(int) Main.aliens.get(i).getWidth(), (int)Main.aliens.get(i).getHeight());
    			}
    		}
    	}
    }

    BaseEntity.java
    package com.spaceinvader.entity;
     
    public class BaseEntity {
     
    	private double x, y;
    	private double height, width;
    	private double velX, velY;
    	private boolean alive;
     
    	//accessor
    	public boolean getAlive(){return alive;}
    	public double getX(){ return x;}
    	public double getY(){ return y;}
    	public double getHeight(){return height;}
    	public double getWidth(){return width;}
    	public double getVelX(){return velX;}
    	public double getVelY(){return velY;}
     
    	//mutators
    	public void setAlive(boolean alive){this.alive = alive;}
    	public void setX(double x){this.x = x;}
    	public void setY(double y){this.y = y;}
    	public void incX(double i){this.x += i;}
    	public void incY(double d){this.y += d;}
    	public void setHeight(double height){this.height = height;}
    	public void setWidth(double width){this.width = width;}
    	public void incHeight(double i){this.height += i;}
    	public void incWidth(double i){this.width += i;}
    	public void setVelX(double velX){this.velX = velX;}
    	public void setVelY(double velY){this.velY = velY;}
     
    	BaseEntity(){
    		setAlive(false);
    		setX(0);
    		setY(0);
    		setWidth(0);
    		setHeight(0);
    	}
    }


    EntityAlien.java
    package com.spaceinvader.entity;
     
    import java.awt.Rectangle;
     
    public class EntityAlien extends BaseEntity {
     
    	public Rectangle getBounds() {
    		Rectangle r;
    		r = new Rectangle((int) getX(), (int) getY(), (int) getWidth(), (int) getHeight());
    		return r;
    	}
     
    	public EntityAlien() {
    		setAlive(true);
    	}
    }

    EntityBullet.java
    package com.spaceinvader.entity;
     
    import java.awt.Rectangle;
     
    public class EntityBullet extends BaseEntity {
     
    	public Rectangle getBounds() {
    		Rectangle r;
    		r = new Rectangle((int) getX(), (int) getY(), (int) getWidth(), (int) getHeight());
    		return r;
    	}
     
    	public EntityBullet() {
    		setAlive(false);
    	}
    }

    EntityPlayer.java
    package com.spaceinvader.entity;
     
    import java.awt.Rectangle;
     
    public class EntityPlayer extends BaseEntity {
     
    	public Rectangle getBounds() {
    		Rectangle r;
    		r = new Rectangle((int) getX(), (int) getY(), (int) getWidth(), (int) getHeight());
    		return r;
    	}
     
    	public EntityPlayer() {
    		setAlive(true);
    	}
    }


  2. #2
    Junior Member
    Join Date
    May 2013
    Posts
    10
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Game problem: java.lang.IndexOutOfBoundsException

    What line does the compiler say there is an error?

  3. #3
    Member
    Join Date
    Jan 2013
    Posts
    39
    My Mood
    Relaxed
    Thanks
    1
    Thanked 1 Time in 1 Post

    Default Re: Game problem: java.lang.IndexOutOfBoundsException

    as said in the top its
    at com.spaceinvader.Main.colision(Main.java:172)

    line 172 thus
    if (bullets.get(i).getBounds().intersects(aliens.get( i2).getBounds())) {

    in the colision methode

    it isnt a syntax error but an out of bounds

  4. #4
    Junior Member
    Join Date
    May 2013
    Posts
    10
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Game problem: java.lang.IndexOutOfBoundsException

    Sorry about that totally spaced out when I read that. Have you tried just adding a few bullets into the list first to see if that was the problem? Same thing with aliens?

  5. #5
    Member
    Join Date
    Jan 2013
    Posts
    39
    My Mood
    Relaxed
    Thanks
    1
    Thanked 1 Time in 1 Post

    Default Re: Game problem: java.lang.IndexOutOfBoundsException

    i havent tried that yet but i dont think it will make a diffrence
    but ill do that now

    --- Update ---

    well i initilasid the bullits earlier but what happens is that the were shot and afther that when the last bullet hits something it crhases agian at the same spot. it has to do something with these for loops i think(i and i2) but i dont know what

  6. #6
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Game problem: java.lang.IndexOutOfBoundsException

    bullets = new ArrayList<EntityBullet>();
    bullets is now initialized as an empty array list designed to hold bullets. (ie an empty clip)
    There are no bullets in it to check for collisions. Which is why the error message says:
    ava.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    Index 0 is not valid because the size is 0 not 1. When there is a bullet in the list, the size will be 1 and the index number of that bullet will be 0

    Same thing applies to aliens

  7. #7
    Member
    Join Date
    Jan 2013
    Posts
    39
    My Mood
    Relaxed
    Thanks
    1
    Thanked 1 Time in 1 Post

    Default Re: Game problem: java.lang.IndexOutOfBoundsException

    So i switched the for loops arround and that was it and now it works.
    Here is the code if anyone wants it.

    	private void colision() {
    		if (aliens.size() >= 1 && bullets.size() >= 1) {
    			for (int i = 0; i < aliens.size(); i++) {
    				for (int i2 = 0; i2 < bullets.size(); i2++) {
    					if (bullets.get(i2).getBounds().intersects(aliens.get(i).getBounds())) {
    						System.out.println("collision");
    						System.out.println(aliens.size() + " " + i);
    						aliens.remove(i);
    						bullets.remove(i2); 
    					}
    				}
    			}
    		}
    	}

Similar Threads

  1. Jva Game error: Exection in thread "main" java.lang.nullpointerexception
    By Amartin4200 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: March 14th, 2013, 07:22 AM
  2. Replies: 5
    Last Post: January 23rd, 2013, 05:29 PM
  3. Problem with java.lang.NullPointerException
    By more_dread in forum Exceptions
    Replies: 11
    Last Post: November 21st, 2011, 06:42 AM
  4. problem in java.lang.NullPointerException
    By jianghuzai in forum What's Wrong With My Code?
    Replies: 6
    Last Post: July 28th, 2010, 11:24 AM
  5. Replies: 2
    Last Post: November 3rd, 2009, 06:28 AM

Tags for this Thread