主頁 > 後端開發 > 桌面寵物開發——羅小黑(一)

桌面寵物開發——羅小黑(一)

2021-09-24 10:06:31 後端開發

文章目錄

  • 寫在前面
  • 第一版雛形
  • 專案目錄
  • 主入口程式
  • 全域常量
  • 動作
    • 動作基本類
    • 動作生成者
    • 動作執行者
  • 事件
  • 資源加載器
  • 互動平臺


寫在前面

我的QQ寵物已經讀大學啦,每天吃得飽飽的,每次回到家,我學習的時候也會讓她也學習,我想著以后大學我一定有更多的時間陪她,可誰知2018年9月15日她卻回到了自己的故鄉,
在這里插入圖片描述
時間過得也快,轉眼就大三了,這些年也學了不少知識,愛上了動漫《羅小黑戰記》,誰知又要停更三年呢?羅小黑說:“我想和小白一起學讀書!”,好呀~那就來讀書吧!

想過多種語言來撰寫,比如C#、Python、C++,但還是選擇了自己最熟悉的Java,謝謝燕然都護的博客給的思路,打算做一個更完整的桌面寵物,模仿原來QQ寵物的饑餓度、健康值、心情值、金幣系統、學習成長系統,結合番劇、電影的故事背景添加法力值等等等等,最終做成一款可安裝式的C/S架構的游戲,讓喜歡羅小黑戰記的人在三年的等待時間內都可以來陪伴他~

第一版雛形

請添加圖片描述

專案目錄

使用的IDE是JetBrains Intellij IDEA,新建一個普通的Java專案,這個為專案目錄
在這里插入圖片描述

主入口程式

整個程式從主入口程式進入,下面是HelloHeiApplication類原始碼:

package org.taibai.hellohei;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.taibai.hellohei.constant.Constant;
import org.taibai.hellohei.event.GlobalEventListener;
import org.taibai.hellohei.img.ResourceGetter;
import org.taibai.hellohei.ui.InterfaceFunction;

import java.io.IOException;


public class HelloHeiApplication extends Application {

    /**
     * 展示圖片的視窗
     */
    private ImageView imageView;
    private AnchorPane pane;
    private InterfaceFunction interfaceFunction;
    /**
     * 全域事件監聽,目前支持拖拽、左鍵點擊反饋
     */
    private GlobalEventListener globalEventListener;

    private final ResourceGetter resourceGetter = ResourceGetter.newInstance();

    @Override
    public void start(Stage primaryStage) throws IOException {
        primaryStage.initStyle(StageStyle.UTILITY);
        primaryStage.setOpacity(0);     // 設定父級透明度為0
        Stage stage = new Stage();
        stage.initOwner(primaryStage);  // 將 primaryStage 設定為歸屬物件,即父級視窗
        initImageView();
        // 互動功能平臺
        interfaceFunction = new InterfaceFunction(stage, imageView);
        // 面板
        pane = new AnchorPane(interfaceFunction.getMessageBox(), interfaceFunction.getImageView());
        pane.setStyle("-fx-background:transparent;");
        // 開啟全域事件
        globalEventListener = new GlobalEventListener(stage, imageView, pane);
        initStage(stage);
        primaryStage.show();
        stage.show();
        interfaceFunction.setTray(stage);   //添加系統托盤
    }

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

    private void initImageView() {
        Image image = resourceGetter.get(Constant.ImageShow.mainImage);
        this.imageView = new ImageView(image);
        imageView.setX(0);
        imageView.setY(0);
        imageView.setLayoutX(0);
        imageView.setLayoutY(50);
        imageView.setFitHeight(Constant.ImageShow.ImageHeight); // 設定圖片顯示的大小
        imageView.setFitHeight(Constant.ImageShow.ImageWidth);
        imageView.setPreserveRatio(true);                       // 保留width:height比例
        imageView.setStyle("-fx-background:transparent;");      // 透明背景
    }

