I am getting this error.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 >= 0
	at java.util.Vector.elementAt(Unknown Source)
	at Game.collision(Game.java:176)
	at Game.<init>(Game.java:20)
	at Frame.<init>(Frame.java:12)
	at Frame.main(Frame.java:31)

The game was working, but when the enemies came on the screen it started lagging, so I made another thread, and just copied the code that animates the players to a separate thread. and left the collision detection. and now it doesn't work. here is the class the error occurs in.

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.util.*;

public class Game extends JPanel implements Runnable, ActionListener{

	Player p1;
	Player p2;
	Image background;
	
	Rectangle screenSize = new Rectangle (Toolkit.getDefaultToolkit().getScreenSize());
	Timer healthTimer;
	Vector<Player> players = new Vector<Player> ();
	Thread t = new Thread (animations());
	Thread t2 = new Thread (collision());
	Timer timer = new Timer (10, this);
	int healthX, healthY;
	boolean displayHealth;
	Rectangle healthRect;
	Vector<Zombie> enemy = new Vector<Zombie> ();
	Timer zombieSpawn;
	boolean healthTimerRunning = false;
	
	Game(Player player, Player player2){
		players.add(player);
		players.add(player2);
		timer.setInitialDelay(1000);
		timer.start();
		timer.setActionCommand("threadTimer");
		setBackground (Color.black);
		zombieSpawn = new Timer (10000, this);
		zombieSpawn.setActionCommand("Spawn Zombie");
		zombieSpawn.start();
		enemy.add(new Zombie(players.elementAt(0),players.elementAt(1)));
		enemy.add(new Zombie(players.elementAt(0),players.elementAt(1)));
		enemy.add(new Zombie(players.elementAt(0),players.elementAt(1)));
		repaintMethod();
	}
	
	
	


	public void repaintMethod() {
		// TODO Auto-generated method stub
		repaint();
	}

	public void paintComponent (Graphics g){
		super.paintComponent(g);
		
		if (displayHealth == true){
			g.setColor (Color.red);
			g.fillRect(healthX + 5, healthY, 5, 15);
			g.fillRect(healthX, healthY + 5, 15, 5);
		}
		
		for (Player p: players){
			if (p.alive){
				g.drawImage (p.playerImage, p.x,p.y,this);
			}
			else {
				g.drawImage(p.playerDead, p.x, p.y, this);
			}
		}
		for (Zombie z : enemy){
			g.drawImage(z.zombie, z.x, z.y, 32, 32, this);
		}
		
		g.setColor (Color.yellow);
		for (Player p: players){
			for (Bullet b : p.bullets){
				g.fillRect (b.bx,b.by,b.bulletRect.width,b.bulletRect.height);
			}
		}
		
		
		g.setColor (Color.yellow);
		g.drawString("Player 1 alive: " + players.elementAt(0).alive, 10, screenSize.height - 10);
		g.drawString("Player 2 alive: " + players.elementAt(1).alive, 150, screenSize.height - 10);
		g.drawString("Zombie Location: " + enemy.elementAt(0).x + ", " + enemy.elementAt(0).y, 300, screenSize.height - 10);
		g.drawString ("Health Timer Running: " + healthTimerRunning, 450, screenSize.height - 10);
	}


	private Runnable animations() {
		// TODO Auto-generated method stub
		// animate players, player 1
		for (Player p: players){
			if (p.alive){
				if (p.up){
					p.y -= 3;
					p.updateImage ('u');
				}
				else if (p.down){
					p.y += 3;
					p.updateImage ('d');
				}
				else if (p.left){
					p.x -= 3;
					p.updateImage ('l');
				}
				else if (p.right){
					p.x += 3;
					p.updateImage ('r');
				}
				p.updateRectangle();
			}
			
		}
		// animate bullets
		for (Player p: players){
			for (Bullet b : p.bullets){
				b.bx += b.dirX;
				b.by += b.dirY;
			}
		}
		//animate zombies
		if (enemy != null){
			for (Zombie z : enemy){
				z.animate();
			}
		}
		return null;
	}
	
