Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Question 2 (13 points): Purpose: Practice with conditionals; practice with varia

ID: 3605744 • Letter: Q

Question

Question 2 (13 points):

Purpose: Practice with conditionals; practice with variables and good program design.

Degree of Di culty: Tricky

Your spaceship is being bombarded by asteroids! To survive, you must shoot down each asteroid before it hits your ship. Luckily for you, the asteroids are not too close to each other, so you will never have to deal with more than one asteroid at a time.

Your job is to write a simple rst-person asteroid-shooting game in Processing. The rules for the game are as follows:

Setting up the game: The game should be played on an 800x800 black canvas (it’s in outer space, after all).

When the game starts: An asteroid appears at a random location on the canvas (see the note below on generating random numbers). We will use a simple circle to represent the asteroid. Initially, the asteroid has a diameter of 0, but it should continually get bigger and bigger over time (representing the asteroid getting closer to the player - it’s like the player is in the cockpit of the spaceship). Also, the player’s score should be displayed on the canvas, and should initially be 0.

If the asteroid gets too big: Pick a reasonable “maximum” size for the asteroids (our solution uses a diam- eter of 100). If the asteroid ever reaches this size, the player’s ship has been hit and the game is over. The asteroid should turn red and stop growing, and a “Game Over” message should appear on the canvas.

If the player clicks on the asteroid before it gets too big: The asteroid is destroyed. Add 1 to the player’s score, and immediately create a new asteroid with diameter 0 at a new random location.

How to start

A central subtask for this problem is determining whether or not a given point (i.e. the point the user clicks with the mouse) is inside of a circle (i.e. the asteroid). You should tackle this task rst by writing the following function:

This inputs to this function are:

x, y: The coordinates of the point that was clicked

ast_x, ast_y: The coordinates of the asteroid’s center

ast_size: The diameter of the asteroid.
The function should return True if the point is inside the asteroid and False otherwise. Test this func-

tion before you go on! Once you are sure it is working, you can start adding the interactive parts of the program.

How to use random numbers

When setting up the coordinates of a new asteroid, you will need to generate random numers. Processing has a function called random() which can be used to do this. random() takes two numbers as arguments, and will return a random number in the given range. So for example, calling random(1, 5) will return a random number between 1 (inclusive) and 5 (exclusive). You can think of this like rolling a die: each time you call random(), it’s like you rolled the die once and got a single, random result. For this program, you should use the call random(50, 750) to generate asteroid coordinates that are still visible on the canvas.

What To Hand In: Your Processing sketch folder (named cmpt140_a5q2) compressed as a zip le (.zip). This folder should contain your Processing program as a .pyde le with the same name as the folder (i.e.cmpt140_a5q2.pyde) and a sketch.properties project le.

Evaluation:

0 marks for submitting nothing and/or les that cannot be opened. • -1 mark for lack of identi cation in the solution.
2 marks for creating and initializing asteroids correctly.
2 marks for asteroids growing over time correctly.

2 marks for program ending correctly when an asteroid hits the player. • 2 marks for correct program behaviour when asteroids are clicked.
2 marks for program correctly resets when ‘r’ is pressed.
1 mark for documenting code using comments and docstrings.

2 marks for good Model-View-Controller design

Must use PYTHON in processing

Score: 8 Game over!! Press 'r' to restart Figure 2: Game over screen when the asteroid is big enough

Explanation / Answer

1)Astreiod.java

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.util.Random;

public class Asteroid {
   private int xPos;
   private int yPos;
   private static int height = 30;       //height of the asteroid
   private static int width = 35;       //width of the asteroid
  
   public Asteroid(int x, int y)
   {
       Random r = new Random();
       xPos = 800 + r.nextInt(50);       //initial x position of the asteroid
       yPos = 50 + r.nextInt(700);       //initial y position of the asteroid
   }
  
   public void move() {
       xPos = xPos - 15;               //move the asteroid to the left by 15
   }
  
