在文本显示之间暂停



所以我正在创建一个基于文本的游戏,我很难找到一种在文本显示之间暂停的方法。我知道线程睡眠会起作用,但我不想对数百行文本执行此操作。这是我所拥有的,但是有没有更简单的方法可以做到这一点?

public class MyClass {
    public static void main(String[] args) {
        System.out.println("Hello?");
        //pause here
        System.out.println("Is this thing on?");
        /**Obviously I have a pause here, but I dont want to have to use this every time.*/
        try {
            Thread.sleep(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Now, what is your name?");
    }
}

为什么不简单地将其包装在另一个类中呢?

class DisplayWrapper {
    private final static long DEFAULT_PAUSE_MS = 250;
    public static void outputWithPause(String text, long ms) {
        System.out.println(text);
        try {
            Thread.sleep(ms);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void show(String text) {
        outputWithPause(text. DEFAULT_PAUSE_MS);
    }
}
public class MyClass {
public static void main(String[] args) {
    DisplayWrapper.show("Hello?");
    DisplayWrapper.show("Is this thing on?");
    DisplayWrapper.show("Now, what is your name?");
}

正如m.antkowicz在评论中提到的,您需要创建一个打印方法。我举了一个例子:

void printAndSleep(String string, int sleepTimeMs) {
  System.out.println(string);
  Thread.sleep(sleepTimeMs);
}

现在,无论何时要打印,只需使用我们上面制作的printAndSleep方法即可。这样:

printAndSleep("Hello?", 1000); // Print and pause for 1 second
printAndSleep("Is this thing on?", 2000); // Print and pause for 2 seconds

查看 TimerTask。

你可以像这样使用它:

public static void main(String[] args) {
    Timer timer = new Timer();
    writeIn(timer, 3000, "Hello?");
    writeIn(timer, 6000, "Is this thing on?");
    writeIn(timer, 12000, "Now, what is your name?");
    closeTimerIn(timer, 13000); // clean exit
}
private static void writeIn(Timer timer, final int millis, final String text){
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            System.out.println(text);
        }
    };
    timer.schedule(task, millis);
}
private static void closeTimerIn(final Timer timer, final int millis){
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            timer.cancel();
        }
    };
    timer.schedule(task, millis);
}

最新更新