Esempio n. 1
0
 private void getVelocity() {
   vy = 3.0;
   vx = rgen.nextDouble(1.0, 3.0);
   if (rgen.nextBoolean(0.5)) {
     vx = -vx;
   }
 }
Esempio n. 2
0
 /** When mouse pressed: begin our fantastic game */
 public void mousePressed(MouseEvent e) {
   if (vx == 0) {
     vx = rgen.nextDouble(0.5, 1);
     vy = -1;
     if (rgen.nextBoolean() == true) {
       vx *= -1;
     }
   }
 }
Esempio n. 3
0
 public GLabel makeLetterLabel(int numDivs) {
   boolean get = randgen.nextBoolean();
   String ga;
   if (get) ga = "G";
   else ga = "A";
   GLabel getOrAvoid = new GLabel(ga);
   getOrAvoid.setFont(new Font("Cambria", Font.BOLD, 24));
   double locx = randgen.nextDouble(INDENT, getWidth() - getOrAvoid.getWidth());
   int whichdiv = randgen.nextInt(1, numDivs);
   double locy = whichdiv * getHeight() / numDivs;
   getOrAvoid.setLocation(locx, locy);
   return getOrAvoid;
 }
public class RandomCircles extends GraphicsProgram {

  /** Number of circles */
  private static final int NCIRCLES = 10;

  /** Minimum radius */
  private static final double MIN_RADIUS = 5;

  /** Maximum radius */
  private static final double MAX_RADIUS = 50;

  public void run() {
    for (int i = 0; i < NCIRCLES; i++) {
      double r = rgen.nextDouble(MIN_RADIUS, MAX_RADIUS);
      double x = rgen.nextDouble(0, getWidth() - 2 * r);
      double y = rgen.nextDouble(0, getHeight() - 2 * r);
      GOval circle = new GOval(x, y, 2 * r, 2 * r);
      circle.setFilled(true);
      circle.setColor(rgen.nextColor());
      add(circle);
    }
  }

  /* Private instance variable */
  private RandomGenerator rgen = RandomGenerator.getInstance();
}
Esempio n. 5
0
  /** getReady: Initialize the game */
  private void getReady() {

    // Make up the bricks
    double brickPerWidth =
        (getWidth() - DIST_BRICK_WALL * 2 - DIST_BRICK_BRICK * (NUM_BRICK_ROW - 1)) / NUM_BRICK_ROW;
    double brickPerHeight = BRICK_HEIGHT;
    double x_start = DIST_BRICK_WALL;
    double y_start;
    for (int i = 1; i <= NUM_BRICK_ROW; i++) {
      for (int j = 1; j <= NUM_BRICK_COL; j++) {
        y_start = 50 + (j - 1) * (DIST_BRICK_BRICK + brickPerHeight);
        GRect tmpbrick = new GRect(brickPerWidth, brickPerHeight);
        tmpbrick.setFilled(true);
        add(tmpbrick, x_start, y_start);
      }
      x_start += DIST_BRICK_BRICK + brickPerWidth;
    }

    // Make up the board
    board = new GRect(BOARD_WIDTH, BOARD_HEIGHT);
    board.setFilled(true);
    add(board, (getWidth() - BOARD_WIDTH) / 2, (getHeight() - 30));

    // Place the ball
    ball = new GOval(BALL_RADIUS * 2, BALL_RADIUS * 2);
    ball.setFilled(true);
    ball.setColor(Color.RED);
    add(ball, (getWidth() - BALL_RADIUS * 2) / 2, (getHeight() - 30 - BALL_RADIUS * 2));

    // Set up random generator
    rgen = RandomGenerator.getInstance();

    // Add Listeners
    addMouseListeners();
  }
  public void run() {

    /* Initialising variables. */
    int counter = 0;
    int currentMoney = 1;
    int totalMoneyInGame = 0;

    /* The main iteration for the St.Peterburg's game.
    If total money is > than 20 - ends the game. */
    while (totalMoneyInGame < 20) {

      /* Randoms flip boolean value for each stage of iteration */
      RandomGenerator r = RandomGenerator.getInstance();
      boolean flip = r.nextBoolean();

      /* Condition for the heads flip, if it's true - double current money */
      if (flip == true) {
        currentMoney *= 2;

        /* Condition for the streak of heads. If total money is >= 20 and current money is >=20,
        prints phrases and adds 1 to counter.
         */
        if (totalMoneyInGame >= 20 && currentMoney >= 20) {
          println("This game you earned $" + currentMoney);
          println("Your total is $" + totalMoneyInGame);
          counter++;
        }
        /* Condition for the tails. Prints current money phrase.
        Prints total money phrase and adds 1 to the counter.
        In the end initialize current money to the start bid.
         */
      } else {
        println("This game you earned $" + currentMoney);
        /* If current money >=1 adds them to the total money. */
        if (currentMoney >= 1) totalMoneyInGame = totalMoneyInGame + currentMoney;
        println("Your total is $" + totalMoneyInGame);
        counter++;
        currentMoney = 1;
      }
    }
    /* In the end of the game prints counter phrase */
    println("It took " + counter + " games to earn $20");
  }
  /**
   * The method which controls the movement the ball, check all the objects with which the ball is
   * faced and performs the appropriate actions to them
   */
  private boolean runBall() {
    double vx;
    double vy = SPEED_Y;
    boolean res = false;
    vx = rgen.nextDouble(1.0, 3.0); // randomly sets horizontal speed
    if (rgen.nextBoolean(
        0.5)) // with a 50 percent chance change the direction of movement of the ball
    vx = -vx;

    while (allDelBricks
        < NBRICK_ROWS * NBRICKS_PER_ROW) { // The game will not end until all the bricks
      GObject collider = getCollidingObject(); // The variable gets test result object
      vx = checkTheLeftAndRightWall(vx); // Check the collision of the ball on the side walls
      vy =
          checkTheTopWallAndPaddle(vy); // Check the collision of the ball on the ceiling and paddle
      vx =
          checkLeftAndRightWallOfPaddle(
              vx); // Check the collision of the ball with the side part of the paddle

      if (collider != null) { // If checkpoints are returned brick, it is then removed
        if (collider != paddle) {
          remove(collider);
          vy = -vy;
          allDelBricks++;
        }
      }
      ball.move(vx, vy);
      pause(TIME_PAUSE);
      if (ball.getY()
          > HEIGHT
              - (PADDLE_Y_OFFSET / 3)
              - BALL_RADIUS * 2) { // The game stops when the ball falls below the window
        res = false;
        return res;
      }
      res = true;
    }
    return res;
  }
