0

My question is how to fix my code so that when the application is run it will accept the keyboard inputs. Now then, I do have most of the code needed, but I am unsure what I am missing to get it to work.

Now please note, this program was made using Eclipse Luna(latest version) and JavaFX that used Scenebuilder to build the GUI, so please make sure everything that is for the solution will work with these aspects in mind.

Now then my code. Also by all means just take my code and repasted it with the corrections, so long as you can explain it alongside it. Just having one or the other is not going to be as effective as having both.

My PongController Class where everything was made

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.fxml.FXML;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.util.Duration;
import java.util.Random;

public class PongController {

final int PADDLE_MOVEMENT_INCREMENT = 7;
final int BALL_MOVEMENT_INCREMENT = 3;

double centerTableY;

DoubleProperty currentUserPaddleY = new SimpleDoubleProperty();
DoubleProperty currentComputerPaddleY = new SimpleDoubleProperty();
double initialComputerPaddleY;

DoubleProperty ballCenterX = new SimpleDoubleProperty();
DoubleProperty ballCenterY = new SimpleDoubleProperty();

double allowedPaddleTopY;
double allowedPaddleBottomY;

Timeline timeline;

@FXML
Rectangle table;
@FXML  
Rectangle compPaddle;
@FXML  
Rectangle userPaddle;
@FXML  
Circle ball;

public void initialize() {

    currentUserPaddleY.set(userPaddle.getLayoutY());
    userPaddle.layoutYProperty().bind(currentUserPaddleY);

    ballCenterX.set(ball.getCenterX());
    ballCenterY.set(ball.getCenterY());

    ball.centerXProperty().bind(ballCenterX);
    ball.centerYProperty().bind(ballCenterY);


    initialComputerPaddleY = compPaddle.getLayoutY();
    currentComputerPaddleY.set(initialComputerPaddleY);
    compPaddle.layoutYProperty().bind(currentComputerPaddleY);


    allowedPaddleTopY = PADDLE_MOVEMENT_INCREMENT;
    allowedPaddleBottomY = table.getHeight() - userPaddle.getHeight() - PADDLE_MOVEMENT_INCREMENT;

    centerTableY = table.getHeight()/2;
 }

public void keyReleasedHandler(KeyEvent event){

    KeyCode keyCode = event.getCode();

    switch (keyCode){
        case UP:
            process_key_Up();
            break;
        case DOWN:
            process_key_Down();
            break;
        case S:
            process_key_S();
            break;
    default:
        break;
    }
}


private void process_key_Up() {

    if (currentUserPaddleY.get() > allowedPaddleTopY) {
        currentUserPaddleY.set(currentUserPaddleY.get() - PADDLE_MOVEMENT_INCREMENT);
    }
}

private void process_key_Down() {

    if (currentUserPaddleY.get()< allowedPaddleBottomY) {
        currentUserPaddleY.set(currentUserPaddleY.get() + PADDLE_MOVEMENT_INCREMENT);
    }
}

private void process_key_S() {
    ballCenterY.set(currentUserPaddleY.doubleValue() + userPaddle.getHeight()/2);
    ballCenterX.set(userPaddle.getLayoutX());
    moveTheBall();
}

private void moveTheBall(){

    Random randomYGenerator = new Random();
    double randomYincrement = randomYGenerator.nextInt(BALL_MOVEMENT_INCREMENT);

    final boolean isServingFromTop = (ballCenterY.get() <= centerTableY)?true:false;

    KeyFrame keyFrame = new KeyFrame(new Duration(10), event -> {
        if (ballCenterX.get() >= -20) {
            ballCenterX.set(ballCenterX.get() - BALL_MOVEMENT_INCREMENT);

            if (isServingFromTop) {
                ballCenterY.set(ballCenterY.get() + randomYincrement);
                currentComputerPaddleY.set( currentComputerPaddleY.get() + 1);

            } 

            else {
                ballCenterY.set(ballCenterY.get() - randomYincrement);

                currentComputerPaddleY.set(currentComputerPaddleY.get() - 1);
            }

            if(checkForBallPaddleContact(compPaddle)){
                timeline.stop();
                currentComputerPaddleY.set(initialComputerPaddleY);
                bounceTheBall();
            };

         } 
        else {
            timeline.stop();
            currentComputerPaddleY.set(initialComputerPaddleY);
         }
        updateScore();
     });

    timeline = new Timeline(keyFrame);
    timeline.setCycleCount(Timeline.INDEFINITE);

    timeline.play();
 }


 private boolean checkForBallPaddleContact(Rectangle paddle){
     if (ball.intersects(paddle.getBoundsInParent())){
         return true;
     } else {
          return false;
     }
 }

 private void bounceTheBall() {
     double theBallOffTheTableX = table.getWidth() + 20;

     KeyFrame keyFrame = new KeyFrame(new Duration(10), event -> {

         if (ballCenterX.get() < theBallOffTheTableX) {
             ballCenterX.set(ballCenterX.get() + BALL_MOVEMENT_INCREMENT);
             if (checkForBallPaddleContact(userPaddle)){
                 timeline.stop();
                 moveTheBall();
             };

         } 
         else {
             timeline.stop();
         }
         updateScore();
     });

     timeline = new Timeline(keyFrame);
     timeline.setCycleCount(Timeline.INDEFINITE);

     timeline.play();
   }

 private void updateScore(){
     int computerScore = 0;
     int userScore = 0;
      if (ballCenterX.get() > table.getWidth()){
          // Computer bounced the ball and the User didn't hit it back
          computerScore ++;
      } else if (ballCenterY.get() > 0 && ballCenterY.get() <= table.getHeight()){
          // The User served the ball and Computer didn't hit it back
          userScore++;
      } else{
          // The User served the ball off the table
          computerScore++;
      }


      System.out.println("Computer: " + computerScore + ", User: " + userScore);
    }
}

And this is my Main class

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.fxml.FXMLLoader;

public class PongMain extends Application {

@Override
public void start(Stage primaryStage) {
    try {
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(PongMain.class.getResource("GUI.fxml"));
        Group root = (Group) loader.load();
        Scene scene = new Scene(root,400,250);

        primaryStage.setScene(scene);
        primaryStage.show();
    } catch(Exception e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) {
    launch(args);
}
}

I just want to say thanks in advance, and that this is the first time ever using this website although I have used this website to get ideas in the past.

Bhavesh Odedra
  • 10,990
  • 12
  • 33
  • 58
Xenon
  • 19
  • 1
  • Welcome to Stack. Most people here are straight to the point without many pleasantries, so don't feel we're being harsh. "*make sure everything that is for the solution will work with these aspects in mind*" - "*Also by all means just take my code and repaste it with the corrections, so long as you can explain it alongside it. Just having one or the other is not going to be as effective as having both.*" You are asking quite a lot, but haven't described what you actually want (apart from a very brief partial sentence). What is it you need? Have you tried? What happens? What should happen? – James Mar 20 '15 at 02:09
  • 3
    This bit is actually your job: "I do have most of the code needed, but I am unsure what I am missing to get it to work." You need to find the part of your code that is giving you problems and then ask specifically about that issue. It's beyond the scope of this site to simply dump your code and expect that some unpaid stranger take time to learn the whole thing and then sift through it to find each and every problem and fix it for you. – MarsAtomic Mar 20 '15 at 02:09
  • What I am wondering is what do I need to implement into my code, whether it is into my Main or my Controller, so that instead of the window opening after running my PongMain class and there just being the elements I placed in Scenebuilder, I am needing to know how to incorporate my keycodes so that when I run the program, I can press my 'S' key to serve the ball, UP & DOWN to move my paddle, that is what I cannot figure out. I don't know what to type into one of the two classes to be able to get that to work. – Xenon Mar 20 '15 at 02:36

0 Answers0