示例#1
1
  /**
   * All of the game's logic (per game iteration) is in this function. Given some initial game
   * state, it computes the next game state.
   */
  private void doGameLogic() {
    float px = mBall.x;
    float py = mBall.y;

    mBall.move();

    // Shake it up if it appears to not be moving vertically
    if (py == mBall.y && mBall.serving() == false) {
      mBall.randomAngle();
    }

    // Do some basic paddle AI
    if (!mRed.player) doAI(mRed, mBlue);
    else mRed.move();

    if (!mBlue.player) doAI(mBlue, mRed);
    else mBlue.move();

    handleBounces(px, py);

    // See if all is lost
    if (mBall.y >= getHeight()) {
      mNewRound = true;
      mBlue.loseLife();

      if (mBlue.living()) playSound(mMissSFX);
      else playSound(mWinSFX);
    } else if (mBall.y <= 0) {
      mNewRound = true;
      mRed.loseLife();
      if (mRed.living()) playSound(mMissSFX);
      else playSound(mWinSFX);
    }
  }
示例#2
0
 public void mouseMoved(MouseEvent e) { // called during motion when no buttons are down
   //  if (e.getY ==
   if ((e.getX() < appletsize_x - pad.width() / 2) && (e.getX() > (pad.width() / 2))) {
     pad.changeX(e.getX() - (pad.width() / 2));
     ball.moveWithPaddle(pad.xPos + (pad.width() / 2) - (ball.radius()));
   }
   e.consume();
   repaint();
 }
 private void applyType(Paddle paddle) {
   if (paddle.getType() == 0) {
     NormalPaddle.set(paddle);
   } else if (paddle.getType() == 1) {
     LargePaddle.set(paddle);
   } else if (paddle.getType() == 2) {
     JumpyPaddle.set(paddle);
   }
 }
示例#4
0
    protected double salt(double angle, Paddle paddle) {
      int cx = paddle.centerX();
      double halfWidth = paddle.getWidth() / 2;
      double change = 0.0;

      if (goingUp()) change = SALT * ((cx - x) / halfWidth);
      else change = SALT * ((x - cx) / halfWidth);

      return boundAngle(angle, change);
    }
示例#5
0
 public void slaveMover(
     int s,
     int dx,
     int ps,
     int pdx) { // The Slave mover is recursive so there can be infinite slave paddles and so the
   // control can be
   // reversed with each new slave paddle added.
   if (this.getSlave() != null) {
     Paddle p = this.getSlave();
     p.mRect.offset((dx > s) ? ps : pdx, 0);
     p.slaveMover(s, dx, -ps, -pdx);
   }
 }
 private void setType(Paddle paddle) {
   if (Math.random() < 0.1 && paddle.getType() != 2) { // %10 chance
     if (Math.random() < 0.5 && paddle.padType != 1) {
       Sound.play("\\sound\\pwrup.wav");
       paddle.padType = 1;
     } else if (paddle.padType != 2) {
       Sound.play("\\sound\\pwrup.wav");
       paddle.padType = 2;
     }
   } else if (paddle.getType() != 1) {
     paddle.padType = 0;
   }
 }
示例#7
0
 public void paint(Graphics g) {
   if (mainMenu) {
     drawTitleScreen(g);
   } else if (gamePlaying) {
     drawBricks(g);
     g.setColor(Color.green);
     g.fillRect(pad.x(), 590, pad.width(), 10);
     g.fillOval(
         ball.x_Pos() - ball.radius(),
         ball.y_Pos() - ball.radius(),
         ball.radius() * 2,
         ball.radius() * 2);
   }
 } // paint method
示例#8
0
文件: Enemy.java 项目: sukhoykin/pong
  @Override
  public void render(Graphics2D g) {

    super.render(g);

    // g.setColor(Color.ORANGE);
    // g.drawLine(0, (int) getCenterY(), Scene.WIDTH, (int) getCenterY());
  }
示例#9
0
 protected float applyCenterHitBonus(Paddle paddle) {
   int cx = paddle.centerX();
   float newSpeed;
   float centerBonusIndicator = Math.abs(cx - this.x);
   if (centerBonusIndicator <= CENTER_HIT_CONSTANT) {
     newSpeed = this.speed * 2;
   } else {
     newSpeed = this.speed;
   }
   return newSpeed;
 }
示例#10
0
  @Override
  public boolean onTrackballEvent(MotionEvent event) {
    if (!gameRunning()) return false;

    if (mBlue.player == false) {
      mBlue.player = true;
      mBlue.destination = mBlue.centerX();
    }

    switch (event.getAction()) {
      case MotionEvent.ACTION_MOVE:
        mBlue.destination =
            (int)
                Math.max(
                    0, Math.min(getWidth(), mBlue.destination + SCROLL_SENSITIVITY * event.getX()));
        break;
    }

    return true;
  }
示例#11
0
文件: Enemy.java 项目: sukhoykin/pong
  @Override
  public void update(long dt) {

    super.update(dt);

    if (ballAbove() && ball.isMoveUp()) {
      moveUp();

    } else if (ballBelow() && ball.isMoveDown()) {
      moveDown();

    } else {
      stop();
    }
  }
示例#12
0
    /**
     * Normalizes a ball's position after it has hit a paddle.
     *
     * @param r The paddle the ball has hit.
     */
    protected void normalize(Paddle p) {
      // Quit if the ball is outside the width of the paddle
      if (x < p.getLeft() || x > p.getRight()) {
        return;
      }

      // Case if ball is above the paddle
      if (y < p.getTop()) {
        y = Math.min(y, p.getTop() - Ball.RADIUS);
      } else if (y > p.getBottom()) {
        y = Math.max(y, p.getBottom() + Ball.RADIUS);
      }
    }
示例#13
0
    @Override
    public void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g;

      // paint ball, paddle, and brick configuration
      g2.drawImage(background.getImage(), 0, 0, null);
      bconfig.paint(g2);
      paddle.paint(g2);
      ball.paint(g2);
      g2.setColor(Color.WHITE);
      g2.setFont(new Font("Serif", Font.PLAIN, 20));
      g2.drawString("Score: " + score, 15, 20);
      if (ball.getY() > 500) {
        g2.setColor(Color.WHITE);
        g2.setFont(new Font("Serif", Font.PLAIN, 30));
        g2.drawString("Game Over!", 200, 300);
        g2.drawString("Your final score was " + score, 150, 330);
        timer.stop();
      }
    }
示例#14
0
  protected void handleBottomFastBounce(Paddle paddle, float px, float py) {
    if (mBall.goingDown() == false) return;

    float bx = mBall.x;
    float by = mBall.y + Ball.RADIUS;
    float pbx = px;
    float pby = py + Ball.RADIUS;
    float dyp = by - paddle.getTop();
    float xc = bx + (bx - pbx) * dyp / (pby - by);

    if (by > paddle.getTop()
        && pby < paddle.getTop()
        && xc > paddle.getLeft()
        && xc < paddle.getRight()) {

      mBall.x = xc;
      mBall.y = paddle.getTop() - Ball.RADIUS;
      mBall.bouncePaddle(paddle);
      playSound(mPaddleSFX);
      increaseDifficulty();
    }
  }
示例#15
0
  protected void handleTopFastBounce(Paddle paddle, float px, float py) {
    if (mBall.goingUp() == false) return;

    float tx = mBall.x;
    float ty = mBall.y - Ball.RADIUS;
    float ptx = px;
    float pty = py - Ball.RADIUS;
    float dyp = ty - paddle.getBottom();
    float xc = tx + (tx - ptx) * dyp / (ty - pty);

    if (ty < paddle.getBottom()
        && pty > paddle.getBottom()
        && xc > paddle.getLeft()
        && xc < paddle.getRight()) {

      mBall.x = xc;
      mBall.y = paddle.getBottom() + Ball.RADIUS;
      mBall.bouncePaddle(paddle);
      playSound(mPaddleSFX);
      increaseDifficulty();
    }
  }
示例#16
0
    public void checkForHit() {

      // change ball speed when ball hits paddle
      if (ball.getShape().intersects(paddle.getShape())) {
        int leftSide = paddle.getX();
        int middleLeft = paddle.getX() + (int) (paddle.getWidth() / 3);
        int middleRight = paddle.getX() + (int) (2 * paddle.getWidth() / 3);
        int rightSide = paddle.getX() + paddle.getWidth();

        if ((ball.getX() >= leftSide) && (ball.getX() < middleLeft)) {
          // change ball speed
          ball.setXspeed(-2);
          ball.setYspeed(-2);
        }
        if ((ball.getX() >= middleLeft) && (ball.getX() <= middleRight)) {
          // change ball speed
          ball.setYspeed(-2);
        }
        if ((ball.getX() > middleRight) && (ball.getX() <= rightSide)) {
          // change ball speed
          ball.setXspeed(2);
          ball.setYspeed(-2);
        }
      }

      // change ball speed when ball hits brick
      for (int i = 0; i < bconfig.getRows(); i++) {
        for (int j = 0; j < bconfig.getCols(); j++) {
          if (bconfig.exists(i, j)) {
            if (ball.getShape().intersects(bconfig.getBrick(i, j).getShape())) {
              Point ballLeft =
                  new Point(
                      (int) ball.getShape().getX(),
                      (int) (ball.getShape().getY() + ball.getShape().getHeight() / 2));
              Point ballRight =
                  new Point(
                      (int) (ball.getShape().getX() + ball.getShape().getWidth()),
                      (int) (ball.getShape().getY() + ball.getShape().getHeight() / 2));
              Point ballTop =
                  new Point(
                      (int) (ball.getShape().getX() + ball.getShape().getWidth() / 2),
                      (int) ball.getShape().getY());
              Point ballBottom =
                  new Point(
                      (int) (ball.getShape().getX() + ball.getShape().getWidth() / 2),
                      (int) (ball.getShape().getY() + ball.getShape().getHeight()));
              if (bconfig.getBrick(i, j).getShape().contains(ballLeft)) {
                // change ball speed
                ball.setXspeed(2);
                score++;
              } else if (bconfig.getBrick(i, j).getShape().contains(ballRight)) {
                // change ball speed
                ball.setXspeed(-2);
                score++;
              }
              if (bconfig.getBrick(i, j).getShape().contains(ballTop)) {
                // change ball speed
                ball.setYspeed(2);
                score++;
              } else if (bconfig.getBrick(i, j).getShape().contains(ballBottom)) {
                // change ball speed
                ball.setYspeed(-2);
                score++;
              }

              // remove brick
              bconfig.removeBrick(i, j);
            }
          }
        }
      }
    }
示例#17
0
  /**
   * Tests the update function's functionality. Update is called on every game timer firing.
   *
   * <p>The update function has to move the paddle by the paddle's x velocity and not move in the y
   * direction. It also can not move the paddle past the game window's boundaries.
   */
  @Test
  public final void testUpdate() {
    // Test that the update function can move a paddle.
    Robot robot;
    try {
      robot = new Robot();
      Field paddleField, directionField;
      Paddle paddle;

      // Check that direction starts at 0
      {
        // Gain access to the paddle
        paddleField = testgame.getClass().getDeclaredField("paddle");
        paddleField.setAccessible(true);
        paddle = (Paddle) paddleField.get(testgame);
        // Gain access to the direction field of the paddle
        directionField = paddle.getClass().getDeclaredField("direction");
        directionField.setAccessible(true);

        assertEquals(0, directionField.get(paddle));
      }

      // Check that when 'a' is pressed direction is set to -1
      {
        // Press 'A'
        robot.keyPress(KeyEvent.VK_A);
        // The game needs a little time to register the key
        Thread.sleep(SLEEPDELAY);

        // Gain access to the paddle
        paddleField = testgame.getClass().getDeclaredField("paddle");
        paddleField.setAccessible(true);
        paddle = (Paddle) paddleField.get(testgame);
        directionField = paddle.getClass().getDeclaredField("direction");
        directionField.setAccessible(true);

        assertEquals(-1, directionField.get(paddle));
      }

      // Check that when 'a' is released direction is reset to 0
      {
        // Release 'A'
        robot.keyRelease(KeyEvent.VK_A);
        // The game needs a little time to register the key
        Thread.sleep(SLEEPDELAY);

        // Gain access to the paddle
        paddleField = testgame.getClass().getDeclaredField("paddle");
        paddleField.setAccessible(true);
        paddle = (Paddle) paddleField.get(testgame);
        directionField = paddle.getClass().getDeclaredField("direction");
        directionField.setAccessible(true);

        assertEquals(0, directionField.get(paddle));
      }

      // Check that when 'd' is pressed with 'a' released direction is set
      // to 1
      {
        // Press 'D'
        robot.keyPress(KeyEvent.VK_D);
        // The game needs a little time to register the key
        Thread.sleep(SLEEPDELAY);

        // Gain access to the paddle after a change
        paddleField = testgame.getClass().getDeclaredField("paddle");
        paddleField.setAccessible(true);
        paddle = (Paddle) paddleField.get(testgame);
        directionField = paddle.getClass().getDeclaredField("direction");
        directionField.setAccessible(true);

        assertEquals(1, directionField.get(paddle));
      }

      // Check that when 'd' is released direction is reset to 0
      {
        // Release 'D'
        robot.keyRelease(KeyEvent.VK_D);
        // The game needs a little time to register the key
        Thread.sleep(SLEEPDELAY);

        // Gain access to the paddle after a change
        paddleField = testgame.getClass().getDeclaredField("paddle");
        paddleField.setAccessible(true);
        paddle = (Paddle) paddleField.get(testgame);
        directionField = paddle.getClass().getDeclaredField("direction");
        directionField.setAccessible(true);
        assertEquals(0, directionField.get(paddle));
      }

      // Check that when two direction buttons are pressed, the first
      // one pressed is dominant
      {

        // Press keys, a first.
        robot.keyPress(KeyEvent.VK_A);
        // The game needs a little time to register the key
        Thread.sleep(SLEEPDELAY);
        robot.keyPress(KeyEvent.VK_D);
        // The game needs a little time to register the key
        Thread.sleep(SLEEPDELAY);

        // Gain access to the paddle after a change
        paddleField = testgame.getClass().getDeclaredField("paddle");
        paddleField.setAccessible(true);
        paddle = (Paddle) paddleField.get(testgame);
        directionField = paddle.getClass().getDeclaredField("direction");
        directionField.setAccessible(true);

        assertEquals(-1, directionField.get(paddle));

        //                // Release D. A should stay active.
        //                robot.keyRelease(KeyEvent.VK_D);
        //                // The game needs a little time to register the key. This case
        //                // may take a little longer than usual
        //                Thread.sleep(SLEEPDELAY);
        //
        //                // Gain access to the paddle after a change
        //                paddleField = testgame.getClass().getDeclaredField("paddle");
        //                paddleField.setAccessible(true);
        //                paddle = (Paddle) paddleField.get(testgame);
        //                directionField =
        //                        paddle.getClass().getDeclaredField("direction");
        //                directionField.setAccessible(true);
        //
        //                assertEquals(-1, directionField.get(paddle));
        //
        //                // Reapply D and then release A. D should go active.
        //                robot.keyPress(KeyEvent.VK_D);
        //                // The game needs a little time to register the key
        //                Thread.sleep(SLEEPDELAY);
        //                robot.keyRelease(KeyEvent.VK_A);
        //                // The game needs a little time to register the key
        //                Thread.sleep(SLEEPDELAY);
        //
        //                // Gain access to the paddle after a change
        //                paddleField = testgame.getClass().getDeclaredField("paddle");
        //                paddleField.setAccessible(true);
        //                paddle = (Paddle) paddleField.get(testgame);
        //                directionField =
        //                        paddle.getClass().getDeclaredField("direction");
        //                directionField.setAccessible(true);
        //
        //                assertEquals(1, directionField.get(paddle));
      }

    } catch (IllegalAccessException e) {
      // TODO Auto-generated catch block
      fail("Can't access the direction field.");
    } catch (NoSuchFieldException e) {
      e.printStackTrace();
      fail("The direction field does not exist.");
    } catch (AWTException e) {
      e.printStackTrace();
      fail("Can't create the testing robot.");
    } catch (InterruptedException e1) {
      // Fired when the sleep function fails
      e1.printStackTrace();
    } finally {
      robot = null;
    }
  }
示例#18
0
  public AirHockeyScene(AbstractMTApplication mtApplication, String name) {
    super(mtApplication, name);
    this.app = mtApplication;
    //		this.setClearColor(new MTColor(120,150,150));
    //		this.setClearColor(new MTColor(190, 190, 170, 255));
    this.setClearColor(new MTColor(0, 0, 0, 255));
    //		this.setClearColor(new MTColor(40, 40, 40, 255));
    this.registerGlobalInputProcessor(new CursorTracer(app, this));

    this.scorePlayer1 = 0;
    this.scorePlayer2 = 0;

    float worldOffset = 10; // Make Physics world slightly bigger than screen borders
    // Physics world dimensions
    AABB worldAABB =
        new AABB(
            new Vec2(-worldOffset, -worldOffset),
            new Vec2((app.width) / scale + worldOffset, (app.height) / scale + worldOffset));
    Vec2 gravity = new Vec2(0, 0);
    boolean sleep = true;
    // Create the pyhsics world
    this.world = new World(worldAABB, gravity, sleep);

    // Update the positions of the components according the the physics simulation each frame
    this.registerPreDrawAction(
        new UpdatePhysicsAction(world, timeStep, constraintIterations, scale));

    physicsContainer = new MTComponent(app);
    // Scale the physics container. Physics calculations work best when the dimensions are small
    // (about 0.1 - 10 units)
    // So we make the display of the container bigger and add in turn make our physics object
    // smaller
    physicsContainer.scale(scale, scale, 1, Vector3D.ZERO_VECTOR);
    this.getCanvas().addChild(physicsContainer);

    // Create borders around the screen
    this.createScreenBorders(physicsContainer);

    // Create gamefield marks
    MTLine line =
        new MTLine(
            mtApplication,
            mtApplication.width / 2f / scale,
            0,
            mtApplication.width / 2f / scale,
            mtApplication.height / scale);
    line.setPickable(false);
    //		line.setStrokeColor(new MTColor(0,0,0));
    line.setStrokeColor(new MTColor(150, 150, 150));
    line.setStrokeWeight(0.5f);
    physicsContainer.addChild(line);

    MTEllipse centerCircle =
        new MTEllipse(
            mtApplication,
            new Vector3D(mtApplication.width / 2f / scale, mtApplication.height / 2f / scale),
            80 / scale,
            80 / scale);
    centerCircle.setPickable(false);
    centerCircle.setNoFill(true);
    //		centerCircle.setStrokeColor(new MTColor(0,0,0));
    centerCircle.setStrokeColor(new MTColor(150, 150, 150));
    centerCircle.setStrokeWeight(0.5f);
    physicsContainer.addChild(centerCircle);

    MTEllipse centerCircleInner =
        new MTEllipse(
            mtApplication,
            new Vector3D(mtApplication.width / 2f / scale, mtApplication.height / 2f / scale),
            10 / scale,
            10 / scale);
    centerCircleInner.setPickable(false);
    centerCircleInner.setFillColor(new MTColor(160, 160, 160));
    //		centerCircleInner.setStrokeColor(new MTColor(150,150,150));
    //		centerCircleInner.setStrokeColor(new MTColor(0,0,0));
    centerCircleInner.setStrokeColor(new MTColor(150, 150, 150));
    centerCircleInner.setStrokeWeight(0.5f);
    physicsContainer.addChild(centerCircleInner);

    // Create the paddles
    PImage paddleTex = mtApplication.loadImage(imagesPath + "paddle.png");
    redCircle =
        new Paddle(
            app,
            new Vector3D(mtApplication.width - 60, mtApplication.height / 2f),
            50,
            world,
            1.0f,
            0.3f,
            0.4f,
            scale);
    redCircle.setTexture(paddleTex);
    redCircle.setFillColor(new MTColor(255, 50, 50));
    redCircle.setNoStroke(true);
    redCircle.setName("red");
    redCircle.setPickable(false);
    physicsContainer.addChild(redCircle);

    blueCircle =
        new Paddle(
            app, new Vector3D(80, mtApplication.height / 2f), 50, world, 1.0f, 0.3f, 0.4f, scale);
    blueCircle.setTexture(paddleTex);
    blueCircle.setFillColor(new MTColor(50, 50, 255));
    blueCircle.setNoStroke(true);
    blueCircle.setName("blue");
    blueCircle.setPickable(false);
    physicsContainer.addChild(blueCircle);

    // Create the ball
    ball =
        new HockeyBall(
            app,
            new Vector3D(mtApplication.width / 2f, mtApplication.height / 2f),
            38,
            world,
            0.5f,
            0.005f,
            0.70f,
            scale);
    //		MTColor ballCol = new MTColor(0,255,0);
    //		ball.setFillColor(ballCol);
    PImage ballTex = mtApplication.loadImage(imagesPath + "puk.png");
    ball.setTexture(ballTex);
    //		ball.setFillColor(new MTColor(160,160,160,255));
    ball.setFillColor(new MTColor(255, 255, 255, 255));
    ball.setNoStroke(true);
    ball.setName("ball");
    physicsContainer.addChild(ball);
    ball.getBody()
        .applyImpulse(
            new Vec2(ToolsMath.getRandom(-8f, 8), ToolsMath.getRandom(-8, 8)),
            ball.getBody().getWorldCenter());

    // Create the GOALS
    HockeyGoal goal1 =
        new HockeyGoal(
            new Vector3D(0, mtApplication.height / 2f),
            50,
            mtApplication.height / 4f,
            mtApplication,
            world,
            0.0f,
            0.1f,
            0.0f,
            scale);
    goal1.setName("goal1");
    goal1.setFillColor(new MTColor(0, 0, 255));
    goal1.setStrokeColor(new MTColor(0, 0, 255));
    physicsContainer.addChild(goal1);

    HockeyGoal goal2 =
        new HockeyGoal(
            new Vector3D(mtApplication.width, mtApplication.height / 2f),
            50,
            mtApplication.height / 4f,
            mtApplication,
            world,
            0.0f,
            0.1f,
            0.0f,
            scale);
    goal2.setName("goal2");
    goal2.setFillColor(new MTColor(255, 0, 0));
    goal2.setStrokeColor(new MTColor(255, 0, 0));
    physicsContainer.addChild(goal2);

    // Make two components for both game field sides to drag the puks upon
    MTRectangle leftSide =
        new MTRectangle(
            app,
            PhysicsHelper.scaleDown(0, scale),
            PhysicsHelper.scaleDown(0, scale),
            PhysicsHelper.scaleDown(app.width / 2f, scale),
            PhysicsHelper.scaleDown(app.height, scale));
    leftSide.setName("left side");
    leftSide.setNoFill(true); // Make it invisible -> only used for dragging
    leftSide.setNoStroke(true);
    leftSide.unregisterAllInputProcessors();
    leftSide.removeAllGestureEventListeners(DragProcessor.class);
    leftSide.registerInputProcessor(new DragProcessor(app));
    leftSide.addGestureListener(DragProcessor.class, new GameFieldHalfDragListener(blueCircle));
    physicsContainer.addChild(0, leftSide);
    MTRectangle rightSide =
        new MTRectangle(
            app,
            PhysicsHelper.scaleDown(app.width / 2f, scale),
            PhysicsHelper.scaleDown(0, scale),
            PhysicsHelper.scaleDown(app.width, scale),
            PhysicsHelper.scaleDown(app.height, scale));
    rightSide.setName("right Side");
    rightSide.setNoFill(true); // Make it invisible -> only used for dragging
    rightSide.setNoStroke(true);
    rightSide.unregisterAllInputProcessors();
    rightSide.removeAllGestureEventListeners(DragProcessor.class);
    rightSide.registerInputProcessor(new DragProcessor(app));
    rightSide.addGestureListener(DragProcessor.class, new GameFieldHalfDragListener(redCircle));
    physicsContainer.addChild(0, rightSide);

    // Display Score UI
    MTComponent uiLayer = new MTComponent(mtApplication, new MTCamera(mtApplication));
    uiLayer.setDepthBufferDisabled(true);
    getCanvas().addChild(uiLayer);
    IFont font = FontManager.getInstance().createFont(mtApplication, "arial", 50, MTColor.WHITE);

    t1 = new MTTextArea(mtApplication, font);
    t1.setPickable(false);
    t1.setNoFill(true);
    t1.setNoStroke(true);
    t1.setPositionGlobal(new Vector3D(5, 30, 0));
    uiLayer.addChild(t1);

    t2 = new MTTextArea(mtApplication, font);
    t2.setPickable(false);
    t2.setNoFill(true);
    t2.setNoStroke(true);
    t2.setPositionGlobal(new Vector3D(mtApplication.width - 65, 30, 0));
    uiLayer.addChild(t2);
    this.updateScores();

    // Set up check for collisions between objects
    this.addWorldContactListener(world);

    /*
    		//Sound
    		if (enableSound){
    			minim = new Minim(mtApplication);
    			wallHit = minim.loadSnippet(MT4jSettings.getInstance().getDataFolderPath() + "sound" + File.separator + "paddleBallHit.wav");
    //			paddleBallClash = minim.loadSample(MT4jSettings.getInstance().getDataFolderPath() + "sound" + File.separator + "paddleBallHit.wav", 2048);
    //			goalHit = minim.loadSnippet(MT4jSettings.getInstance().getDataFolderPath() + "sound" + File.separator + "goal.wav");
    //			goalHit.play();
    			paddleHit = minim.loadSnippet(MT4jSettings.getInstance().getDataFolderPath() + "sound" + File.separator + "wallHit.wav");
    		}
    		*/
  }
示例#19
0
 private void aiFollow(Paddle cpu) {
   cpu.destination = (int) mBall.x;
   cpu.move(true);
 }
示例#20
0
 /**
  * Tells us if the ball collides with a rectangle.
  *
  * @param r, the rectangle
  * @return true if the ball is colliding, false if not
  */
 public boolean collides(Paddle p) {
   return p.collides(this);
 }
示例#21
0
 public boolean gameRunning() {
   return mInitialized && mRed != null && mBlue != null && mRed.living() && mBlue.living();
 }
示例#22
0
 /** Resets the lives and the position of the paddles. */
 private void resetPaddles() {
   int mid = getWidth() / 2;
   mRed.setPosition(mid);
   mBlue.setPosition(mid);
   mGreen.setPosition(mid);
   mYellow.setPosition(mid);
   mCyan.setPosition(mid);
   mOrange.setPosition(mid);
   mRed.destination = mid;
   mBlue.destination = mid;
   mGreen.destination = mid;
   mYellow.destination = mid;
   mCyan.destination = mid;
   mOrange.destination = mid;
   mRed.setLives(STARTING_LIVES);
   mBlue.setLives(STARTING_LIVES);
 }
示例#23
0
  /**
   * A generalized Pong AI player. Takes a Rect object and a Ball, computes where the ball will be
   * when ball.y == rect.y, and tries to move toward that x-coordinate. If the ball is moving
   * straight it will try to clip the ball with the edge of the paddle.
   *
   * @param cpu
   */
  private void aiPrediction(Paddle cpu, Paddle opponent) {
    Ball ball = new Ball(mBall);

    // Special case: move torward the center if the ball is blinking
    if (mBall.serving()) {
      cpu.destination = getWidth() / 2;
      cpu.move(true);
      return;
    }

    // Something is wrong if vy = 0.. let's wait until things fix themselves
    if (ball.vy == 0) return;

    // Y-Distance from ball to Rect 'cpu'
    float cpuDist = Math.abs(ball.y - cpu.centerY());
    // Y-Distance to opponent.
    float oppDist = Math.abs(ball.y - opponent.centerY());

    // Distance between two paddles.
    float paddleDistance = Math.abs(cpu.centerY() - opponent.centerY());

    // Is the ball coming at us?
    boolean coming =
        (cpu.centerY() < ball.y && ball.vy < 0) || (cpu.centerY() > ball.y && ball.vy > 0);

    // Total amount of x-distance the ball covers
    float total =
        ((((coming) ? cpuDist : oppDist + paddleDistance)) / Math.abs(ball.vy)) * Math.abs(ball.vx);

    // Playable width of the stage
    float playWidth = getWidth() - 2 * Ball.RADIUS;

    float wallDist = (ball.goingLeft()) ? ball.x - Ball.RADIUS : playWidth - ball.x + Ball.RADIUS;

    // Effective x-translation left over after first bounce
    float remains = (total - wallDist) % playWidth;

    // Bounces the ball will incur
    int bounces = (int) ((total) / playWidth);

    boolean left = (bounces % 2 == 0) ? !ball.goingLeft() : ball.goingLeft();

    cpu.destination = getWidth() / 2;

    // Now we need to compute the final x. That's all that matters.
    if (bounces == 0) {
      cpu.destination = (int) (ball.x + total * Math.signum(ball.vx));
    } else if (left) {
      cpu.destination = (int) (Ball.RADIUS + remains);
    } else { // The ball is going right...
      cpu.destination = (int) ((Ball.RADIUS + playWidth) - remains);
    }

    // Try to give it a little kick if vx = 0
    int salt = (int) (System.currentTimeMillis() / 10000);
    Random r = new Random((long) (cpu.centerY() + ball.vx + ball.vy + salt));
    int width = cpu.getWidth();
    cpu.destination =
        (int)
            bound(
                cpu.destination + r.nextInt(2 * width - (width / 5)) - width + (width / 10),
                0,
                getWidth());
    cpu.move(true);
  }
示例#24
0
  /** Paints the game! */
  @Override
  public void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    if (mInitialized == false) {
      return;
    }

    Context context = getContext();

    // Draw the paddles / touch boundaries
    mRed.draw(canvas);
    mBlue.draw(canvas);
    mSnowy.draw(canvas);

    mGreen.draw(canvas);
    mYellow.draw(canvas);
    mOrange.draw(canvas);
    mCyan.draw(canvas);

    // Draw touchboxes if needed
    if (gameRunning() && mRed.player && mCurrentState == State.Running) mRed.drawTouchbox(canvas);

    if (gameRunning() && mBlue.player && mCurrentState == State.Running) mBlue.drawTouchbox(canvas);

    // Draw ball stuff
    mPaint.setStyle(Style.FILL);
    mPaint.setColor(Color.YELLOW);
    mBall.draw(canvas);

    // If either is a not a player, blink and let them know they can join in!
    // This blinks with the ball.
    if (mBall.serving()) {
      String join = context.getString(R.string.join_in);
      int joinw = (int) mPaint.measureText(join);

      if (!mRed.player) {
        mPaint.setColor(Color.MAGENTA);
        canvas.drawText(join, getWidth() / 2 - joinw / 2, mRed.touchCenterY(), mPaint);
      }

      if (!mBlue.player) {
        mPaint.setColor(Color.CYAN);
        canvas.drawText(join, getWidth() / 2 - joinw / 2, mBlue.touchCenterY(), mPaint);
      }
    }

    // Show where the player can touch to pause the game
    if (mBall.serving()) {
      String pause = context.getString(R.string.pause);
      int pausew = (int) mPaint.measureText(pause);

      mPaint.setColor(Color.GREEN);
      mPaint.setStyle(Style.STROKE);
      mPaint.setTextSize(36);
      canvas.drawRect(mPauseTouchBox, mPaint);
      canvas.drawText(pause, getWidth() / 2 - pausew / 2, getHeight() / 2, mPaint);
    }

    // Paint a PAUSED message
    if (gameRunning() && mCurrentState == State.Stopped) {
      String s = context.getString(R.string.paused);
      int width = (int) mPaint.measureText(s);
      int height = (int) (mPaint.ascent() + mPaint.descent());

      mPaint.setColor(Color.WHITE);
      canvas.drawText(s, getWidth() / 2 - width / 2, getHeight() / 3 - height / 2, mPaint);
    }

    // Draw a 'lives' counter
    mPaint.setColor(Color.YELLOW);
    mPaint.setStyle(Style.FILL_AND_STROKE);
    for (int i = 0; i < mRed.getLives(); i++) {
      canvas.drawCircle(
          Ball.RADIUS + PADDING + i * (2 * Ball.RADIUS + PADDING),
          PADDING + Ball.RADIUS,
          Ball.RADIUS,
          mPaint);
    }

    for (int i = 0; i < mBlue.getLives(); i++) {
      canvas.drawCircle(
          Ball.RADIUS + PADDING + i * (2 * Ball.RADIUS + PADDING),
          getHeight() - PADDING - Ball.RADIUS,
          Ball.RADIUS,
          mPaint);
    }

    // Announce the winner!
    if (!gameRunning()) {
      mPaint.setColor(Color.MAGENTA);
      String s = "You both lose";

      if (!mBlue.living()) {
        s = context.getString(R.string.red_wins);
        mPaint.setColor(Color.MAGENTA);
      } else if (!mRed.living()) {
        s = context.getString(R.string.blue_wins);
        mPaint.setColor(Color.CYAN);
      }

      int width = (int) mPaint.measureText(s);
      int height = (int) (mPaint.ascent() + mPaint.descent());
      canvas.drawText(s, getWidth() / 2 - width / 2, getHeight() / 2 - height / 2, mPaint);
    }
  }
示例#25
0
  private void initializePaddles() {
    // Order from top to bottom; Red, Green, Orange, Cyan, Yellow, Blue

    Rect redTouch = new Rect(0, 0, getWidth(), getHeight() / 8);
    Rect blueTouch = new Rect(0, 7 * getHeight() / 8, getWidth(), getHeight());
    Rect greenTouch = new Rect(0, 4 * getHeight() / 16, getWidth(), (getHeight() / 16) * 5);
    Rect orangeTouch = new Rect(0, 6 * getHeight() / 16, getWidth(), (getHeight() / 16) * 7);
    Rect yellowTouch = new Rect(0, 11 * getHeight() / 16, getWidth(), (getHeight() / 4) * 3);
    Rect cyanTouch = new Rect(0, 9 * getHeight() / 16, getWidth(), (getHeight() / 16) * 10);

    mRed = new Paddle(Color.RED, redTouch.bottom + PADDING);
    mBlue = new Paddle(Color.BLUE, blueTouch.top - PADDING - Paddle.PADDLE_THICKNESS);
    mGreen = new Paddle(Color.GREEN, greenTouch.centerY() + PADDING);
    mYellow = new Paddle(Color.YELLOW, yellowTouch.centerY() + PADDING);
    mOrange = new Paddle(Color.rgb(255, 128, 0), orangeTouch.centerY() + PADDING);
    mCyan = new Paddle(Color.rgb(0, 255, 255), cyanTouch.centerY() + PADDING);

    mRed.setTouchbox(redTouch);
    mBlue.setTouchbox(blueTouch);
    mGreen.setTouchbox(greenTouch);
    mYellow.setTouchbox(yellowTouch);
    mOrange.setTouchbox(orangeTouch);
    mCyan.setTouchbox(cyanTouch);

    mRed.setHandicap(mCpuHandicap);
    mBlue.setHandicap(mCpuHandicap);
    mGreen.setHandicap(mCpuHandicap);
    mYellow.setHandicap(mCpuHandicap);
    mOrange.setHandicap(mCpuHandicap);
    mCyan.setHandicap(mCpuHandicap);

    mRed.player = mRedPlayer;
    mBlue.player = mBluePlayer;

    mRed.setSlave(mOrange);
    mBlue.setSlave(mCyan);
    mOrange.setSlave(mYellow);
    mCyan.setSlave(mGreen);

    mRed.setLives(STARTING_LIVES + mLivesModifier);
    mBlue.setLives(STARTING_LIVES + mLivesModifier);
  }
示例#26
0
  // Constructor//
  public Game_Screen() {
    JFrame game_frame = new JFrame("Legend of Pong"); // creates the jframe
    JLabel Background =
        new JLabel(
            new ImageIcon(
                "C:\\Users\\Daniel\\workspace\\Pong_Game\\src\\resources\\Pics\\gameScreen.jpg")); // gets the BG image
    game_frame.setContentPane(Background); // places background image

    // setting the header section//

    // Score//
    long score = getScore(); // int to hold score value
    JLabel scoreL = new JLabel(); // label to display score
    scoreL.setText("Score: " + String.valueOf(score)); // connects label and int
    scoreL.setBounds(25, 15, 200, 35); // sets location of score
    scoreL.setFont(new Font("Courier New", Font.BOLD, 20)); // sets font and size of font
    scoreL.setForeground(Color.GREEN); // sets color of Score
    game_frame.add(scoreL); // adds score

    // Timer//
    int time = getTime();
    JLabel timeL = new JLabel(); // label to hold time
    timeL.setText("Time(sec): " + String.valueOf(time)); // connects label and int
    timeL.setBounds(350, 15, 200, 35); // set location of time
    timeL.setFont(new Font("Courier New", Font.BOLD, 20)); // sets font and size of font
    timeL.setForeground(Color.GREEN); // sets color
    game_frame.add(timeL); // adds time

    // Life//
    int life = getLife(); // int to hold value of lives left
    JLabel lifeL = new JLabel(); // label to hold life
    lifeL.setText("Lives: " + String.valueOf(life)); // connects label and int
    lifeL.setBounds(700, 15, 200, 35); // sets location of life
    lifeL.setFont(new Font("Courier New", Font.BOLD, 20)); // sets font and size of font
    lifeL.setForeground(Color.GREEN); // sets color of life
    game_frame.add(lifeL); // adds life

    // Paddle//
    JPanel paddle = new JPanel(); // new panel for paddle object and image
    Paddle object = new Paddle(); // creates new paddle object
    JLabel link =
        new JLabel(
            new ImageIcon(
                "C:\\Users\\Daniel\\workspace\\Pong_Game\\src\\resources\\Pics\\Link.gif")); // new
                                                                                             // paddle image(also link)
    paddle.add(object); // adds the actual object
    paddle.add(link); // adds image to the paddle Panel
    paddle.setBounds(
        object.getX(),
        object.getY(),
        object.getWidth(),
        object.getHeight()); // sets location and size of the paddle
    game_frame.add(paddle); // game_frame gets link image

    // a single ball = test //
    JPanel ball = new JPanel(); // creates the JPanel to hold the ball object and image
    Ball obj = new Ball(); // creates the ball object
    JLabel stone =
        new JLabel(
            new ImageIcon(
                "C:\\Users\\Daniel\\workspace\\Pong_Game\\src\\resources\\Pics\\Ball.png")); // creates the ball image
    ball.add(obj); // adds the object
    ball.add(stone); // adds the image
    ball.setBounds(750, 250, obj.getWidth(), obj.getHeight()); // sets ball location and size
    game_frame.add(ball); // adds it to the screen

    // final frame things//
    game_frame.pack();
    game_frame.setResizable(false);
    game_frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    game_frame.setVisible(true);
  } // end of screen constructor
示例#27
0
  /**
   * Touching is the method of movement. Touching the touchscreen, that is. A player can join in
   * simply by touching where they would in a normal game.
   */
  public boolean onTouch(View v, MotionEvent mo) {
    if (v != this || !gameRunning()) return false;

    // We want to support multiple touch and single touch
    InputHandler handle = InputHandler.getInstance();

    // Loop through all the pointers that we detected and
    // process them as normal touch events.
    for (int i = 0; i < handle.getTouchCount(mo); i++) {
      int tx = (int) handle.getX(mo, i);
      int ty = (int) handle.getY(mo, i);

      // Bottom paddle moves when we are playing in one or two player mode and the touch
      // was in the lower quartile of the screen.
      if (mBlue.player && mBlue.inTouchbox(tx, ty)) {
        mBlue.destination = tx;
        mGreen.destination = tx;
        mCyan.destination = tx;
      } else if (mRed.player && mRed.inTouchbox(tx, ty)) {
        mRed.destination = tx;
        mYellow.destination = tx;
        mOrange.destination = tx;
      } else if (mo.getAction() == MotionEvent.ACTION_DOWN && mPauseTouchBox.contains(tx, ty)) {
        if (mCurrentState != State.Stopped) {
          mLastState = mCurrentState;
          mCurrentState = State.Stopped;
        } else {
          mCurrentState = mLastState;
          mLastState = State.Stopped;
        }
      }

      // In case a player wants to join in...
      if (mo.getAction() == MotionEvent.ACTION_DOWN) {
        if (!mBlue.player && mBlue.inTouchbox(tx, ty)) {
          mBlue.player = true;
        } else if (!mRed.player && mRed.inTouchbox(tx, ty)) {
          mRed.player = true;
        }
      }
    }

    return true;
  }
示例#28
0
 private void aiExact(Paddle cpu) {
   cpu.destination = (int) mBall.x;
   cpu.setPosition(cpu.destination);
 }
示例#29
0
  public void paint(Graphics g) {
    // set up the double buffering to make the game animation nice and smooth
    Graphics2D twoDGraph = (Graphics2D) g;

    // take a snap shop of the current screen and same it as an image
    // that is the exact same width and height as the current screen
    if (back == null) back = (BufferedImage) (createImage(getWidth(), getHeight()));

    // create a graphics reference to the back ground image
    // we will draw all changes on the background image
    Graphics graphToBack = back.createGraphics();

    if (lives < 1) {
      ball.setXSpeed(0);
      ball.setYSpeed(0);
      paddle.setSpeed(0);
      graphToBack.drawString("GAME OVER", 387, 30);
    } else if (bricks.isEmpty()) {
      ball.setXSpeed(0);
      ball.setYSpeed(0);
      paddle.setSpeed(0);
      graphToBack.drawString("YOU WIN", 387, 30);
    }

    ball.moveAndDraw(graphToBack);
    paddle.draw(graphToBack);
    for (Block x : bricks) {
      x.draw(graphToBack);
    }
    graphToBack.setColor(Color.white);
    graphToBack.drawString(score + ":" + lives, 387, 15);

    if (ball.didCollide(left) || ball.didCollide(right)) {
      ball.setXSpeed(-ball.getXSpeed());
    }

    if (ball.didCollide(top)) {
      ball.setYSpeed(-ball.getYSpeed());
    }

    if (ball.didCollide(bottom)) {
      ball.draw(graphToBack, Color.white);
      ball.setXSpeed(2);
      ball.setYSpeed(2);
      ball.setX(400);
      ball.setY(500);
      lives--;
      ball.setYSpeed(-ball.getYSpeed());
    }

    // see if the ball hits the paddle
    if (ball.didCollide(paddle)) ball.setYSpeed(-ball.getYSpeed());

    // brick collision
    for (Block x : bricks) {
      if (x.didCollide(ball)) {
        score++;
        x.draw(graphToBack, Color.white);
        bricks.remove(x);
        if (ball.didCollideTop(x) || ball.didCollideBottom(x)) ball.setYSpeed(-ball.getYSpeed());
        else ball.setXSpeed(-ball.getXSpeed());
      }
    }
    // see if the paddles need to be moved
    graphToBack.setColor(Color.black);
    graphToBack.drawString(score + ":" + lives, 387, 15);

    if (keys[0]) paddle.moveLeftAndDraw(graphToBack);
    if (keys[1]) paddle.moveRightAndDraw(graphToBack);

    twoDGraph.drawImage(back, null, 0, 0);
  }
示例#30
0
  public void run() {
    while (true) {
      if (t < 5) {
        t++;
      } else {
        t = 0;
      }
      if (mainMenu) {

        // Ball is bounced if its x - position reaches the right border of the applet
        if (posy_cursor < posy_new) {

          // Change direction of ball movement
          posy_cursor += 50;

        }
        // Ball is bounced if its x - position reaches the left border of the applet
        else if (posy_cursor > posy_highscores) {

          // Change direction of ball movement
          posy_cursor -= 50;
        }
      } else if (gamePlaying) {
        ball.move();
        if (ball.y_Pos() < 0) {
          ball.reflectVertically();

        } else if ((ball.x_Pos() < 0) || (ball.x_Pos() > appletsize_x)) {
          ball.reflectHorizontally();
        }

        if (ball.y_Pos() > 590) {

          if ((ball.x_Pos() > pad.x() - ball.radius())
              && ((ball.x_Pos() < pad.x() + (pad.width() / 2)))) {
            ball.reflectFromPaddle(LEFT);
          } else if ((ball.x_Pos() > pad.x() + (pad.width() / 2))
              && ((ball.x_Pos() < pad.x() + pad.width + ball.radius()))) {
            ball.reflectFromPaddle(RIGHT);
          } else {
            ball.startBall();
          }
        }

        for (int x = 0; x < numBricksX; x++) {
          for (int y = 0; y < numBricksY; y++) {
            if (brickWall[x][y].notBroken()) {
              if (brickWall[x][y].ballContactVertical(ball.x_Pos(), ball.y_Pos())) {
                ball.reflectVertically();
                brickWall[x][y].reduceLife();
                brickWall[x][y].startDropping();
              } else if (brickWall[x][y].ballContactHorizontal(ball.x_Pos(), ball.y_Pos())) {
                ball.reflectHorizontally();
                brickWall[x][y].reduceLife();
                brickWall[x][y].startDropping();
              }
            }
          }
        }
      }
      if (t == 5) {
        for (int x = 0; x < numBricksX; x++) {
          for (int y = 0; y < numBricksY; y++) {
            brickWall[x][y].dropPowerUp();
            if (brickWall[x][y].paddleContact(pad.xPos, 590)) {
              pad.widthIncrease();
            }
          }
        }
      }

      try {
        // Stop thread for 20 milliseconds
        Thread.sleep(2);
      } catch (InterruptedException ex) {
        // do nothing
      }

      repaint();
    }
  }