Esempio n. 8
0
public class Craps extends ConsoleProgram {

  public void run() {
    // rgen.setSeed(23423);
    int total = rollTwoDice();
    if (total == 7 || total == 11) {
      println("That's a natural. You win");
    } else if (total == 2 || total == 3 || total == 12) {
      println("That's craps. You lose.");
    } else {
      int point = total;
      println("You point is " + point + ".");
      while (true) {
        total = rollTwoDice();
        if (total == point) {
          println("You made your point. You win.");
          break;
        } else if (total == 7) {
          println("That's a 7. You lose.");
          break;
        }
      }
    }
  }

  /* Rolls two dice and returns their sum. */
  private int rollTwoDice() {
    int d1 = rgen.nextInt(1, 6);
    int d2 = rgen.nextInt(1, 6);
    int total = d1 + d2;
    println("Rolling dice: " + d1 + " + " + d2 + " = " + total);
    return total;
  }
  /* Create an instance variable for the random number generator */
  private RandomGenerator rgen = RandomGenerator.getInstance();
}
Esempio n. 9
0
public class Breakout extends GraphicsProgram {

  /** Width and height of application window in pixels */
  public static final int APPLICATION_WIDTH = 400;

  public static final int APPLICATION_HEIGHT = 600;

  /** Dimensions of game board (usually the same) */
  private static final int WIDTH = APPLICATION_WIDTH;

  private static final int HEIGHT = APPLICATION_HEIGHT;

  /** Dimensions of the paddle */
  private static final int PADDLE_WIDTH = 60;

  private static final int PADDLE_HEIGHT = 10;

  /** Offset of the paddle up from the bottom */
  private static final int PADDLE_Y_OFFSET = 30;

  /** Number of bricks per row */
  private static final int NBRICKS_PER_ROW = 10;

  /** Number of rows of bricks */
  private static final int NBRICK_ROWS = 10;

  /** Separation between bricks */
  private static final int BRICK_SEP = 4;

  /** Width of a brick */
  private static final int BRICK_WIDTH =
      (WIDTH - (NBRICKS_PER_ROW - 1) * BRICK_SEP) / NBRICKS_PER_ROW;

  /** Height of a brick */
  private static final int BRICK_HEIGHT = 8;

  /** Radius of the ball in pixels */
  private static final int BALL_RADIUS = 10;

  /** Offset of the top brick row from the top */
  private static final int BRICK_Y_OFFSET = 70;

  /** Number of turns */
  private int endtrying = 0;

  /* Method: init() */
  /** Sets up the Breakout program. */
  public void init() {
    addMouseListeners();
  }

  /* Method: run() */
  /** Runs the Breakout program. */
  public void run() {

    buildBricks();
    paddle();
    ball();
    startApp();
  }
  // Creating bricks as requested in colors and separators
  private void buildBricks() {
    for (int x = 0; x < NBRICK_ROWS; x++) {
      for (int j = 0; j < NBRICKS_PER_ROW; j++) {
        reak = new GRect(BRICK_WIDTH, BRICK_HEIGHT);
        reak.setFilled(true);
        reakCounter++;
        // adding bricks from the start of the line and increasing by j the width and separator
        add(reak, +(BRICK_SEP + BRICK_WIDTH) * j, BRICK_Y_OFFSET + (BRICK_SEP + BRICK_HEIGHT) * x);

        // Setting color to the bricks depending on brick row number
        switch (x) {
          case 0:
          case 1:
            reak.setColor(Color.red);
            break;
          case 2:
          case 3:
            reak.setColor(Color.orange);
            break;
          case 4:
          case 5:
            reak.setColor(Color.yellow);
            break;
          case 6:
          case 7:
            reak.setColor(Color.green);
            break;
          case 8:
          case 9:
            reak.setColor(Color.cyan);
            break;
        }
      }
    }
  }
  // Creating Paddle
  private void paddle() {
    // declaring variables for more clarity and to be used in other method
    baddleY = getHeight() - PADDLE_Y_OFFSET - PADDLE_HEIGHT;
    baddleX = (WIDTH - PADDLE_WIDTH) / 2;
    // creating the paddle
    baddle = new GRect(PADDLE_WIDTH, PADDLE_HEIGHT);
    baddle.setFilled(true);
    add(baddle, baddleX, baddleY);
  }

  public void mouseMoved(MouseEvent e) {
    // tracking the mouse inside the window and ignoring it if it's out of
    // window perspective, which is requested in assignment handout.
    // mouse is almost in the middle of the paddle.
    // height remains the same all time

    if ((e.getX() < WIDTH - PADDLE_WIDTH / 2) && (e.getX() > PADDLE_WIDTH / 2)) {
      baddle.setLocation(e.getX() - PADDLE_WIDTH / 2, baddleY);
    }
  }
  // Creating the ball above the paddle :D
  private void ball() {
    ballY = (HEIGHT - BALL_RADIUS) / 2;
    ball = new GOval(BALL_RADIUS, BALL_RADIUS);
    ball.setFilled(true);
    add(ball, (WIDTH - BALL_RADIUS) / 2, ballY);
  }

