创建包裹窗格的多个球

时间:2014-10-10 18:31:00

标签: java arraylist javafx

首先要说明我是计算机科学专业的学生,​​我的大学严格要求直接代码复制,所以如果你能够克制来解决 >“它应该看起来像这样”非常感谢。所以基本上我的任务是创建一个包含多个绿球和一个红球的JavaFX程序。所有的球必须缠绕在窗格上(以小行星的方式)并且如果红球碰巧与绿球碰撞,则移除绿球。我有很多问题,但我需要关注的关键是如何从我的ArrayList中获取所有球以及我的一个红球,以显示在窗格中并独立移动。它们都在窗格中(并且当前弹跳),但它们都绑定在一起。我给每个球随机的xy值,他们也应该都有随机的dx / dy值(它们的速度)。而且我相信这就是我的问题所在,每个球都没有自己的dx / dy,因此我创建了一个扩展Circle的类来尝试解决这个问题,但我的getter和setter似乎无法访问。我也知道问题的根源在于moveBall()方法,因为它是需要调整值的方法,但我无法弄清楚算法,因为我教授的办公时间结束了,所以我来到这里希望有人指出我正确的方向。以下是分类(我还想说明,这不完全是我的代码;它是来自Y.Daniel Liang的“Intro To Java Programming 10th ed。”的案例研究练习中的修改代码):

编辑:纠正了一个小错误。主要问题是让所有球通过moveBall()方法独立移动。