	private Runnable collision() {
		// TODO Auto-generated method stub
		
		//collision detection man and wall
		for (Player p : players){
			if (p.facing == 'u' && p.y < 0){
				p.y = 0;
			}
			if (p.facing == 'd' && p.y + 32 > screenSize.height){
				p.y = screenSize.height - 32;
			}
			if (p.facing == 'l' && p.x < 0){
				p.x = 0;
			}
			if (p.facing == 'r' && p.x + 32 > screenSize.width){
				p.x = screenSize.width - 32;
			}
		}
		
		
		//collision detection zombie and wall
		int removal = -1;
		//collision detection bullets and wall
		for (Player p : players){
			for (Bullet b : p.bullets){
				if (b.dirX == -3 && b.bx < 0){
					removal = p.bullets.indexOf (b);
				}
				else if (b.dirX == 3 && b.bx + 3 > screenSize.width){
					removal = p.bullets.indexOf(b);
				}
				else if (b.dirY == 3 && b.by + 3 > screenSize.height){
					removal = p.bullets.indexOf(b);
				}
				else if (b.dirY == -3 && b.by < 0){
					removal = p.bullets.indexOf(b);
				}
			}
			if (removal != -1){
				p.bullets.removeElementAt(removal);
				removal = -1;
			}
		}
		//collision detection player and bullet
		if (players.elementAt(1).alive){
			for (Bullet b : players.elementAt(0).bullets){
			
				if (b.dirX == -4 && players.elementAt(1).playerRect.contains(b.bx,b.by)){
					removal = players.elementAt(0).bullets.indexOf (b);
				}
				else if (b.dirX == 4 && players.elementAt(1).playerRect.contains(b.bx + 3, b.by)){
					removal = players.elementAt(0).bullets.indexOf(b);
				}
				else if (b.dirY == 4 && players.elementAt(1).playerRect.contains(b.bx, b.by + 3)){
					removal = players.elementAt(0).bullets.indexOf(b);
				}
				else if (b.dirY == -4 && players.elementAt(1).playerRect.contains(b.bx, b.by)){
					removal = players.elementAt(0).bullets.indexOf(b);
				}
			}
		}
		if (removal != -1){
			players.elementAt(0).bullets.removeElementAt(removal);
			players.elementAt(1).alive = false;
			removal = -1;
		}
		for (Bullet b : players.elementAt(1).bullets){
			if (players.elementAt(0).alive){
				if (b.dirX == -4 && players.elementAt(0).playerRect.contains(b.bx,b.by)){
					removal = players.elementAt(1).bullets.indexOf (b);
				}
				else if (b.dirX == 4 && players.elementAt(0).playerRect.contains(b.bx + 3, b.by)){
					removal = players.elementAt(1).bullets.indexOf(b);
				}
				else if (b.dirY == 4 && players.elementAt(0).playerRect.contains(b.bx, b.by + 3)){
					removal = players.elementAt(1).bullets.indexOf(b);
				}
				else if (b.dirY == -4 && players.elementAt(0).playerRect.contains(b.bx, b.by)){
					removal = players.elementAt(1).bullets.indexOf(b);
				}
			}
		}
		if (removal != -1){
			players.elementAt(1).bullets.removeElementAt(removal);
			players.elementAt(0).alive = false;
			removal = -1;
		}
		//collision detection zombie and bullet
		
		//collision detection zombie and man
		
		//collision player and health
		if (displayHealth == true){
			for (Player p : players){
				if (p.alive == true && p.playerRect.contains(healthRect)){
					if (players.elementAt(0).alive == false){
						displayHealth = false;
						players.elementAt(0).alive = true;
					}
					if (players.elementAt(1).alive == false){
						displayHealth = false;
						players.elementAt(1).alive = true;
						
					}
				}
			}
		}
		
		//generate revive
		if ((!players.elementAt(0).alive || !players.elementAt(1).alive) && !healthTimerRunning && !displayHealth ){
			healthTimer = new Timer (3000, this);
			healthTimer.setActionCommand("reviveTimer");
			healthTimerRunning = true;
			healthTimer.start();
		}
		repaint();
		return null;
	}


	@Override
	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub
		if (arg0.getActionCommand().equals("threadTimer")){
			t.run();
			t2.run();
		}
		else if (arg0.getActionCommand().equals("reviveTimer")){
			healthTimer.stop();
			healthTimerRunning = false;
			if (displayHealth == false && (!players.elementAt(0).alive || !players.elementAt(1).alive)){
				healthX = (int) Math.round (Math.random() * screenSize.width - 10);
				healthY = (int) Math.round (Math.random() * screenSize.height - 10);
				displayHealth = true;
				healthRect = new Rectangle (healthX, healthY, 15,15);
			}
		}
		else if (arg0.getActionCommand().equals("Spawn Zombie")){
			enemy.add(new Zombie(players.elementAt(0),players.elementAt(1)));
			enemy.add(new Zombie(players.elementAt(0),players.elementAt(1)));
			
		}
	}





	@Override
	public void run() {
		// TODO Auto-generated method stub
		
	}
	
	
	
	
}

Thanks for any help.

Recommended Answers

All 9 Replies

It seems like your collision code starts running in its thread before you have created/added any players (Vector players is empty)?
ArrayIndexOutOfBoundsException: 1 >= 0 ... at Game.collision(Game.java:176)
line 176: players.elementAt(1)

but why is it running before I add the players, when I create the players before I even make the class I posted? also the timer is made after the players have been assigned before I start the timer. plus there is a one second delay on the timer to try to prevent these sorts of errors.

You call collision() on line 20 which is an initialiser. Players are added in the constructor. Initialisers get executed before the constructor is called

that fixed that problem. I moved the constructor under the players area, but now my players don't move. why is this? I changed the initial delay, and added a repaint

Is there a more effective way of reducing lag when many enemies on on the screen?

Well, I noticed that you are using vectors to store the players and enemies. However, because the Vector class is synchronized, it pays the price of synchronization which is a loss in speed. I would propose that you go back to using a single thread and switch from using vectors to using an ArrayList. ArrayLists are not synchronized and therefore will run faster than a Vector. However, I would advise you not to use ArrayLists in a multi-threaded environment because, due to the lack of synchronization, errors may occur when more than one thread acts upon the ArrayList simultaneously.

I can't promise this will fix anything, but it may at least help speed it up a little, especially if you have a lot of enemies in-game at once.

thanks. could you link me to an example that uses ArrayLists?

Honestly, I'm still learning how to use them myself, but this is what I found regarding ArrayLists vs Vectors. That page also links to this page which contains quite a few ArrayList examples. I can't guarantee that everything is accurate because I haven't had time to read through the entire page myself, but from what I skimmed, it seems legit.

thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.