  public void startApp() {
    waitForClick();
    getVelocity();
    while (true) {
      moveBall();
      // delay time, reduced as the player is about to end the game to increases it's difficult
      pause(delay + reakCounter / 25);
      if (reakCounter == 0) {
        GLabel win = new GLabel("YOU WIN!!");
        add(win, (getWidth() - win.getWidth()) / 2, HEIGHT / 2);
      }
    }
  }

  private void moveBall() {
    ball.move(vx, vy);
    /*
     * top side reflection
     */
    if (ball.getY() - ball.getHeight() / 2 < 0) {
      vy = -vy;

    }
    /*
     * sides reflect
     */
    else if (ball.getX() > WIDTH - ball.getHeight() || ball.getX() - ball.getHeight() / 2 < 0) {
      vx = -vx;

    }
    /*
     * ending game if ball goes beyond the paddle, with 3 tries
     *  and restarting it b4 the 3 tries
     */
    else if (ball.getY() > HEIGHT) {
      endtrying++;
      if (endtrying >= 3) {
        removeAll();
        GLabel end = new GLabel("YOU LOST!!");
        add(end, (getWidth() - end.getWidth()) / 2, getHeight() / 2);
      }
      // restart part
      else {
        removeAll();
        run();
      }
    }
    // getting what's on sides of the ball, and starting to handle it
    GObject row = collectSides();

    if (row == baddle) {
      /*
       * to test Y coordinates for ball and paddle
       * println( baddle.getY()+ "|" +  ball.getY());
       * turned out to be that there's 19 pixel between ball.y and paddle.y; fixing that with if
       */

      if (ball.getY() > baddle.getY() - BALL_RADIUS) {
        vy = -vy;
        bounceClip.play();
        /*
         * glue issue fix, move the ball above the paddle, so that it doesn't reverse again
         */
        if (row == baddle) {
          ball.move(0, -PADDLE_HEIGHT);
        }
      }

    }
    /* here removing object which is brick, then subtracting the counter, also checking if
     * bricks ended so it display final message "YOY WIN"
     */
    else if (row != null) {
      remove(row);
      reakCounter--;

      vy = -vy;
    }
  }
  // setting speed and randomness, though i'm not satisfied with it's randomness
  // but it's doing the job for now
  private void getVelocity() {
    vy = 3.0;
    vx = rgen.nextDouble(1.0, 3.0);
    if (rgen.nextBoolean(0.5)) {
      vx = -vx;
    }
  }
  /* getting what's on the sides of our ball
   * changing x, y because we've a ball, not the midpoint.
   */
  private GObject collectSides() {

    GObject obj = getElementAt(ball.getX(), ball.getY());
    GObject obj2 = getElementAt(ball.getX() + 2 * BALL_RADIUS, ball.getY());
    GObject obj3 = getElementAt(ball.getX(), ball.getY() + 2 * BALL_RADIUS);
    GObject obj4 = getElementAt(ball.getX() + 2 * BALL_RADIUS, ball.getY() + 2 * BALL_RADIUS);
    if (obj != null) {
      return obj;
    } else if (obj2 != null) {
      return obj2;
    } else if (obj3 != null) {
      return obj3;
    } else if (obj4 != null) {
      return obj4;
    } else {
      return null;
    }
  }

  // private instances

  private static int reakCounter = 0;
  private static double delay = 7.5;
  // Velocity
  private static double vx, vy;

  private static GRect reak;
  private static GRect baddle;
  private static GOval ball;
  private static double ballY;
  private static double baddleY;
  private static double baddleX;

  // creating random instance
  private RandomGenerator rgen = RandomGenerator.getInstance();

  // adding sound
  AudioClip bounceClip = MediaTools.loadAudioClip("bounce.au");
}
Esempio n. 10
0
/**
 * Get or Avoid Game is modeled on the starter game from the SIGSE nifty labs Generic Scrolling Game
 * 2011
 *
 * <p>The objective is for the students to modify this starting point to develop a more significant
 * game.
 *
 * <p>Goals:
 *
 * <p>use an array to store multiple things of one type use JButton, JTextField and JLabel and
 * ActionEvents
 *
 * @author J. Smith
 * @version February 2015
 */
public class LetterGame extends GraphicsProgram {
  private static final int WINDOW_WIDTH = 600;
  private static final int WINDOW_HEIGHT = 400;
  private static final int SCOREAREA_HEIGHT = 75;
  private static final int INDENT = 10;

  private int screenDivisions = 5;
  private double speed = 2.0;
  private double playerspeed = 10.0;
  private int gameSpeed = 25;
  private GLabel[] letters;
  private RandomGenerator randgen = RandomGenerator.getInstance();
  private JLabel scoreLabel;
  private int score;
  private GLabel player;

  @Override
  public void init() {
    randgen = new RandomGenerator();
    setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
    setTitle("Get or Avoid!");
    setBackground(Color.gray);
    score = 0;
    scoreLabel = new JLabel("Score: " + score);
    scoreLabel.setFont(new Font("Cambria", Font.BOLD, 18));
    add(scoreLabel, NORTH);

    letters = new GLabel[10];

    for (int i = 0; i < 10; i++) {
      letters[i] = makeLetterLabel(screenDivisions); // 5 initial divisions
      add(letters[i]);
    }

    player = new GLabel("P", INDENT, 3 * getHeight() / screenDivisions);
    player.setFont(new Font("Cambria", Font.BOLD, 24));
    player.setColor(Color.blue);
    add(player);
    addKeyListeners();
  }

  public GLabel makeLetterLabel(int numDivs) {
    boolean get = randgen.nextBoolean();
    String ga;
    if (get) ga = "G";
    else ga = "A";
    GLabel getOrAvoid = new GLabel(ga);
    getOrAvoid.setFont(new Font("Cambria", Font.BOLD, 24));
    double locx = randgen.nextDouble(INDENT, getWidth() - getOrAvoid.getWidth());
    int whichdiv = randgen.nextInt(1, numDivs);
    double locy = whichdiv * getHeight() / numDivs;
    getOrAvoid.setLocation(locx, locy);
    return getOrAvoid;
  }

  @Override
  public void keyPressed(KeyEvent event) {
    char key = event.getKeyChar();
    if (key == 'k') {
      player.move(0, playerspeed);
    } else if (key == 'i') {
      player.move(0, -playerspeed);
    }
  }

  @Override
  public void run() {
    double reset = getWidth() - letters[0].getWidth();
    while (true) {

      for (int i = 0; i < letters.length; i++) {

        if (letters[i].getBounds().intersects(player.getBounds())) {
          if (letters[i].getLabel().equals("A")) score--; // A for avoid lose a point
          else score++; // G for get earn 1 point
          scoreLabel.setText("Score: " + score);
          // move the letter immediately
          letters[i].setLocation(reset, letters[i].getY());
        } else {
          letters[i].move(-speed, 0);
          // wrap around if past the left edge
          if (letters[i].getX() < 0) letters[i].setLocation(reset, letters[i].getY());
        }
      }
      pause(gameSpeed);
    }
  }
}
Esempio n. 11
0
public class MathQuiz extends ConsoleProgram {

  // Number of questions to ask
  private static final int NUM_QUESTIONS = 5;

  // Number of additional incorrect guesses after the first question before moving on
  private static final int NUM_GUESSES = 2;

  // Minimum integer or difference
  private static final int MIN_VALUE = 0;

  // Maximum integer or sum
  private static final int MAX_VALUE = 20;

  public void run() {
    int studentAnswer;
    String correct = "That's the answer!";
    String incorrect = "That's incorrect - try a different answer: ";
    for (int i = 0; i < NUM_QUESTIONS; i++) {
      int guessNumber = 0;
      String operator = rgen.nextBoolean(0.5) ? "+" : "-";
      int x = rgen.nextInt(MIN_VALUE, MAX_VALUE);
      int y = rgen.nextInt(MIN_VALUE, MAX_VALUE);
      int addAnswer = x + y;
      int subAnswer = x - y;
      if (operator.equals("+")) {
        while (addAnswer > MAX_VALUE) {
          x = rgen.nextInt(MIN_VALUE, MAX_VALUE);
          y = rgen.nextInt(MIN_VALUE, MAX_VALUE);
          addAnswer = x + y;
        }
        studentAnswer = readInt("What is " + x + " + " + y + "? ");
        while (studentAnswer != addAnswer && guessNumber < NUM_GUESSES) {
          guessNumber++;
          studentAnswer = readInt(incorrect);
        }
        if (studentAnswer == addAnswer) {
          println(getAnswer());
        } else {
          println("No, the answer is " + addAnswer);
        }
      } else {
        while (subAnswer < MIN_VALUE) {
          x = rgen.nextInt(MIN_VALUE, MAX_VALUE);
          y = rgen.nextInt(MIN_VALUE, MAX_VALUE);
          subAnswer = x - y;
        }
        studentAnswer = readInt("What is " + x + " - " + y + "? ");
        while (studentAnswer != subAnswer && guessNumber < NUM_GUESSES) {
          guessNumber++;
          studentAnswer = readInt(incorrect);
        }
        if (studentAnswer == subAnswer) {
          println(getAnswer());
        } else {
          println("No, the answer is " + subAnswer);
        }
      }
    }
  }

  private String getAnswer() {
    int response = rgen.nextInt(0, 3);
    switch (response) {
      case 0:
        return "That's correct";
      case 1:
        return "You got it!";
      case 2:
        return "Way to go!";
      case 3:
        return "Correct!";
      default:
        return null;
    }
  }
  // Private instance variables
  private RandomGenerator rgen = RandomGenerator.getInstance();
}
public class BreakoutExt extends WindowProgram {

  // Width and height of application window in pixels
  public static final int APPLICATION_WIDTH = 400;
  public static final int APPLICATION_HEIGHT = 630;

  // Dimensions of game board (usually the same)
  private static final int WIDTH = APPLICATION_WIDTH;
  private static final int HEIGHT =
      APPLICATION_HEIGHT - 25; // Amendment 25px on the menu at the top of the screen

  // Dimensions of the paddle
  private static final int PADDLE_WIDTH = 60;
  private static final int PADDLE_HEIGHT = 10;

  // Offset of the paddle up from the bottom
  private static final int PADDLE_Y_OFFSET = 60;

  // Number of bricks per row
  private static final int NBRICKS_PER_ROW = 10;

  // Number of rows of bricks
  private static final int NBRICK_ROWS = 10;

  // Separation between bricks
  private static final int BRICK_SEP = 4;

  // Width of a brick
  private static final int BRICK_WIDTH =
      (WIDTH - (NBRICKS_PER_ROW - 1) * BRICK_SEP) / NBRICKS_PER_ROW;

  // Height of a brick
  private static final int BRICK_HEIGHT = 8;

  // Radius of the ball in pixels
  private static final int BALL_RADIUS = 10;

  // Offset of the top brick row from the top
  private static final int BRICK_Y_OFFSET = 70;

  // The starting speed of the ball
  private static final double SPEED_Y = 3.0;

  // The time delay of motion of the game
  private static final double TIME_PAUSE = 15;

  // The delay of the text on the screen when displaying result game
  private static final double TEXT_PAUSE_TIME = 2500;

  // Number of turns
  private static final int NTURNS = 3;

  // Connecting random generator
  RandomGenerator rgen = RandomGenerator.getInstance();

  // The variables are stored initial state of the game
  private int startGame = 0;

  // The variables that will store the links to the following sites: paddle and ball, respectively
  private GRect paddle;
  private GOval ball;

  // The variable in which to store the number of downed bricks per game
  private int allDelBricks = 0;

  // This variable will store the amount of scores per game
  private int resGame = 0;

  /** The method contains all the methods that control the whole process of the game */
  public void run() {
    addMouseListeners();
    boolean res = false;
    drawBricks(); // Creates bricks
    for (int numberOfGame = 1; numberOfGame <= NTURNS; numberOfGame++) {
      if (res) {
        break;
      }
      startGame = 0;
      paddle = madePaddle(); // Create paddle
      ball = madeBall(); // Create ball
      waitForClick(); // Waiting for a mouse click for further implementation of the program
      startGame = 1;
      res = runBall(); // Starts ball
      if (!res) {
        messageLostAndTryAgain(numberOfGame); // It displays a message in case of loss
      } else {
        removeAll();
        messageWin(); // Displays a message in case of a win
      }
    }
    removeAll();
    createMessage("GAME OVER!");
    createScore("Result of your game: " + resGame + " score");
  }

  /** Text output in the event of winning player */
  private void messageWin() {
    createMessage("Congratulations, you WIN!");
    pause(TEXT_PAUSE_TIME);
  }

  /** Text output in case of loss player */
  private void messageLostAndTryAgain(int numberOfGame) {
    GLabel label = createMessage("You lost, but don't cry.");
    pause(TEXT_PAUSE_TIME);

    remove(label);
    remove(paddle);
    remove(ball);
    if (numberOfGame != NTURNS) {
      label = createMessage("You have " + (NTURNS - numberOfGame) + " Chance. Click to start.");
      waitForClick();
      remove(label);
    }
  }

  /**
   * The method which controls the movement the ball, check all the objects with which the ball is
   * faced and performs the appropriate actions to them
   */
  private boolean runBall() {
    double vx;
    double vy = SPEED_Y;
    boolean res = false;
    vx = rgen.nextDouble(1.0, 3.0); // randomly sets horizontal speed
    if (rgen.nextBoolean(
        0.5)) // with a 50 percent chance change the direction of movement of the ball
    vx = -vx;

    while (allDelBricks
        < NBRICK_ROWS * NBRICKS_PER_ROW) { // The game will not end until all the bricks
      GObject collider = getCollidingObject(); // The variable gets test result object
      vx = checkTheLeftAndRightWall(vx); // Check the collision of the ball on the side walls
      vy =
          checkTheTopWallAndPaddle(vy); // Check the collision of the ball on the ceiling and paddle
      vx =
          checkLeftAndRightWallOfPaddle(
              vx); // Check the collision of the ball with the side part of the paddle

      if (collider != null) { // If checkpoints are returned brick, it is then removed
        if (collider != paddle) {
          remove(collider);
          vy = -vy;
          allDelBricks++;
        }
      }
      ball.move(vx, vy);
      pause(TIME_PAUSE);
      if (ball.getY()
          > HEIGHT
              - (PADDLE_Y_OFFSET / 3)
              - BALL_RADIUS * 2) { // The game stops when the ball falls below the window
        res = false;
        return res;
      }
      res = true;
    }
    return res;
  }

  /**
   * If the ball is hit in the fall on the side of the paddle, it will change the direction of the
   * x-coordinate
   */
  private double checkLeftAndRightWallOfPaddle(double vx) {
    if (getElementAt(paddle.getX() - 1, paddle.getY()) == ball
        || getElementAt(paddle.getX() - 1, paddle.getY() + PADDLE_HEIGHT) == ball
        || getElementAt(paddle.getX() + PADDLE_WIDTH + 1, paddle.getY()) == ball
        || getElementAt(paddle.getX() + PADDLE_WIDTH + 1, paddle.getY() + PADDLE_HEIGHT) == ball) {
      vx = -vx;
    }
    return vx;
  }

  /**
   * Makes the ball bounce from the top wall and paddle When you hit the upper wall and a paddle
   * changes direction along the y-coordinate.
   */
  private double checkTheTopWallAndPaddle(double vy) {
    if (ball.getY() + 1 <= 0) { // Checks upper wall
      vy = -vy;
    } else if (getElementAt(ball.getX() + BALL_RADIUS * 2, ball.getY() + BALL_RADIUS * 2) == paddle
        || getElementAt(ball.getX(), ball.getY() + BALL_RADIUS * 2) == paddle) { // Checks paddle
      if (vy > -2.0) {
        vy = -vy - 0.1; // Makes the the acceleration of the ball at every touch the paddle
      }
    }
    return vy;
  }

  /**
   * Makes the ball bounce from the left and right walls. At blow the side of the wall, changes
   * direction of the x coordinate. Returns the direction of the ball along the x coordinate
   */
  private double checkTheLeftAndRightWall(double vx) {
    if (ball.getX() - 1 <= 0 || ball.getX() + BALL_RADIUS * 2 + 1 >= WIDTH) {
      vx = -vx;
    }
    return vx;
  }

  /**
   * Creates a point at the ball 4 check and verifies the presence of an object near it. Returns
   * null or the name of the object, if it is present
   */
  private GObject getCollidingObject() {
    GObject colliding;

    colliding =
        getElementAt(ball.getX(), ball.getY()); // Creates the upper left point of check ball
    if (colliding != null) {
      Color color = colliding.getColor();
      count(color);
      return colliding;
    }
    colliding =
        getElementAt(
            ball.getX() + BALL_RADIUS * 2,
            ball.getY()); // Creates the top right point of check ball
    if (colliding != null) {
      Color color = colliding.getColor();
      count(color);
      return colliding;
    }
    colliding =
        getElementAt(
            ball.getX(),
            ball.getY() + BALL_RADIUS * 2); // Creates the lower left point of check ball
    if (colliding != null) {
      Color color = colliding.getColor();
      count(color);
      return colliding;
    }
    colliding =
        getElementAt(
            ball.getX() + BALL_RADIUS * 2,
            ball.getY() + BALL_RADIUS * 2); // Creates a check point of the lower right on the ball
    if (colliding != null) {
      Color color = colliding.getColor();
      count(color);
      return colliding;
    }

    return null;
  }

  /**
   * Sets the sum of the scores depending on the color of brick, and displays the result on the
   * screen
   */
  private void count(Color color) {
    int scores = 0;
    if (color == Color.CYAN) {
      scores = 100;
    } else if (color == Color.GREEN) {
      scores = 200;
    } else if (color == Color.YELLOW) {
      scores = 300;
    } else if (color == Color.ORANGE) {
      scores = 400;
    } else if (color == Color.RED) {
      scores = 500;
    }

    rectangle(
        0,
        HEIGHT - (PADDLE_Y_OFFSET / 4),
        WIDTH,
        PADDLE_Y_OFFSET / 4,
        Color.white,
        Color.white); // Draw a white square to hide the previous result
    resGame = resGame + scores;
    createScore("Score: " + resGame);
  }

  /** Displays the amount of points on the screen in text form */
  private GLabel createScore(String score) {
    GLabel text = new GLabel(score);
    text.setFont("Arial Black-12");
    text.setColor(Color.black);
    double x = (WIDTH - text.getWidth()) / 2;
    double y = HEIGHT - text.getDescent();
    text.setLocation(x, y);
    add(text);
    return text;
  }

  /** Sends information about the state of the mouse */
  public void mouseMoved(MouseEvent e) {
    muvedPaddle(e);
    muvedBall(e);
  }

  /** Bind the ball to the mouse cursor */
  private void muvedBall(MouseEvent e) {
    if (startGame == 0) {
      int y = HEIGHT - PADDLE_HEIGHT - PADDLE_Y_OFFSET - BALL_RADIUS * 2;
      int x;
      if (e.getX()
          > WIDTH
              - PADDLE_WIDTH
                  / 2) { // Makes it impossible to exit the ball over the right part of the window
        x = WIDTH - PADDLE_WIDTH / 2 - BALL_RADIUS;
      } else if (e.getX()
          < PADDLE_WIDTH
              / 2) { // Makes it impossible to exit the ball over the left part of the window
        x = PADDLE_WIDTH / 2 - BALL_RADIUS;
      } else {
        x = e.getX() - BALL_RADIUS; // Bind the ball to the center of the cursor
      }
      ball.setLocation(x, y);
    }
  }

  /** Bind the paddle to the mouse cursor */
  private void muvedPaddle(MouseEvent e) {
    int y = HEIGHT - PADDLE_HEIGHT - PADDLE_Y_OFFSET;
    int x;
    if (e.getX()
        > WIDTH
            - PADDLE_WIDTH
                / 2) { // Makes it impossible to exit the paddle over the right part of the window
      x = WIDTH - PADDLE_WIDTH;
    } else if (e.getX()
        < PADDLE_WIDTH
            / 2) { // Makes it impossible to exit the paddle over the left part of the window
      x = 0;
    } else {
      x = e.getX() - PADDLE_WIDTH / 2; // Bind the paddle to the center of the cursor
    }
    paddle.setLocation(x, y);
  }

  // Created the bricks of different colors
  private void drawBricks() {
    int startPosX =
        (WIDTH - (BRICK_WIDTH * NBRICKS_PER_ROW + BRICK_SEP * (NBRICKS_PER_ROW - 1))) / 2;
    for (int i = 0; i < NBRICK_ROWS; i++) { // Created rows of bricks
      Color color;
      if (i == 0 || i == 1) {
        color = (Color.RED);
      } else if (i == 2 || i == 3) {
        color = (Color.ORANGE);
      } else if (i == 4 || i == 5) {
        color = (Color.YELLOW);
      } else if (i == 6 || i == 7) {
        color = (Color.GREEN);
      } else {
        color = (Color.CYAN);
      }
      int posY = BRICK_Y_OFFSET + ((BRICK_HEIGHT + BRICK_SEP) * i);
      for (int j = 0; j < NBRICKS_PER_ROW; j++) { // Created the bricks in a row
        int posX = startPosX + (BRICK_WIDTH + BRICK_SEP) * j;
        rectangle(posX, posY, BRICK_WIDTH, BRICK_HEIGHT, color, color);
      }
    }
  }

  /** Creates a paddle */
  private GRect madePaddle() {
    int startPosX = (WIDTH - PADDLE_WIDTH) / 2;
    Color color = Color.BLACK;
    int posY = HEIGHT - PADDLE_HEIGHT - PADDLE_Y_OFFSET;
    GRect paddle = rectangle(startPosX, posY, PADDLE_WIDTH, PADDLE_HEIGHT, color, color);
    return paddle;
  }

  /** Creates a red ball */
  private GOval madeBall() {
    int startPosX = (WIDTH - BALL_RADIUS * 2) / 2;
    int startPosY = HEIGHT - PADDLE_Y_OFFSET - PADDLE_HEIGHT - BALL_RADIUS * 2;
    Color color = Color.RED;
    GOval oval = oval(startPosX, startPosY, BALL_RADIUS * 2, BALL_RADIUS * 2, color, color);
    return oval;
  }

  /** The method accepts a string and displays the green text in the center of the screen */
  private GLabel createMessage(String message) {
    GLabel text = new GLabel(message);
    text.setFont("Arial Black-20");
    text.setColor(Color.GREEN);
    double x = (WIDTH - text.getWidth()) / 2;
    double y = (HEIGHT - text.getDescent()) / 2;
    text.setLocation(x, y);
    add(text);
    return text;
  }

  /** The method takes parameters and returns, square shape figure */
  private GRect rectangle(int x, int y, int width, int height, Color colorSetFill, Color colorSet) {
    GRect rectangle = new GRect(x, y, width, height);
    rectangle.setFilled(true);
    rectangle.setFillColor(colorSetFill);
    rectangle.setColor(colorSet);
    add(rectangle);
    return rectangle;
  }

  /** The method takes parameters and returns, oval shape figure */
  private GOval oval(int x, int y, int width, int height, Color colorSetFill, Color colorSet) {
    GOval oval = new GOval(x, y, width, height);
    oval.setFilled(true);
    oval.setFillColor(colorSetFill);
    oval.setColor(colorSet);
    add(oval);
    return oval;
  }
}
Esempio n. 13
0
public class Breakout_Extension extends GraphicsProgram {

