#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Posts
    65
    Rep Power
    2

    How to restart in java japplet?


    how to restart a game? problem with my code is that when it restarts it double the enemy. so there are 10 enemies and lets say player dies than user restart and now there are 20 enemies and so on.....

    in start method i am create 10 enemies and storing in arraylist
    Code:
    public void start()
    {
    for(int i = 0; i < 10; i++){  
        enemyObject = new Enemy(10*i,10);
        enemyStore.add(enemyObject);    //store in array
    }
    }
    in here i am making enemy move, collision etc and if enemy is dead than i am remooving it from arraylist
    Code:
    public void actionPerformed(ActionEvent e)
    {
    	for(int i = 0; i < enemyStore.size(); i++){       
    		enemyObject = (Enemy)enemyStore.get(i);
    			if(!enemyObject.getDead()){               //if enemy is not died
    				//make enemy move, collision etc... here
                                    ....
    			}
    			else{           //remove enemy and create another one
    				enemyStore.remove(i);
    				enemyObject = new Enemy(10*i, 10); //create enemy
    				enemyStore.add(enemyObject);                                               //store in array
    			}
    		}
    }

    in paint method paint enemy
    Code:
    public class Display extends JPanel
    {
        public void paintComponent(Graphics g){	
    	super.paintComponent(g);
             
    	for(int i = 0; i < enemyStore.size(); i++){      //PAINT ENEMY
    		enemyObject = (Enemy)enemyStore.get(i);
    		enemyObject.paint(g);
    	}
        }
    }

    in there if player dies than remove all enemies in arraylist and restart
    Code:
    public void mouseClicked(MouseEvent e)
    {
    if(playerObject.getDead()){
    	if(e.getX() > bx && e.getX() < bx + bw)	{
    		if(e.getY() > by && e.getY() < by + bh){
    			for(int i = 0; i < enemyStore2.size(); i++){
    				enemyStore2.remove(i);	
    			}		
    			start();
    		 }
    	 }
      }
    }
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2007
    Posts
    765
    Rep Power
    929
    Before you call start(), you clear the enemyStore2 (and I don't think you actually succeed there since .size() changes as you remove elements--there is probably a .clear() method to remove everything at once), but in the start() method (and everywhere else) you're working from the enemyStore list. (BTW, it would probably be much simpler just to discard the whole list and do an "enemyStore = new ArrayList" in start.)
    sub{*{$::{$_}}{CODE}==$_[0]&& print for(%:: )}->(\&Meh);

IMN logo majestic logo threadwatch logo seochat tools logo