    private void initStage(Stage stage) {
        Scene scene = new Scene(pane, 400, 400);
        scene.setFill(null);
        scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
        stage.setScene(scene);
        // 設定表單的初始位置
        stage.setX(850);
        stage.setY(400);
        stage.setAlwaysOnTop(true);// 視窗總顯示在最前
        // 修改任務欄圖示
        stage.getIcons().add(resourceGetter.get(Constant.ImageShow.iconImage));
        stage.initStyle(StageStyle.TRANSPARENT);// 背景透明
        stage.setOnCloseRequest(event -> {
            event.consume();
            interfaceFunction.exit();
        });
    }

}

依次說明一下:

  1. primaryStage并非正在的stage,在start方法中又新建了一個Stage實體,并且讓primaryStage隱藏,這樣做的目的是就不會在任務欄里面顯示行程了,否則強迫癥患者會很難受的,
  2. ImageView將作為整個程式展示的視窗,一系列動作也只是替換gif圖片罷了
  3. 互動平臺InterfaceFunction提供了用戶的一系列互動動作,例如顯示隱藏、退出、切換狀態,以后的各種功能也將在互動平臺擴展
  4. 全域事件監聽者GlobalEventListener:考慮到各事件之間可能會相互干擾,于是開了一個類去集中管理,意在解決重復觸發點擊事件、拖動時不觸發點擊事件等問題,這樣也讓start方法更輕便一些,
  5. 最后將互動平臺加入系統托盤,于是你可以在任務欄里像找到QQ程式一樣找到小黑后臺

全域常量

雖然全域常量不太好,目前功能單一,全域常量有助于除錯,希望在后面能選擇更好的解決方案

package org.taibai.hellohei.constant;

/**
 * <p>Creation Time: 2021-09-21 18:00:49</p>
 * <p>Description: 各種常量,集中管理</p>
 *
 * @author 太白
 */
public class Constant {

    public static class ImageShow {
        /**
         * 主體的長與寬
         */
        public static final int ImageHeight = 100;
        public static final int ImageWidth = 100;

        public static final String mainImage = "/org/taibai/hellohei/img/licking the claw.gif";
        public static final String byeImage = "/org/taibai/hellohei/img/bye.gif";
        public static final String iconImage = "/org/taibai/hellohei/img/icon.png";
        public static final String guitarImage = "/org/taibai/hellohei/img/playing guitar.gif";
    }

    public static class UserInterface {
        /**
         * 互動時間,例如點擊羅小黑會回應一個動作,該動作持續RunTime
         */
        public static final int RunTime = 3;

        /**
         * 碎碎念
         */
        public static final String[] selfTalking = {
                "嘿咻~",
                "點我~",
                "小白,這個字怎么念呀",
                "想吃甘蔗了……",
                "在干嘛呢~"
        };
    }

}

動作

動作基本類

一個動作應該有如下屬性

  • path: 該動作是什么
  • time: 執行多少時間
  • isTemporaryAction: 是否是暫時的,比如點擊后觸發的動作是展示顯示的,而恢復到默認狀態是持續的
  • recoverPath: 如果是暫時的那么應該恢復到什么動作
  • interruptable: 是否可中斷的,例如退出影片是不可中斷的,而在做普通影片是可中斷的,這樣退出影片就得以顯示
package org.taibai.hellohei.ui;

/**
 * <p>Creation Time: 2021-09-22 11:49:27</p>
 * <p>Description: 動作</p>
 *
 * @author 太白
 */
public class Action {

    /**
     * 當前動作
     */
    private final String path;

    /**
     * 動作維持時間,如果為-1則保持該動作
     */
    private final double time;

    /**
     * 是否是暫時的動作
     */
    private final boolean isTemporaryAction;

    /**
     * 如果是暫時的動作,則應當在該時間內恢復到這個動作
     */
    private String recoverPath;

    /**
     * 是否可中斷
     */
    private final boolean interruptable;

    /**
     * 若動作是持續的,則維持時間為 PerpetualTime
     */
    public static final double PerpetualTime = -1.0;

    private Action(String path, double time, boolean isTemporaryAction, String recoverPath, boolean interruptable) {
        this.path = path;
        this.time = time;
        this.isTemporaryAction = isTemporaryAction;
        this.recoverPath = recoverPath;
        this.interruptable = interruptable;
    }

    private Action(String path, double time, boolean isTemporaryAction, boolean interruptable) {
        this.path = path;
        this.time = time;
        this.isTemporaryAction = isTemporaryAction;
        this.interruptable = interruptable;
    }

    /**
     * 創建暫時的、可中斷的動作
     *
     * @param path        動作路徑
     * @param time        持續時間
     * @param recoverPath 恢復動作路徑
     * @return 創建的動作實體
     */
    public static Action creatTemporaryInterruptableAction(String path, double time, String recoverPath) {
        return new Action(path, time, true, recoverPath, true);
    }

    /**
     * 創建持續的、可中斷的動作
     *
     * @param path 動作路徑
     * @return 創建的動作實體
     */
    public static Action creatContinuousInterruptableAction(String path) {
        return new Action(path, PerpetualTime, false, true);
    }

    /**
     * 創建短暫的、不可中斷的動作,例如退出影片
     *
     * @param path        動作路徑
     * @param time        持續時間
     * @param recoverPath 恢復動作路徑
     * @return 創建的動作實體
     */
    public static Action creatTemporaryUninterruptibleAction(String path, double time, String recoverPath) {
        return new Action(path, time, true, recoverPath, false);
    }

    /**
     * 創建持續的、不可中斷的動作,比較苛刻展示想不到案例
     *
     * @param path 動作路徑
     * @return 創建的動作實體
     */
    public static Action creatContinuousUninterruptibleAction(String path) {
        return new Action(path, PerpetualTime, false, false);
    }

    public String getPath() {
        return path;
    }

    public double getTime() {
        return time;
    }

    public boolean isTemporaryAction() {
        return isTemporaryAction;
    }

    public String getRecoverPath() {
        return recoverPath;
    }

    public boolean isInterruptable() {
        return interruptable;
    }
}

并且采納《Effective Java》“隱藏”了建構式,并且提供公開的介面來構造四種型別的動作,分別是

  • creatTemporaryInterruptableAction:暫時的、可中斷的動作
  • creatContinuousInterruptableAction:持續的、可中斷的動作
  • creatTemporaryUninterruptibleAction:暫時的、不可中斷的動作
  • creatContinuousUninterruptibleAction:持續的、不可中斷的動作

動作生成者

一個動作的產生是隨機的,如果放在動作類或者動作執行類不太妥當,因此將其獨立管理,構建了一個名為ActionGenerator的動作生成者類

package org.taibai.hellohei.ui;

import org.taibai.hellohei.constant.Constant;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>Creation Time: 2021-09-21 18:15:02</p>
 * <p>Description: 獲取一個新的互動動作以及互動動作的關閉</p>
 *
 * @author 太白
 */
public class ActionGenerator {

    /**
     * 動作編號
     */
    private int actionIndex = NoAction;

    private static final Map<Integer, String> resource = new HashMap<Integer, String>() {{
        put(1, Constant.ImageShow.guitarImage);
    }};
    private static final int MinIndex = 1;
    private static final int MaxIndex = 1;
    public static final int NoAction = 0;

    /**
     * 隨機生成一個動作編號,這里當動作編號不為0時說明動作還未結束
     *
     * @return 當且僅當上一個動作未結束時,回傳false,且不生成新動作
     */
    public boolean generateNewActionIndex() {
        if (actionIndex != NoAction) return false;
        actionIndex = (int) (Math.random() * (MaxIndex - MinIndex + 1) + MinIndex);
        return true;
    }

    /**
     * 結束動作時必須呼叫該API,約定的
     *
     * @return 是否關閉,若早已關閉也回傳false
     */
    public void close() {
        actionIndex = NoAction;
    }

    /**
     * 獲得動作的GIF資源
     *
     * @return 動作GIF資源檔案相對路徑
     */
    public String getActionPath() {
        if (resource.containsKey(actionIndex))
            return resource.get(actionIndex);
        return null;
    }
}

這里約定一個動作的開啟必須要關閉,不關閉將不會再生成動作,

動作執行者

動作的執行是互相影響的,例如連續點擊不應該連續觸發動作等,因此將其獨立出來,構建了一個動作執行者類ActionExecutor

package org.taibai.hellohei.ui;

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.util.Duration;
import org.taibai.hellohei.constant.Constant;
import org.taibai.hellohei.img.ResourceGetter;

/**
 * <p>Creation Time: 2021-09-22 11:49:12</p>
 * <p>Description: 動作執行者</p>
 *
 * @author 太白
 */
public class ActionExecutor {

    private ImageView imageView;
    private Action curAction;
    private final ResourceGetter resourceGetter = ResourceGetter.newInstance();
    private final ActionGenerator actionGenerator = new ActionGenerator();
    private static ActionExecutor actionExecutor;
    private Timeline timeline;

    public static ActionExecutor newInstance(ImageView imageView) {
        if (actionExecutor == null) actionExecutor = new ActionExecutor(imageView);
        return actionExecutor;
    }

    private ActionExecutor(ImageView imageView) {
        this.imageView = imageView;
    }

    public boolean execute(Action action) {
        // 如果上一個動作不可中斷,那么動作執行失敗
        if (curAction != null && !curAction.isInterruptable()) return false;
        Image actionImage = resourceGetter.get(action.getPath());
        imageView.setImage(actionImage);
        curAction = action;
        if (timeline != null) timeline.pause();
        // 如果當前動作是暫時的,則還需要恢復到某一個動作
        if (action.isTemporaryAction()) {
            timeline = new Timeline(new KeyFrame(Duration.seconds(action.getTime()), e -> executeContinuousInterruptableActionAction(action.getRecoverPath())));
            timeline.play();
        }
        return true;
    }

    public boolean executeClickAction() {
        boolean ok = actionGenerator.generateNewActionIndex();
        if (ok) {
            execute(Action.creatTemporaryInterruptableAction(
                    actionGenerator.getActionPath(),
                    Constant.UserInterface.RunTime,
                    Constant.ImageShow.mainImage));
        }
        return ok;
    }

    /**
     * 立即執行一個可中斷的、持續的動作
     */
    private void executeContinuousInterruptableActionAction(String path) {
        curAction = null;
        timeline = null;
        actionGenerator.close();
        Action action = Action.creatContinuousInterruptableAction(path);
        execute(action);
    }

}

動作的執行是影響全域的,因此將其設計為單例模式,這樣全域拿到的就是同一個物件,所產生的影響也是全域同步的,

事件

事件起初遇到了點麻煩,就是拖動也會觸發點擊事件,如果在主入口程式設定會很繁瑣,因此我將事件管理劃到了一個類中,這樣拖動時記錄初始坐標,松開滑鼠時只需要判斷坐標值是不是一樣的,如果是一樣的就說明在原地,執行點擊事件(就是逗小黑玩),雖然有可能拖動到同一個地方,但用戶既然要拖拽肯定是想移動一個位置,所以不大可能回到原來的位置(就算故意移回到原位也很困難是吧~)

package org.taibai.hellohei.event;

import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import org.taibai.hellohei.constant.Constant;
import org.taibai.hellohei.img.ResourceGetter;
import org.taibai.hellohei.ui.Action;
import org.taibai.hellohei.ui.ActionExecutor;
import org.taibai.hellohei.ui.ActionGenerator;

/**
 * <p>Creation Time: 2021-09-22 12:50:52</p>
 * <p>Description: 全域事件監聽者</p>
 *
 * @author 太白
 */
public class GlobalEventListener {

    private final Stage stage;
    private final ImageView imageView;
    private final AnchorPane anchorPane;
    /**
     * 動作執行者,觸發的動作需要托付給動作執行者執行
     */
    private final ActionExecutor actionExecutor;

    private double xOffset = 0;
    private double yOffset = 0;
    private double preScreenX = 0;
    private double preScreenY = 0;

    public GlobalEventListener(Stage stage, ImageView imageView, AnchorPane anchorPane) {
        this.stage = stage;
        this.imageView = imageView;
        this.anchorPane = anchorPane;
        this.actionExecutor = ActionExecutor.newInstance(imageView);
        enableDrag();
        enableClick();
    }

    /**
     * 激活拖動
     */
    private void enableDrag() {
        anchorPane.setOnMousePressed(e -> {
            xOffset = e.getSceneX();
            yOffset = e.getSceneY();
        });
        anchorPane.setOnMouseDragged(e -> {
            stage.setX(e.getScreenX() - xOffset);
            stage.setY(e.getScreenY() - yOffset);
        });
    }

    /**
     * 點擊隨機觸發一個動作
     */
    private void enableClick() {
        imageView.setOnMousePressed(e -> {
            preScreenX = e.getScreenX();
            preScreenY = e.getScreenY();
        });
        imageView.setOnMouseReleased(e -> {
            if (e.getScreenX() == preScreenX && e.getScreenY() == preScreenY) {
                actionExecutor.executeClickAction();
            }
        });
    }

}

資源加載器

整個程式的運作都需要GIF圖片的顯示,因此需要用一個類去加載GIF圖片,這里使用類級別與屬性級別的單例模式,降低了創建類所需要的時間,當然如果使用HashMap容易導致記憶體泄漏,因此使用WeekHashMap

擴展閱讀 WeekHashMap
和HashMap一樣,WeakHashMap 也是一個散串列,它存盤的內容也是鍵值對(key-value)映射,而且鍵和值都可以是null,不過WeakHashMap的鍵是“弱鍵”,在 WeakHashMap 中,當某個鍵不再正常使用時,會被從WeakHashMap中被自動移除,更精確地說,對于一個給定的鍵,其映射的存在并不阻止垃圾回收器對該鍵的丟棄,這就使該鍵成為可終止的,被終止,然后被回收,某個鍵被終止時,它對應的鍵值對也就從映射中有效地移除了,

package org.taibai.hellohei.img;

import javafx.scene.image.Image;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.WeakHashMap;

/**
 * <p>Creation Time: 2021-09-21 18:35:46</p>
 * <p>Description: 資源加載器</p>
 *
 * @author 太白
 */
public class ResourceGetter {

    private static final Map<String, Image> images = new WeakHashMap<>();
    private static ResourceGetter singleton;

    public static ResourceGetter newInstance() {
        if (singleton == null) singleton = new ResourceGetter();
        return singleton;
    }

    private ResourceGetter() {
    }

    public Image get(String path) {
        if (!images.containsKey(path)) {
            images.put(path, new Image(Objects.requireNonNull(this.getClass().getResourceAsStream(path))));
        }
        return images.get(path);
    }

}

互動平臺

目前的互動功能僅僅只有碎碎念、顯示隱藏,希望后面能擴充點功能,互動平臺開啟一個執行緒,隨機事件后觸發一次互動功能,比如開啟碎碎念功能后,將在隨機事件后彈出訊息框,

package org.taibai.hellohei.ui;

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Polygon;
import javafx.stage.Stage;
import javafx.util.Duration;
import org.taibai.hellohei.constant.Constant;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Objects;
import java.util.Random;

/**
 * <p>Creation Time: 2021-09-21 19:00:47</p>
 * <p>Description: 互動功能</p>
 *
 * @author 太白
 */
public class InterfaceFunction {

    private final ImageView imageView;
    private final ActionExecutor actionExecutor;
    private final Stage stage;
    private VBox messageBox;
    private CheckboxMenuItem itemSay = new CheckboxMenuItem("碎碎念");
    private final String greet = "好久不見鴨,想你了~";

    public InterfaceFunction(Stage stage, ImageView imageView) {
        this.stage = stage;
        this.imageView = imageView;
        this.actionExecutor = ActionExecutor.newInstance(imageView);
        this.messageBox = new VBox();
        initMessage();
        say(greet, 8);
        // 開啟隨機事件
        RandomEvent randomEvent = new RandomEvent();
        new Thread(randomEvent).start();
    }

    /**
     * 初始化訊息框
     */
    private void initMessage() {
        Label bubble = new Label();
        //設定氣泡的寬度,如果沒有這句,就會根據內容多少來自適應寬度
        bubble.setPrefWidth(100);
        bubble.setWrapText(true);   //自動換行
        bubble.setStyle("-fx-background-color: rgba(255,255,255,0.7); -fx-background-radius: 8px;");
        bubble.setPadding(new Insets(7)); //標簽的內邊距的寬度
        bubble.setFont(new javafx.scene.text.Font(14));
        bubble.setTextFill(Color.web("#000000"));

        Polygon triangle = new Polygon(0.0, 0.0, 8.0, 10.0, 16.0, 0.0);//分別設定三角形三個頂點的X和Y
        triangle.setFill(new Color(1, 1, 1, 0.7));

        // VBox.setMargin(triangle, new Insets(0, 50, 0, 0));//設定三角形的位置,默認居中
        messageBox.getChildren().addAll(bubble, triangle);
        messageBox.setAlignment(Pos.BOTTOM_CENTER);
        messageBox.setStyle("-fx-background:transparent;");
        //設定相對于父容器的位置
        messageBox.setLayoutX(0);
        messageBox.setLayoutY(0);
        messageBox.setVisible(true);
    }

    /**
     * 退出
     */
    public void exit() {
        // 展示告別影片
        double time = 1.5;
        actionExecutor.execute(Action.creatTemporaryUninterruptibleAction(Constant.ImageShow.byeImage, time, Constant.ImageShow.mainImage));
        // 要用Platform.runLater,不然會報錯Not on FX application thread;
        Platform.runLater(() -> say("再見~", Constant.UserInterface.SayingRunTime));
        // 影片結束后執行退出
        new Timeline(new KeyFrame(
                Duration.seconds(time),
                ae -> System.exit(0)))
                .play();
    }

    /**
     * 說一句話
     *
     * @param msg      訊息
     * @param duration 持續時間
     */
    public void say(String msg, int duration) {
        Label lbl = (Label) messageBox.getChildren().get(0);
        lbl.setText(msg);
        messageBox.setVisible(true);
        //設定氣泡的顯示時間
        new Timeline(new KeyFrame(
                Duration.seconds(duration),
                ae -> {
                    messageBox.setVisible(false);
                }))
                .play();
    }

    /**
     * 添加系統托盤
     *
     * @param stage 舞臺
     */
    public void setTray(Stage stage) {
        SystemTray tray = SystemTray.getSystemTray();
        //托盤圖示
        BufferedImage image;
        try {
            // 為托盤添加一個右鍵彈出選單
            PopupMenu popMenu = new PopupMenu();
            popMenu.setFont(new Font("微軟雅黑", Font.PLAIN, 14));

            MenuItem itemShow = new MenuItem("顯示");
            itemShow.addActionListener(e -> Platform.runLater(() -> stage.show()));

            MenuItem itemHide = new MenuItem("隱藏");
            // 要先setImplicitExit(false),否則stage.hide()會直接關閉stage
            // stage.hide()等同于stage.close()
            itemHide.addActionListener(e -> {
                Platform.setImplicitExit(false);
                Platform.runLater(stage::hide);
            });

            MenuItem itemExit = new MenuItem("退出");
            itemExit.addActionListener(e -> exit());

            popMenu.add(itemSay);
            popMenu.addSeparator();
            popMenu.add(itemShow);
            popMenu.add(itemHide);
            popMenu.add(itemExit);
            //設定托盤圖示
            image = ImageIO.read(Objects.requireNonNull(getClass().getResourceAsStream(Constant.ImageShow.iconImage)));
            TrayIcon trayIcon = new TrayIcon(image, "小黑", popMenu);
            trayIcon.setToolTip("小黑");
            trayIcon.setImageAutoSize(true);//自動調整圖片大小,這步很重要,不然顯示的是空白
            tray.add(trayIcon);
        } catch (IOException | AWTException e) {
            e.printStackTrace();
        }
    }

    public ImageView getImageView() {
        return imageView;
    }

    public VBox getMessageBox() {
        return messageBox;
    }

    class RandomEvent implements Runnable {
        @Override
        public void run() {
            while (true) {
                Random rand = new Random();
                //隨機發生自動事件,以下設定間隔為9~24秒,要注意這個時間間隔包含了影片播放的時間
                long time = (rand.nextInt(15) + 10) * 1000;
                if (itemSay.getState()) {
                    //隨機選擇要說的話,因為目前只有兩個寵物,所以可以用三目運算子
                    String str = Constant.UserInterface.selfTalking[rand.nextInt(5)];
                    Platform.runLater(() -> say(str, Constant.UserInterface.SayingRunTime));
                }
                try {
                    Thread.sleep(time);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

之后功能還會繼續擴充,苦命考研狗,先去學習了~

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/302506.html

標籤:java

上一篇:985高校的高材生只會寫代碼片段,丟人嗎?

下一篇:Spring Data Redis怎么讀不到我剛才設進去的值?

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more