  /**
   * Width and height of application window in pixels. On some platforms these may NOT actually be
   * the dimensions of the graphics canvas.
   */
  public static final int APPLICATION_WIDTH = 400;

  public static final int APPLICATION_HEIGHT = 600;

  /**
   * Dimensions of game board. On some platforms these may NOT actually be the dimensions of the
   * graphics canvas.
   */
  private static final int WIDTH = APPLICATION_WIDTH;

  private static final int HEIGHT = APPLICATION_HEIGHT;

  /** Dimensions of the paddle */
  private static final int PADDLE_WIDTH = 60;

  private static final int PADDLE_HEIGHT = 10;

  /** Offset of the paddle up from the bottom */
  private static final int PADDLE_Y_OFFSET = 30;

  /** Number of bricks per row */
  private static final int NBRICKS_PER_ROW = 10;

  /** Number of rows of bricks */
  private static final int NBRICK_ROWS = 10;

  /** Separation between bricks */
  private static final int BRICK_SEP = 4;

  /** Width of a brick */
  private static final int BRICK_WIDTH =
      (WIDTH - (NBRICKS_PER_ROW - 1) * BRICK_SEP) / NBRICKS_PER_ROW;

  /** Height of a brick */
  private static final int BRICK_HEIGHT = 8;

  /** Radius of the ball in pixels */
  private static final int BALL_RADIUS = 10;

  /** Offset of the top brick row from the top */
  private static final int BRICK_Y_OFFSET = 70;

  /** Number of turns */
  private static final int NTURNS = 3;

  /** Animation delay or pause time between ball moves */
  private static final int DELAY = 20;

  /* Method: run() */
  /** Runs the Breakout program. */

  /*
   * instance variables
   */

  private GRect paddle; // the paddle

  private GOval ball; // the ball
  private double vx, vy; // the x component and y component of velocity of ball
  private GLabel lifeCount; // the prompt to show the life user still has
  private RandomGenerator rgen = RandomGenerator.getInstance(); // create a random number generator
  private int brickCount = NBRICK_ROWS * NBRICKS_PER_ROW; // total number of bricks

  /*
   * first create the items in the game then play.
   */

  public void run() {
    setup();
    showInitialLifeCount();
    play();
  }

  /*
   * set up the items in the game, including bricks, a paddle and a ball.
   */

  private void setup() {
    drawBricks();
    drawPaddle();
    createBall();
  }

  /*
   * Draw all the bricks.
   */

  private void drawBricks() {
    for (int i = 0; i < NBRICK_ROWS; i++) {
      drawRow(i);
    }
  }

  /*
   * draw a row of the brick pile
   */

  private void drawRow(int row) {
    for (int i = 0; i < NBRICKS_PER_ROW; i++) {
      drawOneBrick(row, i);
    }
  }

  /*
   * create one brick.
   */

  private void drawOneBrick(int row, int col) {
    double x0 =
        (WIDTH - NBRICKS_PER_ROW * BRICK_WIDTH - (NBRICKS_PER_ROW - 1) * BRICK_SEP)
            / 2; // the distance of leftmost brick to left border of the world
    double x = x0 + (BRICK_WIDTH + BRICK_SEP) * col;
    double y = BRICK_Y_OFFSET + (BRICK_SEP + BRICK_HEIGHT) * row;
    GRect brick = new GRect(x, y, BRICK_WIDTH, BRICK_HEIGHT);
    brick.setFilled(true);
    colorBrick(row, brick);
    add(brick);
  }

  /*
   * set color for the bricks according to which rows they are in.
   */

  private void colorBrick(int row, GRect brick) {
    if (row < 2) {
      brick.setColor(Color.RED);
    } else if (row < 4) {
      brick.setColor(Color.ORANGE);
    } else if (row < 6) {
      brick.setColor(Color.YELLOW);
    } else if (row < 8) {
      brick.setColor(Color.GREEN);
    } else if (row < 10) {
      brick.setColor(Color.CYAN);
    }
  }

  /*
   * Draw a paddle.
   */

  private void drawPaddle() {
    double x = (WIDTH - PADDLE_WIDTH) / 2;
    double y = HEIGHT - BRICK_Y_OFFSET - PADDLE_HEIGHT;
    paddle = new GRect(x, y, PADDLE_WIDTH, PADDLE_HEIGHT);
    paddle.setFilled(true);
    add(paddle);
    addMouseListeners();
  }

  /*
   * change the x location of the paddle according to the movement of user's mouse.
   */

  public void mouseMoved(MouseEvent e) {
    if ((e.getX() > PADDLE_WIDTH / 2) && (e.getX() < WIDTH - PADDLE_WIDTH / 2)) {
      double x = e.getX() - PADDLE_WIDTH / 2;
      double y = HEIGHT - BRICK_Y_OFFSET - PADDLE_HEIGHT;
      paddle.setLocation(x, y);
    }
  }

  /*
   * draw a ball and assign a initial velocity for it
   */

  private void createBall() {
    drawBall();
    getVelocity();
  }

  /*
   * Draw a ball at the center of the world with radius BALL_RADIUS.
   */

  private void drawBall() {
    double x = WIDTH / 2 - BALL_RADIUS;
    double y = HEIGHT / 2 - BALL_RADIUS;
    double d = 2 * BALL_RADIUS;
    ball = new GOval(x, y, d, d);
    ball.setFilled(true);
    add(ball);
  }

  /*
   * The balls gains an initial speed and starts to move.
   * The x component of the initial velocity is 3.0.
   * The y component of the initial velocity is a random number of certain range.
   */

  private void getVelocity() {
    vy = 3.0;
    vx = rgen.nextDouble(1.0, 3.0);
    if (rgen.nextBoolean(0.5)) {
      vx = -vx;
    }
  }

  /*
   * display the turns users have at the beginning of the game
   */

  private void showInitialLifeCount() {
    GLabel lifeCount = prompt("You have " + NTURNS + " lives.");
    add(lifeCount);
    waitForClick();
    remove(lifeCount);
  }

  /*
   * Users start the game with a click. The game does not end until the ball falls off the bottom
   * of the screen or there is no brick left. If you break all the bricks before using up the lives,
   * you win. If the ball falls off the bottom of the screen, you turn to other round until you use
   * up all your lives.
   */

  private void play() {
    gaming();
    showPrompt();
  }

  /*
   * user plays the game. If the user loses in one turn,the game goes on to the next turn.
   * If the user loses NTURNS times, he or she loses the game. If the user wins in one turn,
   * the game does not go on to next turn, but ends.
   */

  private void gaming() {
    boolean loseOneTurn;
    boolean win = false;
    boolean stillAlive = true;
    for (int i = NTURNS; i > 0; i--) { // loops for the number of turns.
      GLabel life = showLifeCount(i);
      waitForClick();
      add(life);
      while (stillAlive) { // the ball moves and bounces until the user loses or wins the turn.
        moveBall();
        loseOneTurn =
            (ball.getY() >= HEIGHT); // user loses one turn when the ball falls under the paddle.
        win = (brickCount == 0); // user wins when there is no brick left.
        stillAlive = !(loseOneTurn || win);
      }
      if (win) break; // breaks from the loop if the user wins in one turn.
      remove(ball);
      createBall(); // a new ball appears on the center of the screen after one turn
      stillAlive = true;
      remove(life);
    }
  }

  /*
   * Show remaining lives the user has at the upper left corner of the screen.
   */

  private GLabel showLifeCount(int life) {
    GLabel lifeCount = new GLabel("Life Count: " + life);
    lifeCount.setFont("Times-15");
    lifeCount.setLocation(10, lifeCount.getAscent() + 10);
    return lifeCount;
  }

  /*
   * the ball starts to fall, and bounces when hitting the wall or objects.
   */

  private void moveBall() {
    startFall();
    checkWall();
    checkObject();
  }

  /*
   * the ball falls from its original location at the center of the screen.
   */

  private void startFall() {
    ball.move(vx, vy);
    pause(DELAY);
    ball.sendToBack();
  }

  /*
   * checks if the ball hits the left, the right or the top wall. Then change the movement
   * of the ball accordingly.
   */

  private void checkWall() {
    boolean checkLeftWall = ball.getX() <= 0;
    boolean checkRightWall = ball.getX() + BALL_RADIUS * 2 >= WIDTH;
    boolean checkTop = ball.getY() <= 0;
    if ((checkLeftWall) || (checkRightWall)) {
      vx = -vx;
    }
    if (checkTop) {
      vy = -vy;
    }
  }

  /*
   * Check the four corners of the square inscribing the ball in order.
   * If one of the corner is contained in an object other than paddle, remove the object and then bounce off.
   * If one of the corner is contained in paddle, bounce off without removing the paddle.
   *
   */

  private void checkObject() {
    // x and y parameters for the different corners
    double leftX = ball.getX();
    double rightX = ball.getX() + (2 * BALL_RADIUS);
    double upperY = ball.getY();
    double lowerY = ball.getY() + (2 * BALL_RADIUS);
    // check the corners for object
    GObject upperLeft = checkCorner(leftX, upperY); // check upper-left corner
    if (upperLeft == null) {
      GObject upperRight = checkCorner(rightX, upperY); // check upper-right corner
    }
    GObject lowerLeft = checkCorner(leftX, lowerY); // //check lower-left corner
    if (lowerLeft == null) {
      GObject lowerRight = checkCorner(rightX, lowerY); // check lower-right corner
      if ((lowerLeft == paddle)
          && (lowerRight == paddle)) { // When both lower corners hit paddle, change direction.
        vy = -vy;
      }
    }
  }

  /*
   * check one corner of the square inscribing the ball in order.
   * If one of the corner is contained in an object other than paddle, remove the object and then bounce off.
   * If one of the corner is contained in paddle, bounce off without removing the paddle.
   */

  private GObject checkCorner(double x, double y) {
    GObject obj = getElementAt(x, y); // check the corner for GObject
    if (obj == paddle) {
      vy = -Math.abs(vy);
      PrecisionPaddle();
    } else if (obj != null && obj != lifeCount) { // check if the ball hits a brick
      remove(obj);
      vy = -1.05 * vy;
      vx = 1.05 * vx;
      brickCount--;
      AudioClip bounceClip = MediaTools.loadAudioClip("bounce.au");
      bounceClip.play();
    }
    return obj;
  }

  /*
   * check if ball gets into the paddle, update location as appropriate
   */

  private void PrecisionPaddle() {
    if (ball.getY()
        > HEIGHT
            - PADDLE_Y_OFFSET
            - PADDLE_HEIGHT
            - BALL_RADIUS * 2) { // check if the ball drops below the paddle
      double diff = ball.getY() - (HEIGHT - PADDLE_Y_OFFSET - PADDLE_HEIGHT - BALL_RADIUS * 2);
      ball.move(0, -2 * diff); // move ball an amount equal to the amount it drops below the paddle
    }
  }

  /*
   * Show the prompt to indicate whether user loses or wins.
   */

  private void showPrompt() {
    if (brickCount == 0) {
      add(prompt("YOU WIN!"));
    } else {
      add(prompt("GAME OVER!"));
    }
  }
  /*
   * prompt at the end of the game to indicate whether the user wins or loses
   */

  private GLabel prompt(String endGame) {
    GLabel prompt = new GLabel(endGame);
    prompt.setFont("Times-Bold-50");
    double x = (WIDTH - prompt.getWidth()) / 2;
    double y = HEIGHT * 4.0 / 5.0;
    prompt.setLocation(x, y);
    return prompt;
  }
}