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
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
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
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
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(); } } } }