做一个简单的弹球GAME,竟然比我想象代码量要少的多,基本上基于animation,球球是一闪一闪自动改变颜色的,接下来可能会做个登陆界面啥的,看心情。
上下方向键改变速度
注意:两个程序要放在同一个package里面//新手友好
下面是弹球主要代码,不包括主函数
package project;
import javafx.animation.FadeTransition;
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.scene.shape.Rectangle;
import javafx.util.Duration;
public class Ballpane extends Pane {
public final double radius = 15;
private double x = (Math.random() * 200 + 15), y = radius;
double dx = 1, dy = 1;
private Circle circle = new Circle(x, y, radius);
private Rectangle rt = new Rectangle(100, 180, 50, 20);
private Timeline animation;
private Timeline animation1;
public Ballpane() {
circle.setFill(Color.RED);
rt.setFill(Color.BLACK);
getChildren().add(rt);
getChildren().add(circle);
animation = new Timeline(new KeyFrame(Duration.millis(50), e -> moveball()));
animation.setRate(5);
animation.setCycleCount(Timeline.INDEFINITE);
animation.play();
animation1 = new Timeline(new KeyFrame(Duration.millis(500), e -> circlecolor()));
animation1.setCycleCount(Timeline.INDEFINITE);
animation1.play();
}
public void circlecolor() {
circle.setFill(new Color(Math.random(), Math.random(), Math.random(), Math.random()));
}
public void play() {
animation.play();
}
public void right() {
rt.setX(rt.getX() + 5);
}
public void left() {
rt.setX(rt.getX() - 5);
}
public void increasespeed() {
animation.setRate(animation.getRate() + 0.1);
}
public void decreasespeed() {
animation.setRate(animation.getRate() > 0 ? animation.getRate() - 0.1 : 0.1);
}
public void moveball() {
if (x < 15 || x > 235) {
dx *= -1;
}
if (y > 235 && (x < rt.getX() || x > rt.getX() + 50))
System.exit(0);
if (y < 15 || (y > 165 && x > rt.getX() && x < rt.getX() + 50))
dy *= -1;
x += dx;
y += dy;
circle.setCenterX(x);
circle.setCenterY(y);
}
}
下面是主函数的控制界面
package project;
import javafx.application.*;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.input.KeyCode;
public class Ballcontrol extends Application{
public void start(Stage pr) {
Ballpane ballpane=new Ballpane();
ballpane.setOnKeyPressed(e->{
if(e.getCode()==KeyCode.UP)
ballpane.increasespeed();
else if(e.getCode()==KeyCode.DOWN)
ballpane.decreasespeed();
else if(e.getCode()==KeyCode.RIGHT)
ballpane.right();
else if(e.getCode()==KeyCode.LEFT)
ballpane.left();
});
Scene scene=new Scene(ballpane,250,200);
pr.setTitle("弹球");
pr.setScene(scene);
pr.show();
ballpane.requestFocus();
}
public static void main(String [] args) {
Application.launch(args);
}
}