使控制台输出不“滚动”

问题描述 投票:0回答:1

我正在编写一个教程,通过重新打印整个内容的每个新帧来在控制台上模拟 ascii 动画,这确实有意义。

问题是控制台看起来像“滚动”,也就是说,新框架不是立即打印并替换以前的“框架”,它看起来更像是实际发生的事情,新框架(快速)正在构建并从下面滚动到。

现在,教程似乎对此非常满意,但我不满意。我尝试通过附加到字符串生成器缓冲区并一次性打印所有内容来替换单独的“print”和“println”调用,它可能有所帮助,但没有解决问题。

如何平滑逐帧感知?有可能吗?我想回答这个问题背后隐藏着很多非常有趣的专业知识,但我没有。

java console
1个回答
0
投票

您可以在每次打印动画帧之前清除屏幕。正如 Jorn 指出的,这可以在 Unix/Linux 终端中工作,并且可以在 Windows 命令窗口中工作,但可能无法在 IDE 中工作:

import java.io.IOException;

public class TerminalAnimation {
    public void animate()
    throws IOException,
           InterruptedException {

        ProcessBuilder clearScreenBuilder =
            new ProcessBuilder("tput", "clear");
        clearScreenBuilder.inheritIO();

        int x = 1;
        int increment = 1;
        while (true) {
            if (System.getProperty("os.name").contains("Windows")) {
                System.out.print("\u001b[H\u001b[2J\u001b[3J");
            } else {
                clearScreenBuilder.start().waitFor();
            }

            System.out.printf("%" + x + "s", "*");
            System.out.flush();

            Thread.sleep(125);

            x += increment;
            if (x <= 0 || x >= 40) {
                increment = -increment;
                x += increment * 2;
            }
        }
    }

    public static void main(String[] args)
    throws IOException,
           InterruptedException {

        new TerminalAnimation().animate();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.