   public void draw(Graphics g) {
       g.setColor(Color.gray);
       g.fillOval(xPos, yPos, width, height);   //draws the asteroid as a gray oval  
   }
  
   public Point getPosition() {
       return new Point(xPos, yPos);       //returns the position of the asteroid
   }
}

2.Spaceship.java

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;

public class SpaceShip{
   private int xPos;
   private int yPos;
   private static int height = 50;       //height of the spaceship
   private static int width = 60;       //width of the spaceship
   private boolean shooting;
  
   public SpaceShip()
   {
       xPos = 0;               //initial x position
       yPos = 0;               //initial y position
       shooting = false;
   }
  
   public void move(int x, int y) {
       xPos = x;               //updated x position of the spaceship
       yPos = y;               //updated y position of the spaceship
   }
  
   public void setShooting(boolean value) {
       shooting = value;
   }
  
   public Boolean getShooting() {
       return Boolean.valueOf(shooting);
   }
  
   public Point getPosition() {
       return new Point(xPos, yPos);
   }
  
   public void draw(Graphics g, int laserlength) {
       g.setColor(Color.yellow);
       g.fillOval(xPos, yPos, width, height);       //spaceship body
       g.setColor(Color.red);
       g.fillOval(xPos + 35 , yPos + 10, 20, 8);       //red window on the spaceship
       g.drawLine(xPos, yPos + height/2, xPos + width, yPos + height/2);
       g.setColor(Color.blue);
       g.drawLine(xPos, yPos + height/2 + 3, xPos + width, yPos + height/2 + 3);
       g.drawLine(xPos, yPos + height/2 - 3, xPos + width, yPos + height/2 - 3);
       g.setColor(Color.red);
      
       if (shooting)
           g.drawLine(xPos + width, yPos + height/2, laserlength, yPos + height/2);       //spaceship's laser beam
   }
}

3)SpaceShipGame.java

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.Timer;


public class SpaceShipGame extends JPanel
{
   private SpaceShip s = new SpaceShip();
   private ArrayList<Asteroid> aster;       //Array list to store the asteroids
   private int score = 0;                   //Initial score = 0
   private int lifeleft = 3;               //Player starts with 3 lives
   private int timeleft = 10;               //Player starts with 10 seconds of time
   private int x, y;
   private Timer countTimer;               //Count down timer for the time remaining
   private Timer asterTimer;               //Timer to move the asteroids
   private int delay = 1000;
   private int delay2 = 90;
   private int shootX, shootY;               //Get coordinates of asteroids when shot by laser
   private int collideX, collideY;           //Get coordinates of asteroids when collided with the space ship


   public SpaceShipGame()
   {
      SpaceshipListener monitor = new SpaceshipListener();
      aster = new ArrayList<Asteroid>();
    
      for(int i=0; i<5; i++){
           aster.add(new Asteroid(x,y));
       }
      addMouseMotionListener(monitor);
      addMouseListener(monitor);
    
      countTimer = new Timer(delay, new CountdownTimer());
      asterTimer = new Timer(delay2, new AsteroidTimer());

      setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
      setBackground (Color.white);
      setPreferredSize(new Dimension(800, 800));
    
      countTimer.start();       //Starts the count down timer from 10 seconds
      asterTimer.start();       //Starts the timer to move the asteroids
   }

   public static void main (String[] args)
   {
      JFrame frame = new JFrame ("SpaceShip Game");
      frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

      frame.getContentPane().add (new SpaceShipGame());

      frame.pack();
      frame.setVisible(true);
   }

   public void paintComponent(Graphics g)
   {
      //draws the spaceship
      super.paintComponent(g);
      s.draw(g,800);
    
      //draws the asteroids
      for (Asteroid a : aster)
          a.draw(g);
    
      g.setColor(Color.red);
      //prints 'OH NO!!!' when the spaceship collides with an asteroid
      if(lifeleft>0 && timeleft>0 && s.getPosition().x==0 && s.getPosition().y==0){
        g.drawString("OH NO!!!", collideX, collideY);
      } else {
              g.drawString("", collideX, collideY);
      }
    
      //prints 'Score!!!' when the spaceship destroys an asteroid
      if(lifeleft>0 && timeleft>0 && s.getShooting()){
             g.drawString("Score!!!", shootX, shootY);
         } else {
                 g.drawString("", shootX, shootY);
         }
    
      if (lifeleft == 0 ){
          g.drawString("Score: " + score, 20, 40);
          g.drawString("Life: " + lifeleft, 20, 60);
          g.drawString("Time Remain: " + timeleft, 20, 80);
          g.drawString("Game Over", 400, 400);
      } else if (timeleft > 0){
          g.drawString("Score: " + score, 20, 40);
          g.drawString("Life: " + lifeleft, 20, 60);
          g.drawString("Time Remain: "+ timeleft, 20, 80);
      } else {
          g.drawString("Score: " + score, 20, 40);
          g.drawString("Life: " + lifeleft, 20, 60);
          g.drawString("Time Remain: " + timeleft, 20, 80);
          g.drawString("Game Over", 400, 400);
      }    
   }

   //Timer counting down from 10 seconds by every 1 second. Timer stops when time remaining = 0.
   private class CountdownTimer implements ActionListener{
       public void actionPerformed (ActionEvent event){
           if (timeleft > 0){
           timeleft --;
           }
         
           if (timeleft==0) {
               countTimer.stop();
               asterTimer.stop();
               aster.clear();
           }
           repaint();
       }
   }

   private class AsteroidTimer implements ActionListener{
       public void actionPerformed (ActionEvent event){
           for(int i=0; i<5; i++){
               aster.get(i).move();       //moves all 5 asteroids
             
               if(aster.get(i).getPosition().x < 0){
                   aster.remove(i);
                   aster.add(i, new Asteroid(x,y));       //removes and adds a new asteroid when 1 asteroid leaves the screen
               }
               if(aster.get(i).getPosition().x < s.getPosition().x+55
                       && aster.get(i).getPosition().y + 30 > s.getPosition().y
                       && aster.get(i).getPosition().y < s.getPosition().y + 50){
                   collideX = aster.get(i).getPosition().x;
                   collideY = aster.get(i).getPosition().y;
                   aster.remove(i);               //removes asteroid when collides with spaceship
                   s.move(0,0);                   //moves spaceship back to (0,0) after it collides with an asteroid
                   lifeleft--;                   //life remaining - 1 after the collision
                   aster.add(i, new Asteroid(x,y));       //adds a new asteroid after the collision
               }
               if(aster.get(i).getPosition().y < s.getPosition().y + 25
                       && aster.get(i).getPosition().y + 30 > s.getPosition().y + 25
                       && s.getShooting()){
                   shootX = aster.get(i).getPosition().x;
                   shootY = aster.get(i).getPosition().y;
                 
                   aster.remove(i);               //removes asteroid after it is shot by the laser
                   score = score + 1;           //updates the score when spaceship destroys an asteroid
                   aster.add(i, new Asteroid(x,y));       //adds a new asteroid after 1 asteroid is destroyed
               }
           }
           if (lifeleft == 0){
               asterTimer.stop();
               countTimer.stop();
               aster.clear();
           }
           repaint();
       }
   }

   private class SpaceshipListener implements MouseListener, MouseMotionListener
   {
      public void mouseMoved(MouseEvent event)
      {
         s.move(event.getX(), event.getY());       //gets and updates the spaceship's position
         repaint();
      }
    
      public void mousePressed(MouseEvent event)
      {
         s.setShooting(true);                   //draws the laser
         repaint();
      }

      public void mouseReleased(MouseEvent event)
      {
         s.setShooting(false);              
         shootX =0;
         shootY =0;
         repaint();
      }
      public void mouseDragged(MouseEvent event){}
      public void mouseClicked(MouseEvent event) {}
      public void mouseEntered(MouseEvent event) {}
      public void mouseExited(MouseEvent event) {}
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote