Question

JavaFX programming (Not Javascript) Using the code from BallPane.java and BounceBallControl.java create a "Pong for One"...

JavaFX programming (Not Javascript)

Using the code from BallPane.java and BounceBallControl.java

create a "Pong for One" game -

a rectangular paddle moves back and forth via mouse drag along the bottom of the pane;

the bottom of the paddle should be about 1/2 the diameter of the ball off the bottom.

If the ball connects with the paddle, then it bounces at a 90 degree angle back into the pane space.

If the ball misses the paddle, then the score is decremented by 1.

The game ends when 20 points are lost.

Nice things:

A label that displays the score (you can start at 20 and go to zero if you want...)

For every 10 paddle connections in a row, the ball moves faster

For every 10 paddle connections in a row, the ball changes color

For every (2?) paddle misses in a row, the paddle grows in length

There is MATH involved in figuring out the connection between the paddle and the ball.

You probably want to pay a lot of attention to how moveBall() works.

JavaFX programming (Not Javascript)

JavaFX programming (Not Javascript)

JavaFX programming (Not Javascript)

JavaFX programming (Not Javascript)

-----------------------------------------------------------------------------------------------------------------------

BallPane.java

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.beans.property.DoubleProperty; 4 import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.util.Duration;

public class BallPane extends Pane {

public final double radius = 20;

private double x = radius, y = radius;

private double dx = 1, dy = 1;

private Circle circle = new Circle(x, y, radius);

private Timeline animation;

public BallPane() {

circle.setFill(Color.GREEN); // Set ball color

getChildren().add(circle); // Place a ball into this pane

animation = new Timeline(

new KeyFrame(Duration.millis(50), e -> moveBall()));

animation.setCycleCount(Timeline.INDEFINITE);

animation.play(); // Start animation

}
public void play(){

animation.play();

}

public void pause() {

animation.pause();

}

public void increaseSpeed() {

animation.setRate(animation.getRate() + 0.1);

}

public void decreaseSpeed() {

animation.setRate(

animation.getRate() > 0 ? animation.getRate() - 0.1 : 0);

}

public DoubleProperty rateProperty() {

return animation.rateProperty();

}

protected void moveBall() {

if (x < radius || x > getWidth() - radius) {

dx *= -1;}

if (y < radius || y > getHeight() - radius) {

dy *= -1; }

x += dx;

y += dy;

circle.setCenterX(x);

circle.setCenterY(y);

} }

--------------------------------------------------------------------------------------------------------

BounceBallControl.java

import javafx.application.Application;

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;


public class BounceBallControl extends Application {

@Override 

public void start(Stage primaryStage) {

BallPane ballPane = new BallPane(); // Create a ball pane

ballPane.setOnMousePressed(e -> ballPane.pause());

ballPane.setOnMouseReleased(e -> ballPane.play());

ballPane.setOnKeyPressed(e -> {

if (e.getCode() == KeyCode.UP) {

ballPane.increaseSpeed();

}

else if (e.getCode() == KeyCode.DOWN) {

ballPane.decreaseSpeed();

}

});

Scene scene = new Scene(ballPane, 250, 150);

primaryStage.setTitle("BounceBallControl"); // Set the stage title

primaryStage.setScene(scene); // Place the scene in the stage

primaryStage.show(); // Display the stage

ballPane.requestFocus();

}

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

I think the code you using not clearly explains me , the following code works well for ping pong game.

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import java.applet.*;
import java.awt.*;
 
 
 
public class GAME extends  Applet implements Runnable  ,MouseMotionListener,MouseListener {
     
    private final int UP = 38;
    private final int DOWN = 40;
    private Player myPlayer;
    private Computer myComp;
    private Ball myBall;
    private Image  dbImage;
    private Image GameName;
    private AudioClip kicknoise;
    private Graphics dbg;
    private Thread th;
    private boolean GAME_STARTED;
    private boolean GAME_OPTION;
    private boolean GAME_OVER;
    private int CScore=0;
    private int PScore=0   ;
    private int TopScore=5;
     
    public void init() {
        GAME_OPTION=true;
        GAME_STARTED=false;
        GAME_OVER=false;
        CScore=0;
        PScore=0;
        TopScore=5;
        myPlayer=new Player(20,125,10,50,Color.GREEN.darker());
        myComp=new Computer(370,124,10,50,Color.RED);
        myBall=new Ball(8,200,150,2,-2,Color.blue,this);
         
        
         
         
        addMouseMotionListener(this);
        addMouseListener(this);
        kicknoise = getAudioClip(getCodeBase(), "hit.au");
         
        GameName=
 ((Applet) this).getImage(((Applet) this).getCodeBase(), "images/gamename.gif");
         
         
    }
    public void start() {
         
    }
    public void stop() {
        th.interrupt();
    }
     
    public void paint(Graphics g) {
        if(GAME_OPTION) {
            Image codemiles=
((Applet) this).getImage(((Applet) this).getCodeBase(), "images/codemiles.gif");
             
            g.setColor(Color.GRAY);
             
            g.fillRect(0,0,400,400);
            g.setColor(Color.white);
             
            g.drawString("Press Mouse Click To Start Ball Sticker",100,100);
            g.drawImage(codemiles,150,150,this);
            g.drawString("Visit us ",35,250);
            g.drawImage( GameName,100,275,this);
             
        } else if(GAME_STARTED) {
            g.fillRect(0,0,400,300);
             
            myPlayer.DrawStrick(g);
            myComp.DrawStrick(g);
            myBall.DrawBall(g);
            g.setColor(Color.YELLOW);
            g.drawLine(25,32,375,32);
            g.drawLine(25,292,375,292);
            g.setColor(Color.GRAY);
            g.fillRect(400,300,400,100);
            g.setColor(Color.BLACK);
            g.drawString("Player Score :"+Integer.toString(PScore),50,350);
            g.drawString("Computer Score :"+Integer.toString(CScore),250,350);
             
        }
    }
     
    public void update(Graphics g) {
         
        if (dbImage == null) {
            dbImage = createImage(this.getSize().width, this.getSize().height);
            dbg = dbImage.getGraphics();
        }
         
         
        dbg.setColor(getBackground());
        dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
         
         
        dbg.setColor(getForeground());
        paint(dbg);
      
         
        g.drawImage(dbImage, 0, 0, this);
    }
    public void run() {
        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
         
        while (true) {
             
             
             
            repaint();
            myBall.move();
             
             
            myComp.ComputerMove(myBall);
             
             
            int  whosgoal = myBall.wheresBall();
             
             
            if (whosgoal != 0) {
                if(whosgoal==1)
                    CScore++;
                else
                    PScore++;
                 
                if(PScore==5) {
                    GAME_STARTED=false;
                    GAME_OVER=GAME_OPTION=true;
                    th.interrupt();
                      repaint();
                }else if(CScore==5) {
                    GAME_STARTED=false;
                    GAME_OVER=GAME_OPTION=true;
                    th.interrupt();
                      repaint();
                }
                 
                myBall.x= 200;
                myBall.vx = 3;
                myBall.vy = -3;
                 
                 
            }
             
             
             
             
             
            if (myBall.vx < 0) {
                myBall.PCollision(myPlayer,kicknoise);
            } else if (myBall.vx > 0) {
                myBall.CCollision(myComp,kicknoise);
            }
             
            try {
                 
                Thread.sleep(15);
            } catch (InterruptedException ex) {
                break;
            }
             
             
            Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        }
         
    }
     
     
     
     
     
    public void mouseDragged(MouseEvent e) {
    }
     
    public void mouseMoved(MouseEvent e) {
        int y=e.getY();
        if(y<250&&y>25)
            myPlayer.MoveByMouse(y);
         
    }
     
    public void mouseClicked(MouseEvent e) {
         
        if(!GAME_STARTED) {
            GAME_STARTED=true;
            GAME_OPTION=false;
            CScore=0;
            PScore=0;
            TopScore=5;
             
            myBall.vx = 3;
            myBall.vy = -3;
            th=new Thread(this);
            th.start();
             
        }
    }
     
    public void mousePressed(MouseEvent e) {
    }
     
    public void mouseReleased(MouseEvent e) {
    }
     
    public void mouseEntered(MouseEvent e) {
    }
     
    public void mouseExited(MouseEvent e) {
    }
     
     
}

Hope it is useful :)

Add a comment
Know the answer?
Add Answer to:
JavaFX programming (Not Javascript) Using the code from BallPane.java and BounceBallControl.java create a "Pong for One"...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • JavaFX! Just need to fill several lanes of code please!!! CSE205 OOP and Data Structure Quiz #15 Last Name (print) First Name (print) Write a JavaFX GUI application program that simulates a timer. T...

    JavaFX! Just need to fill several lanes of code please!!! CSE205 OOP and Data Structure Quiz #15 Last Name (print) First Name (print) Write a JavaFX GUI application program that simulates a timer. The timer should show "count: the beginning and increase the number by 1 in every one second, and so on. o" at .3 A Timer - × A Timer Count: 0 Count: 1 (B) After 1 second, the GUI Window (A) Initial GUI Window According to the...

  • Write a JavaFX application that displays 10,000 very small circles (radius of 1 pixel) in random...

    Write a JavaFX application that displays 10,000 very small circles (radius of 1 pixel) in random locations within the visible area. Fill the dots on the left half of the scene red and the dots on the right half of the scene green. Use the getWidth method of the scene to help determine the halfway point. This is what I have so far: import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.shape.Circle; import javafx.scene.paint.Color; import javafx.stage.Stage; import java.util.Random; import javafx.scene.Group; public class Class615...

  • Java Programming Assignment (JavaFX required). You will modify the SudokuCheckApplication program that is listed below. Start...

    Java Programming Assignment (JavaFX required). You will modify the SudokuCheckApplication program that is listed below. Start with the bolded comment section in the code below. Create a class that will take string input and process it as a multidimensional array You will modify the program to use a multi-dimensional array to check the input text. SudokuCheckApplication.java import javafx.application.*; import javafx.event.*; import javafx.geometry.*; import javafx.scene.*; import javafx.scene.control.*; import javafx.scene.layout.*; import javafx.stage.*; public class SudokuCheckApplication extends Application { public void start(Stage primaryStage)...

  • 15.3 (Move the ball) Write a program that moves the ball in a pane. You should...

    15.3 (Move the ball) Write a program that moves the ball in a pane. You should define a pane class for displaying the ball and provide the methods for moving the ball left, right, up, and down, as shown in Figure 15.24c. Check the boundary to prevent the ball from moving out of sight completely. import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.shape.Circle; import javafx.stage.Stage; public class Driver extends Application...

  • //No JPanel please: Write a javafx application that displays an image and //plays a sound effect...

    //No JPanel please: Write a javafx application that displays an image and //plays a sound effect with each mouse click. Rotate through four images and //five sound effects, so the image/sound effect pairing is different each time. //What my problem is on is actually getting the pictures to switch. The x variable //works perfect for the sound change but I am unsure what to do with y for the //image change. Also I dont know if I should put this...

  • For this question you will need to complete the methods to create a JavaFX GUI application...

    For this question you will need to complete the methods to create a JavaFX GUI application that implements two String analysis algorithms. Each algorithm is activated when its associated button is pressed. They both take their input from the text typed by the user in a TextField and they both display their output via a Text component at the bottom of the GUI, which is initialized to “Choose a string methods as indicated in the partially completed class shown after...

  • use this code of converting Km to miles , to create Temperature converter by using java...

    use this code of converting Km to miles , to create Temperature converter by using java FX import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.geometry.Pos; import javafx.geometry.Insets; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.control.Button; import javafx.event.EventHandler; import javafx.event.ActionEvent; /** * Kilometer Converter application */ public class KiloConverter extends Application { // Fields private TextField kiloTextField; private Label resultLabel; public static void main(String[] args) { // Launch the application. launch(args); } @Override public void start(Stage primaryStage) { //...

  • Create a FRACTAL Javafx program ; it should draw some kind of fractal image ( a...

    Create a FRACTAL Javafx program ; it should draw some kind of fractal image ( a pattern that repeats). .... you can start with code similar to this (but I DO NOT want you just doing this simple one.. do a more complex image) //call the following method from your start() method after you create an empty pane (start with your drawHouse code that you did last week): Pane pane = new Pane(); //create an empty pane drawCircle(pane, 50,50, 20);  //draw...

  • CS 1181 - Lab 03 The due date for every lab assignment is found in the...

    CS 1181 - Lab 03 The due date for every lab assignment is found in the course’s Pilot drop box. POINTS: 10 PURPOSE: This lab will introduce you to Java’s framework for working with simple graphics, as well as the concept of an animation loop and dialog boxes for I/O. PROCEDURES: You are provided with a “starter” Project for this lab. Import this project file (In NetBeans Use File->Import->From Zip). CS1181BallPanel uses JavaFX to display an animation of two balls...

  • Modify the JavaFX TipCalculator application program to allow the user to enter the number of persons...

    Modify the JavaFX TipCalculator application program to allow the user to enter the number of persons in the party through a text field. Calculate and display the amount owed by each person in the party if the bill is to be split evenly among the party members. /////////// TipCalculatorController.java: import java.math.BigDecimal; import java.math.RoundingMode; import java.text.NumberFormat; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.Slider; import javafx.scene.control.TextField; public class TipCalculatorController { // formatters for currency and percentages private...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT