簡體   English   中英

是否可以使方法運行一段時間?(初學者)

[英]Is it possible to make a method run for a period of time?(beginner)

我有一個單球迷宮java項目(Internet和Github上的CBallMaze),並且我想通過調用每個4個方向的方法來使球自動移動到最終目標。 我想知道是否可以為每種方法設置時間間隔,這將導致方法在其設置的時間間隔內持續使用-或是否有其他方法可以解決此問題。

下面是“運行”按鈕的當前代碼

        if (source == buttonRun) {
        timer = new Timer(1000, this);
        timer.start();
        System.out.println("The program's timer has started");
        if (Maze == Maze1) {

            for (int i=0;i<2;i++) {
            moveLeft();
            moveLeft();
            moveLeft();
            //2nd section//
            moveDown();
            moveDown();
            moveDown();
            //3rd section//
            moveLeft();
            moveLeft();
            //4th section
            moveDown();
            moveDown();
            moveDown();
            //5th section//
            moveRight();
            moveRight();
            //6th section//
            moveDown();
            moveDown();
            moveDown();
            //7th section//
            moveRight();
            moveRight();
            moveRight();
            //8th section//
            moveDown();
            moveDown();
            moveDown();
            //9th section//
            moveLeft();
            moveLeft();
            moveLeft();
            moveLeft();
            moveLeft();
            moveLeft();
            moveLeft();
        }
    }
    }

該代碼確實將球移動了,但是並沒有將其移動到目的地,並且似乎無法使球以適當的速度自行移動到每個圖塊,以供用戶查看。 任何幫助/指導將不勝感激。

每次進入該方法時,都會讀取當前時間並將其保存為長變量startTime 然后在while循環中執行:

while (currentTime() - startTime < x) {
    // perform task
}

x是您希望函數繼續運行的任意持續時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM