前言
学Java的朋友们,福利来了,今天小编给大家带来了一款 植物大战僵尸源码,看图:
视频演示
环境JDK1.8
类继承UML图
源码实现
我们先从main函数看起,继承了javafx.application.Application。JavaFx是Java图形化界面技术AWT、Swing技术的新替代品。
通过main()执行Application的launch(String str)方法,当然launch(String str)方法不传入任何值也是可以执行的.launch(String str)方法会默认执行本类下的init()、start()、stop()方法。执行下面的main()方法后显示顺序为:
这是初始化方法➡这是start()方法➡这是stop()方法➡这是main()方法。
public class Main extends Application {
// 完整源码: gitee店康姆/hadluo/java_code.git
public static MediaPlayer mediaPlayer;
private static Database currentd;
@Override
public void start(Stage primaryStage) throws Exception{
// 程序启动执行
deserialize();
addMusic();
Parent mainPage=FXMLLoader.load(getClass().getResource("MainPage.fxml"));
Scene scene = new Scene(mainPage,1024,600);
primaryStage.setTitle("Plants VS Zombies");
primaryStage.setScene(scene);
primaryStage.show();
}
public void addMusic() {
Media sound = new Media(getClass().getResource("/assets/background.wav").toString());
mediaPlayer = new MediaPlayer(sound);
mediaPlayer.setAutoPlay(true);
mediaPlayer.setCycleCount(MediaPlayer.INDEFINITE);
mediaPlayer.setStartTime(Duration.seconds(0));
mediaPlayer.setStopTime(Duration.seconds(50));
mediaPlayer.play();
}
public static Database getDatabase(){
return currentd;
}
public static void serialize() throws IOException {
ObjectOutputStream out=null;
try {
out = new ObjectOutputStream (new FileOutputStream("database.txt"));
out.writeObject(currentd);
}
finally {
out.close();
//System.out.println("Saved!");
System.exit(0);
}
}
public static void deserialize() throws ClassNotFoundException, FileNotFoundException, IOException{
ObjectInputStream in = null;
try {
in=new ObjectInputStream (new FileInputStream("database.txt"));
currentd=(Database) in.readObject();
in.close();
}
catch (FileNotFoundException e){
currentd=new Database();
}
catch (NullPointerException e) {
currentd=new Database();
//System.out.println("This user does not exist in the database");
}
}
public static void main(String[] args) {
launch(args);
}
}
// 完整源码: gitee店康姆/hadluo/java_code.git
结尾语
我是分享好物+教程+源码的老罗,欢迎关注!