Results 1 to 7 of 7
  1. #1
    bakriawad is offline Member
    Join Date
    Apr 2013
    Posts
    22
    Rep Power
    0

    Default ArrayList problem

    Hi

    I have made a game of a space craft shooting down enemy space crafts, i have used the ArrayList to allow new missiles and enemy crafts to appear, and the game runs perfectly... well not perfectly since the ArrayList just bugs and causes a crash, here is the Exception:

    Java Code:
    0  65
    0  66
    0  67
    java.awt.Rectangle[x=457,y=44,width=18,height=10]+java.awt.Rectangle[x=472,y=50,width=20,height=10]
    0  1
    Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    	at java.util.ArrayList.rangeCheck(Unknown Source)
    	at java.util.ArrayList.get(Unknown Source)
    	at spaceCraft.MBoard.checkcoll(MBoard.java:151)
    	at spaceCraft.MBoard.actionPerformed(MBoard.java:192)
    	at javax.swing.Timer.fireActionPerformed(Unknown Source)
    	at javax.swing.Timer$DoPostEvent.run(Unknown Source)
    	at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    	at java.awt.EventQueue.access$200(Unknown Source)
    	at java.awt.EventQueue$3.run(Unknown Source)
    	at java.awt.EventQueue$3.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue.dispatchEvent(Unknown Source)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.run(Unknown Source)
    the numbers are from the loop which checks for a collesion of a missile with a space craft, missiles are on the left and crafts on the right.

    the problem is that it suddenly crashes, even after i take down many other space crafts, and rarely i get to eliminate the enemy completly.

    the crash tends to always happen after a collision occurs, please help.
    Code:

    Board:
    Java Code:
    package spaceCraft;
    
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Rectangle;
    import java.awt.Shape;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.image.ImageObserver;
    import java.util.ArrayList;
    
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    
    
    public class MBoard extends JPanel implements ActionListener
    {
    		
        private Timer timer;
    
    	private MCraft craft = new MCraft();
    	private MMissile mm;
    //	private MAliens ma = new MAliens();
    
    	
    	private Image aimg, mimg;
    	private JFrame f;
    	private TAdapter t;
    	
    	private ArrayList aAL = new ArrayList();
    	private ArrayList mAL;
    	private int xx, yy;
    	private int scrWidth;
    	
    	private boolean ingame;
    	
    //	private ArrayList aAL, mAL;
    	
    	private Rectangle r1,r2;
    	
    	private int pos[][] = 
    		{ 
    	        {2380, 29}, {2500, 59}, {1380, 89},
    	        {780, 109}, {580, 139}, {680, 239}, 
    	        {790, 259}, {760, 50 }, {790, 150},
    	        {980, 209}, {560, 45 }, {510, 70 },
    	        {930, 159}, {590, 80 }, {530, 60 },
    	        {940, 59 }, {990, 30 }, {920, 200},
    	        {900, 259}, {660, 50 }, {540, 90 },
    	        {810, 220}, {860, 20 }, {740, 180},
    	        {820, 128}, {490, 170}, {700, 30 }
    	     };
    	
    	     
    	{
    		
    		t = new TAdapter();
    		
    		
    		f  = new JFrame("Space Craft v1");
    		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		f.setBounds(100, 100, 800, 630);
    		f.setVisible(true);
    		f.setResizable(false);
    		f.add(this);
    		scrWidth = f.getWidth();
    		
    		setFocusable(true);
    		setVisible(true);
    		setBackground(Color.BLACK);
    		addKeyListener(new TAdapter());
    		
    		
    		
            timer = new Timer(10, this);
            timer.start();
            ingame = true;
            repaint();
            
            
            for(int i=0; i<100; i++)
            {
            	aAL.add(new MAliens());
            }
            
            
    	}
    	
    
    	public void paintComponent(Graphics g)				
    	{
    		super.paintComponent(g);
    		
    		mAL = craft.getAL(); 
    		
    		
    		Graphics2D gfx = (Graphics2D)g; 
    		
    		gfx.drawImage(craft.getImg(), craft.getX(), craft.getY(), this);
    		for(int i=0; i<mAL.size(); i++)
    		{
    			MMissile m = (MMissile) mAL.get(i);
    			
    			gfx.drawImage(m.getImage(), m.getX(), m.getY(), this);
    			m.setX(m.getX()+2);
    			if(m.getX()>800)
    			{ 
    				mAL.remove(i);
    				craft.setMALS(mAL.size());
    			}
    		}
    		
    		for(int i=0; i<aAL.size(); i++)
    		{
    			MAliens ma = (MAliens) aAL.get(i);
    			gfx.drawImage(ma.getImg(),ma.getX(),ma.getY(),null);
    			ma.move();
    		}
    
    		
    
    	}
    
    	public int getScrWid() { return scrWidth;}
    	
    	
    	public void checkcoll()
    	{
    		
    	//	ArrayList mAL = craft.getAL();
    		xx = mAL.size();
    		yy = aAL.size();
    		
    		for(int i=0; i<xx; i++)
    			{
    			
    				for(int j=0; j<yy; j++)
    				{
    					
    					System.out.println(i+"  "+j+"   "+mAL.size());
    					MMissile m = (MMissile) mAL.get(i);
    					MAliens ma = (MAliens) aAL.get(j);
    					
    					r1 = m.getBounds();
    					r2 = ma.getBounds();
    					
    					
    					if(r1.intersects(r2)) 
    					{
    						mAL.remove(i);
    						aAL.remove(j);
    						System.out.println(r1+"+"+r2);
    						
    						xx = mAL.size();
    						yy = aAL.size();
    				//		if(i!=0) i--;
    				//		if(j!=0) j--;
    						
    						i=0;
    						j=0;
    						if(aAL.size()==0) {timer.stop(); ingame = false;}
    					}	
    				}
    	
    				
    			}
    		
    	
    	}
    
    	public void actionPerformed(ActionEvent e) 	
    	{
    		craft.move();
    //		ma.move();
    		
    //		for (int i=0; i<mAL.size(); i++)
    			{
    			//	m.move();
    			}
    		
    		
    		checkcoll();
    		repaint();
    		
    		if(aAL.size()==0)
    		{
    			JOptionPane.showInternalConfirmDialog(null,"Well Done, you WIN!");
    		}
    		
    	}
    
    	
    	   private class TAdapter extends KeyAdapter
    	   {
    
    	        public void keyReleased(KeyEvent e) 
    	        {
    
    	            craft.keyRelease(e);
    	            repaint();
    	        }
    
    	        public void keyPressed(KeyEvent e) 
    	        {
    
    	            craft.KeyPresse(e);
    	            repaint();
    	        }
    	     
    	   }
    	   
    	   
    	   public int getMAL(){return mAL.size();}
    
    }
    Missile:
    Java Code:
    package spaceCraft;
    
    import java.awt.Image;
    import java.awt.Rectangle;
    import java.util.Random;
    
    import javax.swing.ImageIcon;
    
    public class MMissile 
    {
    
    	
    	private String missile = "\\missile.png";
    //	private String missile = "sword.jpg";
    	private Image img;
    	private int height, width;
    	private int misSpeed = 2;
    	private int x, y, ox, oy;
    	private MCraft craft = new MCraft();
    
    	boolean eos;
    	
    	
    	public MMissile(int xxx, int yyy) 
    	{
    		ImageIcon ii = new ImageIcon(getClass().getResource(missile));
    		img = ii.getImage(); 
    		height = img.getHeight(null);
    		width = img.getWidth(null);
    		
    		x = xxx;
    		y = yyy;
    		
    
    	}
    	
    	
    	public Image getImage() { return img;}
    	public int getX() {return x;}
    	public int getY() {return y;}
    	public int getH() {return height;}
    	public void setX(int sx) {x = sx;}
    	public Rectangle getBounds(){return new Rectangle(x,y,width,height);}
    	
    	
    	
    	public void move()
    	{
    		x += 2;
    //		if (x > 800) {eos = false;}
    	}
    
    	
    	
    	
    	
    	
    	
    
    }
    
    }

    Craft(where missiles are called):
    Java Code:
    package spaceCraft;
    
    import java.awt.Color;
    import java.awt.Image;
    import java.awt.Rectangle;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.util.ArrayList;
    
    import javax.swing.ImageIcon;
    import javax.swing.JPanel;
    
    
    
    
    public class MCraft
    {
    
    	private String craft = "\\craft.png";
    
    	private int x = 1, y = 1;
    	private int dx = 0, dy = 0, width, height, mcnt=0;
    	private Image img;
    	private ArrayList mAL;
    	private MMissile m;
    	
    	private boolean unpressed = true;
    
    	
    	public MCraft()
    	{
    		ImageIcon ii = new ImageIcon(getClass().getResource(craft));
    		img = ii.getImage();
    		
    		height = img.getHeight(null);
    		width  = img.getWidth (null);
    		
    		mAL = new ArrayList();
    		
    		
    	}
    
    	//----------------------------------------------------------------
    	//--------------------------- Methods ----------------------------
    	
    	public void move()
    	{
    		x += dx;
    		y += dy;
    		
    		if(x < 0) {x = 0;}
    		if(y < 0) {y = 0;}
    		if(x > 600 - width)  {x = 600 - width;}
    		if(y > (600 - height)) {y = 600 - height;}
    	}
    
    	public int getX() {return x;}
    	public int getY() {return y;}
    	public Image getImg() {return img;}
        public int getWidth () {return width; }
        public int getHeight() {return height;}
    	public ArrayList<MMissile> getAL() {return mAL;}
    	public Rectangle getBounds() {return new Rectangle(x,y,width,height);}
    	public void setMALS(int i){mcnt=i;}    
    //	public void setMCnt(){mcnt = mcnt-1;}
        
        //------------------------------------------------------------------- 
        //------------------------ Action Listeners -------------------------
      
    	public void KeyPresse(KeyEvent e)
    	{
    		
    		int key = e.getKeyCode();
    		
    		if(key == KeyEvent.VK_SPACE) {if(unpressed=true)fire();unpressed=false;}
    		if(key == KeyEvent.VK_UP 	&& y>1)	 			{dy = -2;}
    		if(key == KeyEvent.VK_DOWN 	&& y<600 -height)	{dy = 2;}
    		if(key == KeyEvent.VK_LEFT 	&& x>1)				{dx = -2;}
    		if(key == KeyEvent.VK_RIGHT && x<800 - width)	{dx = 2;}	
    	}
    	
    	
    	public void fire()
    	{
    		
    
    		if(unpressed=true)
    		{
    			if(mcnt < 30)
    			{
    				mAL.add(new MMissile(x+width,y));
    			}
    			unpressed = false;
    		}
    
    	}
    	
    	
    	public void keyRelease(KeyEvent e)	
    	{
    		int key = e.getKeyCode();
    		
    		if(key == KeyEvent.VK_SPACE) {unpressed = true;}
    		if(key == KeyEvent.VK_UP)	 {dy = 0;}
    		if(key == KeyEvent.VK_DOWN)	 {dy = 0;}
    		if(key == KeyEvent.VK_LEFT)	 {dx = 0;}
    		if(key == KeyEvent.VK_RIGHT) {dx = 0;}
    	}
    
    	
    	
    
    }

    tried many things yet none seem to work, i thought when a missile is removed the loop don't get updated and cause it to try to get something that don't exist, but judging from the output that was not the case...
    tried to make it so that every time something collides with another it restarts the loop and that still hasn't fixed it.
    i thought there might be a call error since it gets the ArrayList from another class, however i could not pin point the mistake, so not sure if that is the cause...

    i appreciate your help

    P.S.
    i did not post all the classes since i thought they dont have anything to do with the problem.. just did not want overflow the page with codes.
    Last edited by bakriawad; 05-16-2013 at 02:45 PM.

  2. #2
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,646
    Rep Power
    5

    Default Re: ArrayList problem

    I'm not certain what is going on. You are modifying loop parameters and removing elements within a loop that you're iterating over. That may be causing some non-deterministic behavior. You may want to try a different construct using a while loop and label.

    Something like this:

    Java Code:
    whileLabel: 
         while (true) {
             int yy = b.size();
             if (yy == 0)
                break;
             
             int xx = a.size();
             for (int j = 0; j < xx; j++) {
                for (int k = 0; k < yy; k++) {
                   obja = a.get(j);
                   objb = b.get(k);
                   if (<some conditional>) {
                      a.remove(j);
                      b.remove(k);
                      continue whileLabel;
                   }
                }
             }
          }
    This may not solve your problem but I believe it is a tad clearer.

    Regards,
    Jim
    Last edited by jim829; 05-16-2013 at 03:32 PM.
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  3. #3
    bakriawad is offline Member
    Join Date
    Apr 2013
    Posts
    22
    Rep Power
    0

    Default Re: ArrayList problem

    As you said, that would not fix the problem at all since it was similar to what you have written and also without the continue argument, if you noticed i did say i tried some things, the parameter change was one of them...

    shall i post all the classes (or upload a .jar/,zip file if it makes it easier) for you to be able to run it and see what is the main problem???


    as i have said, it runs but suddenly stops after an intersect of some elements, so basically when something gets removed...
    i have run it many times and it seems to have the problem frequently at the 2nd element getting checked, sometimes a bit further than that but not always.

    something came to my mind is maybe an error occurs since missiles tend to get removed after they reach the end of the screen, however i was not able to think of a way to counter that, since the ArrayList gets updated and it becomes hard to trace them...

    so if there is a way to make a simple tracing function it would be nice....

  4. #4
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,646
    Rep Power
    5

    Default Re: ArrayList problem

    I believe the problem might be that you are modifying elements on the EDT in your paintComponent method and you may be modifying elements when in the main thread. This could cause problems if you are not synchronizing access to the same data structure which is being shared/accessed by two different threads.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  5. #5
    bakriawad is offline Member
    Join Date
    Apr 2013
    Posts
    22
    Rep Power
    0

    Default Re: ArrayList problem

    I have moved the Missile creating function from MCraft to MBoard where all the intersections and removals happens, so far game looks good.. but further testing is required... so it might seem to have synchronizing problems, or maybe something else...

    error tends to be where the missile is being checked, however, i ran the program and without me pressing anything it crashed... so i am not sure.

    ill post again to confirm it working or not

    thankx for the help :D

  6. #6
    bakriawad is offline Member
    Join Date
    Apr 2013
    Posts
    22
    Rep Power
    0

    Default Re: ArrayList problem

    I guess it was a problem of Syncronization...
    game works fine now.. no problems at all, the crashing stopped

    i solved it by moving the Calling missile method from MCraft.java to Board.java, so i did not have to update the one in MCraft.
    since the removing happens in Board nothing has to be updated in methods in any other classes.

    It can be locked now.

    Thanks all for the help.

  7. #7
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,646
    Rep Power
    5

    Default Re: ArrayList problem

    A lot of folks don't reply when their problem is solved. Thanks for letting me know.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

Similar Threads

  1. Map and ArrayList problem
    By Legaly in forum New To Java
    Replies: 4
    Last Post: 11-19-2012, 05:40 PM
  2. ArrayList problem
    By mathidioticz in forum New To Java
    Replies: 9
    Last Post: 02-04-2012, 06:39 PM
  3. Replies: 12
    Last Post: 07-07-2011, 08:49 PM
  4. Problem in ArrayList
    By justbeller in forum New To Java
    Replies: 8
    Last Post: 02-15-2011, 03:19 PM
  5. ArrayList problem
    By brian.baert in forum New To Java
    Replies: 8
    Last Post: 03-06-2010, 01:49 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •