I was working on a tutorial that simulates ascii animation on console by printing every new frame of the entire thing all over again, which does make sense.
The issue is that the console looks like it's 'scrolling', that is to say, rather than the new frame being printed instantly and replacing the previous 'frame', it looks more like what's actually happening, with the new frame (rapidly) being built and scrolled to from bellow.
Now, the tutorial seems perfectly content with that, but I am not. I attempted to replace the individual 'print' and 'println' calls with appending to a stringbuilder buffer and printing it all in one go, and it may have helped, but it didn't solve it.
How can I smoothen the frame-by-frame perception? Is it even possible? I imagine a lot of very interesting expertise hides behind answering that question, but I do not have it.
You can clear the screen before each printing of an animation frame. As Jorn pointed out, this will work in a Unix/Linux terminal and will work in a Windows command window, but probably won’t work in an 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();
}
}