编辑2:作业完成。答案不再受限制。还添加了其他方法没有做我想要的addBallToPane()checkForCollision()如果有人可以告诉我如何修复这些将是伟大的。仍然希望自己解决这个问题,但在帮助下:)

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



 public class BallPane extends Pane {

        MovementGenerator mG = new MovementGenerator();
        public final double radius = 20;
        private double x = mG.position(), y = mG.position();
        private double dx = mG.velocity(), dy = mG.velocity();
        private Circle predator = new MovableCircle(x, y, radius, Color.RED);
        private Timeline animation;
        ArrayList<MovableCircle> circles = new ArrayList<>();

        public BallPane() {
            for (int i = 0; i < 10; i++) {
                circles.add(i, new MovableCircle(x, y, radius, Color.GREEN));
                circles.get(i).setDx(dx);
                circles.get(i).setDy(dy);
            }
            getChildren().addAll(circles);
            predator.setFill(Color.RED);
            getChildren().add(predator);

            // Create an animation for moving the ball
            animation = new Timeline(
                    new KeyFrame(Duration.millis(5), 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 void addBallToPane() {
         incrementalEnding++;                                 
         circles.add(new MovableCircle(radius, Color.GREEN));               
         getChildren().add(circles.get(incrementalEnding));

    }

    public void checkForCollison() {

        for (int i = 0; i < getChildren().size(); i++) {                  
            if ((predator.intersects(circles.get(i).getBoundsInLocal()))) {
                getChildren().remove(circles.get(i));
            }
        }

    protected void moveBall() {
        // Check boundaries
        if (x < radius || x > getWidth() - radius) {
            dx *= -1; // Change ball move direction
        }
        if (y < radius || y > getHeight() - radius) {
            dy *= -1; // Change ball move direction   
        }
        // Adjust ball position
        for (int i = 0; i < circles.size(); i++) {
            x += dx;
            y += dy;
            circles.get(i).setCenterX(x);
            circles.get(i).setCenterY(y);
        }
        predator.setCenterX(x);
        predator.setCenterY(y);

    }

}

旁注:我想在ArrayList中创建对象时设置dx / dy,但正如我所说,我的访问器和mutator不可访问。

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;

public class BounceBallControl extends Application {
  @Override // Override the start method in the Application class
  public void start(Stage primaryStage) {
    BallPane ballPane = new BallPane(); // Create a ball pane

    // Pause and resume animation
//    ballPane.setOnMousePressed(e -> ballPane.pause());
//    ballPane.setOnMouseReleased(e -> ballPane.play());

    // Increase and decrease animation   
    ballPane.setOnKeyPressed(e -> {
      if (e.getCode() == KeyCode.UP) {
        ballPane.increaseSpeed();
      } 
      else if (e.getCode() == KeyCode.DOWN) {
        ballPane.decreaseSpeed();
      }
    });



    // Create a scene and place it in the stage
    Scene scene = new Scene(ballPane, 500, 500);
    primaryStage.setTitle("BounceBallControl"); // Set the stage title
    primaryStage.setScene(scene); // Place the scene in the stage
    primaryStage.show(); // Display the stage

    // Must request focus after the primary stage is displayed
    ballPane.requestFocus();
  }

  /**
   * The main method is only needed for the IDE with limited
   * JavaFX support. Not needed for running from the command line.
   */
  public static void main(String[] args) {
    launch(args);
  }
}

import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;

public class MovableCircle extends Circle{

   MovementGenerator mG = new MovementGenerator();
   private double dx, dy;


   MovableCircle(double x, double y, double radius, Color color){
       super(x, y, radius);
       setFill(color);
   } 

    public double getDx() {
        return dx;
    }

    public void setDx(double newDx) {
        if (newDx < -10 || newDx > 10) {
            newDx = mG.velocity();
        } else {
          dx = newDx;  
        }   
    }

    public double getDy() {
        return dy;
    }

    public void setDy(double newDy) {
       if (newDy < -10 || newDy > 10) {
            newDy = mG.velocity();
        } else {
          dy = newDy;  
        }   
    }


}

除了生成随机值之外,下一个类没有做太多,可能不需要为它的函数创建一个全新的类,但是呃。它仅供参考,以防万一:

import java.util.Random;

public class MovementGenerator {

    private static int movement;
    private static int spawnPoint;
    Random rand = new Random();


    MovementGenerator(){
        movement = 0;
        spawnPoint = 0;
    }

    public static int getMovement() {
        return movement;
    }

    public static void setMovement(int movement) {
        MovementGenerator.movement = movement;
    }

    public static int getSpawnPoint() {
        return spawnPoint;
    }

    public static void setSpawnPoint(int spawnPoint) {
        MovementGenerator.spawnPoint = spawnPoint;
    }

    public int velocity(){
        movement = rand.nextInt(1);
        if (movement == 1) {
            movement = rand.nextInt(10);
        }
        else if (movement == 0) {
            movement = (rand.nextInt(10)*-1);
        }
        return movement;
    }

    public int position(){
        return spawnPoint = rand.nextInt(500);

    }
}

1 个答案:

答案 0 :(得分:1)

这是一个部分答案,让您有机会开始处理您的项目......

根据James_D的建议,您不仅需要在moveBall中使用MovableCircle方法,而且还需要摆脱xydxdy BallPane,并将控件转移到每个球。

这是我认为应该为初学者做的事情:

<强> MovableCircle

public class MovableCircle extends Circle {

   private final MovementGenerator mG = new MovementGenerator();
   private double x = mG.position(), y = mG.position();
   private double dx = mG.velocity(), dy = mG.velocity();
   private final double radius; 

   MovableCircle(double radius, Color color){
       this.setCenterX(x);
       this.setCenterY(y);
       this.radius=radius;
       this.setRadius(radius);
       this.setFill(color);
       setDx(dx);
       setDy(dy);
   } 

    public double getDx() { return dx; }

    public final void setDx(double newDx) {
        while (newDx < -10 || newDx > 10) {
            newDx = mG.velocity();
        } 
        dx = newDx;  
    }

    public double getDy() { return dy; }

    public final void setDy(double newDy) {
       while(newDy < -10 || newDy > 10) {
            newDy = mG.velocity();
        } 
        dy = newDy;  
    }

    public void moveBall() {
        // Check boundaries
        if (x < radius || x > BounceBallControl.WIDTH - radius) {
            dx *= -1; // Change ball move direction
        }
        if (y < radius || y > BounceBallControl.HEIGHT - radius) {
            dy *= -1; // Change ball move direction   
        }
        // Adjust ball position
        x += dx;
        y += dy;
        setCenterX(x);
        setCenterY(y);
    }

}

<强> BallPane

public class BallPane extends Pane {

    public final double radius = 20;
    private final MovableCircle predator = new MovableCircle(radius, Color.RED);
    private final Timeline animation;
    private final List<MovableCircle> circles;

    public BallPane() {
        circles=IntStream.range(0,10).mapToObj(i->new MovableCircle(radius, Color.GREEN))
                .collect(Collectors.toList());
        getChildren().addAll(circles);
        predator.setFill(Color.RED);
        getChildren().add(predator);

        setWidth(BounceBallControl.WIDTH);
        setHeight(BounceBallControl.HEIGHT);

        // Create an animation for moving the ball
        animation = new Timeline(new KeyFrame(Duration.millis(20), e -> moveBall()));
        animation.setCycleCount(Timeline.INDEFINITE);
        animation.play(); // Start animation
    }

    public final void moveBall() {
        circles.forEach(MovableCircle::moveBall);
        predator.moveBall();

    }
    ...
}

其中

public class BounceBallControl extends Application {

    public static final int WIDTH  = 500;
    public static final int HEIGHT = 500;
    ...
}

运行,你会发现这样的事情:

Snapshot of the game

现在是时候找出去除绿球的方法......