How to restart this game???

I found a brilliant game on processing online. However, I want to learn how to restart a game. can anyone help me to do so?

---------------here is the code I found online that is the closest code that I have learned recently------------

ArrayList Targets; // ArrayList to put all targets in.
ArrayList scoreFire; // ArrayList to put all the pretty +1 and -1 notices above the score
int timeStamp;
int score;
int bullets;
int ammo = 2; // Do we have ammo? 0 means no, 1 means reloading, 2 means yes.
int reloadTime; // Reload time
int totalTargets; // Total targets were spawned.
int maxTargets = 50; // game ends umtil targets reach to 50.

void setup() {
  size(400, 400);
  smooth();
  //bg = loadImage("blue.jpg");
  frameRate(30);


  cursor(HAND); // make the cursor to hand

  Targets = new ArrayList();
  scoreFire = new ArrayList();

  timeStamp = second(); //either millis or seconds

  score = 0;
  bullets = 15;

//  minim = new Minim(this);
//  gun_shot = minim.loadSnippet("gun_shot.wav");
} 

//Draw Targets
class Target {
  // define properties
  float x, y, w, h; // position X, Y, width, height, color of each target.
  color c;

  // constructor
  Target(float init_x, float init_y, float init_width, float init_height, color init_c) {
    x = init_x; // Give the object's properties the values passed as arguments.
    y = init_y;
    w = init_width;
    h = init_height;
    c = init_c;
  }


  void display() {

    stroke(0);
    fill(c); // Fill the target with random color.
    ellipse(x, y, w, h); // Draw the random targets.
    noStroke();
    fill(255);
    ellipse(x, y, w-(w*30/100), h-(h*30/100));   
    noStroke();
    fill(255, 0, 0);
    ellipse(x, y, w-(w*60/100), h-(h*60/100));
    fill(0);
   textSize(15);
   text("Shoot the Targets to get the highest score: ", 10, 50 );
  }
} 

///Make ScoreFire
class scoreFire {
  //define properties
  float x = 370;
  float y = height-20;
  float a = 255;

  // constructor
  scoreFire() {
  }

  void display() {
    fill(255, a);
    textSize(12);
    text("+1", x, y);
  }
}

void draw() {
  background(255);


  //Display target
  for (int i = 0; i < Targets.size(); i++) {
    Target t = (Target) Targets.get(i);
    t.display(); //target to display
  }

  // Display scoreFire
  for (int i = 0; i < scoreFire.size(); i++) {
    scoreFire s = (scoreFire) scoreFire.get(i);
    s.display();
    if (s.y > height-40) {
      s.y--;
    } else {
      scoreFire.remove(i);
    }
  }

  // Counter(count)
  int passedTime = millis() - timeStamp;

  if (passedTime >= random(300, 4000) && totalTargets < maxTargets) { // If 0.5 to 2 seconds have passed since the last target was placed..
    int diameter = int(random(35, 65));
    //add some targets
    Targets.add(new Target(random(0, width), random(0, height), diameter, diameter, color(random(0, 255), random(0, 255), random(0, 255))));
    totalTargets++; //totalTargets increase when more targets are added 
    timeStamp = millis(); // Reset the timer.
  }


  //removing targets until they have 6
  if (Targets.size() == 6) { // If there's 6 targets on screen 
    Targets.remove(0); // Remove the firsr target
  }

  //Printing Score:
  if (totalTargets < maxTargets) {
    noStroke();
    fill(30, 40, 90, 200);
    rect(0, height-20, width, 20); //making a small box at the bottom 
    fill(255);
    textSize(12);
    text("SCORE: " + score, 10, height-5);

    //Printing in Box:
    fill(255);
    textSize(12);
    text("BULLETS: " + bullets, 100, height-5);
  }


  //Reloading the bullets
  if (ammo == 0 && totalTargets < maxTargets) {
    textSize(30);
    fill(255, 0, 0);
    text("Press[R] to RELOAD!", width*0.1, height*0.5);
  }

  //when reloading the bullets
  int timeSinceReload = millis() - reloadTime;
  if (timeSinceReload > 3000 && ammo == 1) {
    ammo = 2;
    bullets = 10;
  }

  //game over
  if (totalTargets >= maxTargets) {
    // Remove remaining targets
    for (int i = 0; i < Targets.size(); i++) {
      Target s = (Target) Targets.get(i);
      Targets.remove(i);
    }

    // End game text
    textSize(32);
    fill(255);
    text("Game over!", width*0.25, height*0.4);
    text("You scored: " + score, width*0.20, height*0.5);
  }

} // end of draw()

void mousePressed() {
  if (bullets > 0 && ammo != 1 && ammo != 0) {
    bullets--;
    for (int i = 0; i < Targets.size(); i++) {
      Target t = (Target) Targets.get(i);
      float distance = dist(mouseX, mouseY, t.x, t.y);

      if (distance < t.w*0.5) {
        Targets.remove(i);
        score++;
        scoreFire.add(new scoreFire());
      }
    }
  } else if (bullets <= 0 && ammo != 1) {
    ammo = 0;
  }
  //gun_shot.play(0);
}




void keyPressed() {
  if (key == 'r' || key =='R' & ammo != 1) {
    ammo = 1;
    reloadTime = second();
  }
}

Thanks guys!

Answers

  • Please highlight your code then press CTRL + K to fix it.

  • Have a function (eg. named reset()) that put the global variables to their default values. Call it in setup(), and when you want to reset your game.

  • ^ thx, but can you give me an example please D: i have a hard time to understand these stuff >< hope you can help me >~< thx

  • edited October 2013
    I tried to do like this in setup()
    ------------------------------
        void setup() {
          size(400, 400);
          smooth();
          bg = loadImage("blue.jpg");
          frameRate(30);
    
    
          cursor(HAND); // make the cursor to hand
    
          Targets = new ArrayList();
          scoreFire = new ArrayList();
    
          timeStamp = second(); //either millis or seconds
    
          score = 0;
          bullets = 15;
    
          reset();
        } 
    
    --------------and I created a void reset() and put my global variables in it, but it doesnt work--------------
    
        void reset() {
          PImage bg;
    
    
        ArrayList Targets; // ArrayList to put all targets in.
        ArrayList scoreFire; // ArrayList to put all the pretty +1 and -1 notices above the score
        int timeStamp;
        int score;
        int bullets;
        int ammo = 2; // Do we have ammo? 0 means no, 1 means reloading, 2 means yes.
        int reloadTime; // Reload time
        int totalTargets; // Total targets were spawned.
        int maxTargets = 50; // game ends umtil targets reach to 50.
        }
    
    ------This is where I call reset() ------
        void keyPressed() {
          if (key == 'r' || key =='R' & ammo != 1) {
            ammo = 1;
            reloadTime = second();
          }
           if (key == '' ) {
             reset();
        }
        }
    
  • Don't (re)declare the global variables in the reset() function! Keep them global.

    I meant just do something like:

    void reset() {
    Targets.clear(); // Empty the list
    scoreFire.clear();
    timeStamp = 0;
    score = 0;
    bullets = 0;
    ammo = 2;
    reloadTime = 0;
    totalTargets = 0;
    maxTargets = 50;
    }
    
  • like this, also i changed color of game over message and '+1' scoring so you can see them.

    ArrayList Targets = new ArrayList(); // ArrayList to put all targets in.
    ArrayList scoreFire = new ArrayList(); // ArrayList to put all the pretty +1 and -1 notices above the score
    int timeStamp;
    int score;
    int bullets;
    int ammo = 2; // Do we have ammo? 0 means no, 1 means reloading, 2 means yes.
    int reloadTime; // Reload time
    int totalTargets; // Total targets were spawned.
    int maxTargets = 50; // game ends umtil targets reach to 50.
    
    void setup() {
      size(400, 400);
      smooth();
      //bg = loadImage("blue.jpg");
      frameRate(30);
    
      cursor(HAND); // make the cursor to hand
    
      reset();
      //  minim = new Minim(this);
      //  gun_shot = minim.loadSnippet("gun_shot.wav");
    } 
    
    //Draw Targets
    class Target {
      // define properties
      float x, y, w, h; // position X, Y, width, height, color of each target.
      color c;
    
      // constructor
      Target(float init_x, float init_y, float init_width, float init_height, color init_c) {
        x = init_x; // Give the object's properties the values passed as arguments.
        y = init_y;
        w = init_width;
        h = init_height;
        c = init_c;
      }
    
    
      void display() {
    
        stroke(0);
        fill(c); // Fill the target with random color.
        ellipse(x, y, w, h); // Draw the random targets.
        noStroke();
        fill(255);
        ellipse(x, y, w-(w*30/100), h-(h*30/100));   
        noStroke();
        fill(255, 0, 0);
        ellipse(x, y, w-(w*60/100), h-(h*60/100));
        fill(0);
        textSize(15);
        text("Shoot the Targets to get the highest score: ", 10, 50 );
      }
    } 
    
    ///Make ScoreFire
    class scoreFire {
      //define properties
      float x = 370;
      float y = height-20;
      float a = 255;
    
      // constructor
      scoreFire() {
      }
    
      void display() {
        fill(50);
        textSize(12);
        text("+1", x, y);
      }
    }
    
    void draw() {
      background(255);
    
    
      //Display target
      for (int i = 0; i < Targets.size(); i++) {
        Target t = (Target) Targets.get(i);
        t.display(); //target to display
      }
    
      // Display scoreFire
      for (int i = 0; i < scoreFire.size(); i++) {
        scoreFire s = (scoreFire) scoreFire.get(i);
        s.display();
        if (s.y > height-40) {
          s.y--;
        } 
        else {
          scoreFire.remove(i);
        }
      }
    
      // Counter(count)
      int passedTime = millis() - timeStamp;
    
      if (passedTime >= random(300, 4000) && totalTargets < maxTargets) { // If 0.5 to 2 seconds have passed since the last target was placed..
        int diameter = int(random(35, 65));
        //add some targets
        Targets.add(new Target(random(0, width), random(0, height), diameter, diameter, color(random(0, 255), random(0, 255), random(0, 255))));
        totalTargets++; //totalTargets increase when more targets are added 
        timeStamp = millis(); // Reset the timer.
      }
    
    
      //removing targets until they have 6
      if (Targets.size() == 6) { // If there's 6 targets on screen 
        Targets.remove(0); // Remove the firsr target
      }
    
      //Printing Score:
      if (totalTargets < maxTargets) {
        noStroke();
        fill(30, 40, 90, 200);
        rect(0, height-20, width, 20); //making a small box at the bottom 
        fill(255);
        textSize(12);
        text("SCORE: " + score, 10, height-5);
    
        //Printing in Box:
        fill(255);
        textSize(12);
        text("BULLETS: " + bullets, 100, height-5);
      }
    
    
      //Reloading the bullets
      if (ammo == 0 && totalTargets < maxTargets) {
        textSize(30);
        fill(255, 0, 0);
        text("Press[R] to RELOAD!", width*0.1, height*0.5);
      }
    
      //when reloading the bullets
      int timeSinceReload = millis() - reloadTime;
      if (timeSinceReload > 3000 && ammo == 1) {
        ammo = 2;
        bullets = 10;
      }
    
      //game over
      if (totalTargets >= maxTargets) {
        // Remove remaining targets
        Targets.clear();
    
        // End game text
        textSize(32);
        fill(180);
        text("Game over!", width*0.25, height*0.4);
        text("You scored: " + score, width*0.20, height*0.5);
      }
    } // end of draw()
    
    void mousePressed() {
      if (bullets > 0 && ammo != 1 && ammo != 0) {
        bullets--;
        for (int i = 0; i < Targets.size(); i++) {
          Target t = (Target) Targets.get(i);
          float distance = dist(mouseX, mouseY, t.x, t.y);
    
          if (distance < t.w*0.5) {
            Targets.remove(i);
            score++;
            scoreFire.add(new scoreFire());
          }
        }
      } 
      else if (bullets <= 0 && ammo != 1) {
        ammo = 0;
      }
      //gun_shot.play(0);
    }
    
    
    
    
    void keyPressed() {
      if (key == 'r' || key =='R' & ammo != 1) {
        ammo = 1;
        reloadTime = second();
      }
    
      if (key == 'n') {
        reset();
      }
    }
    
    void reset() {
      timeStamp = second(); //either millis or seconds
      score = 0;
      bullets = 15;
      Targets.clear();
      scoreFire.clear();
      totalTargets = 0;
      ammo = 2;
      reloadTime = 0;
    }
    
  • How about the code down here? 
    it has more complicated variables with those PVector and arrayList...
    it doesnt look like the one as before, obviously it's a harder version. 
    How do I reset this then? I tried to put the variable in void reset() at the bottom, but it doesnt work. ( and please look for the cap letter where it's what I want to call the reset())
    
    This is not all of the code, just the part where we want to put the reset()
    

    Thank You. You really taught me a lot! I am appreciated!

    -------------------------------
    
    
     Rocket player; 
        PImage img;
    
        float speed = 2; // Speed of player movement 
    
        // Different vectors to move player left and right
        PVector upForce = new PVector(0, -0.5*speed); // Moves Rocket straight up
        PVector downForce = new PVector(0, 0.5*speed); // Moves Rocket straight down
        PVector leftForce = new PVector(-0.5*speed, 0);
        PVector rightForce = new PVector(0.5*speed, 0);
    
        boolean up, left, right, down, fire; // Which key is currently press (fire correspoonds to up key or space key)
    
        int addBossEnemy = 90; // Delay, in frame, between adding enemies
        int addBasicEnemy = 80;
    
        ArrayList<BossEnemy> boss = new ArrayList<BossEnemy>(); // List containing all the enemies
        ArrayList<BasicEnemy> enemy = new ArrayList <BasicEnemy>();
    
    
    ------------I TIRED TO RESET THE GAME HERE----------------
        void keyPressed() {
        //  if (key== 'r' || key=='R') {
        //    reset();
        //  }
        //  
    
          if (key == CODED) {
            if (keyCode == LEFT) {
              left = true;
            }
            else if (keyCode == RIGHT) { 
              right = true;
            }
            else if (keyCode == UP) {
              up = true;
            }
            else if (keyCode == DOWN) {
              down = true;
            }
          } 
          else {
            if (key == ' ') {
              fire = true;
            }
          }
        }
    
        void keyReleased() {
          if (key == CODED) {
            if (keyCode == LEFT) { 
              left = false;
            }
            else if (keyCode == RIGHT) { 
              right = false;
            }
            else if (keyCode == UP) { 
              up = false;
            }
            else if (keyCode == DOWN) {
              down = false;
            }
          } 
          else {
            if (key == ' ') { 
              fire = false;
            }
          }
        }
    
        void setup() {
          size(800, 600);
          stroke(200);
          strokeWeight(2);
          fill(63);
    
          player = new Rocket(new PVector(width/2, height - 50)); // Create the player object
          img = loadImage("space4.jpg");
          reset();
        }
    
        void draw() {
    
    
          background(img);
          //    for (int i = 0; i < boss.size(); i++) { //outer loop
          //    //get the current ball in the loop, the ball at position i 
          //    BossEnemy myboss  = boss.get(i);
          //    for (int j = i + 1; j < boss.size(); j++) { //inner loop Particle otherParticle = particles.get(j);
          //      if (myboss.collision(BossEnemy other)) {
          //        myboss.resolveCollision(BossEnemy other);
          //      }
          //    }
          //    //call the update method of the Particle class curParticle.update();
          //    //call the draw method of the Particle class 
          //    myboss.draw();
          //  }
    
          // Move the player or fier accoring to which keys are pressed
          if (up) { 
            player.move(upForce);
          }
    
          if (down) {
            player.move(downForce);
          }
          if (right) { 
            player.move(rightForce);
          }
    
          if (left) { 
            player.move(leftForce);
          }
          if (fire) { 
            player.fireMissile();
          }
    
          // Add an enemy to the screen after a certain delay
          if (frameCount % addBossEnemy == 0) {
            boss.add( new BossEnemy(new PVector(random(64, width - 128), -64)) );
            if (addBossEnemy > 20) {
              addBossEnemy--;
            }
          }
    
          if (frameCount % addBasicEnemy == 0) {
            enemy.add( new BasicEnemy(new PVector(random(64, width - 128), -64)) );
            if (addBasicEnemy > 20) {
              addBasicEnemy--;
            }
          }
    
          //draw bossenemies
          for (int i = 0; i < boss.size(); i++) {
            BossEnemy b = boss.get(i);
            b.update();
            b.draw();
    
            // Check for collision between player and enemies
            if (b.collision(player)) {
              player.hit();
            }
          }
    
          //draw basic enemies
          for (int s = 0; s < enemy.size(); s++) {
            BasicEnemy e = enemy.get(s);
            e.update();
            e.draw();
    
            // Check for collision between player and basicenemies
            if (e.collision(player)) {
              player.hit();
            }
          }
    
          //update and draw player
          player.update();
    
          //draw health bar and score HUD
          drawHealthBar();
          drawScore();
    
          // Game over if health is <= 0
          if (player.healthPercentage <= 0) {
            gameOver();
          }
        }
        ------------------AND I TRIED TO RESET THE GAME IN HERE-------------
        void gameOver() {
          background(255);
          text("Game Over", width/2 - 40, height/2);
          text("Press 'R/r' to restart", width/2, height/2+ 50);
        //  if keyPressed (key== 'r' || key=='R') {
        //    reset();
        //  }
          if (keyPressed) {
            if (key == 'r' || key == 'R') {
              reset();
            }
          }
        }
    
        void drawScore() {
          text("SCORE: " + player.score, width - 100, 40);
        }
    
        void drawHealthBar() {
          int healthBarWidth = 200;
          pushMatrix();
          strokeWeight(3);  
          stroke(255);
          fill(0, 64);
          translate(20, 50);
          fill(255);
          text("LIFE ", 0, -20);
          rect(0, 0, healthBarWidth, 20); //container for health
          fill(255, 0, 0, 255);
          rect(0, 0, healthBarWidth * player.healthPercentage, 20); //health bar
          popMatrix();
        }
    
        void reset() {
          speed = 2;
          addBossEnemy = 90; // Delay, in frame, between adding enemies
          addBasicEnemy = 80;
          boss.add( new BossEnemy(new PVector(random(64, width - 128), -64)) );
          enemy.add( new BasicEnemy(new PVector(random(64, width - 128), -64)) );
        }
    
Sign In or Register to comment.