1. 程式人生 > >java彈球GAME

java彈球GAME

做一個簡單的彈球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);
	}

}