0

So I'm making a text adventure game and I'm using this code as a print method:

public static void p(String x)
  {
    for(int i = 0; i < x.length(); i++)
    {
      try
      {
        Thread.sleep(30);
        System.out.print(x.charAt(i));
      }
      catch(InterruptedException ex)
      {
        Thread.currentThread().interrupt();
      }
    }
    System.out.println("");
    try
      {
        Thread.sleep(900);
      }
      catch(InterruptedException ex)
      {
        Thread.currentThread().interrupt();
      }
  }

It basically just waits a certain amount of time before printing the next letter in a string. However, I've noticed that when players replay the game, it can sometimes get tedious to wait through the wall of text they've already read. What I need help with is making my code so that pressing enter in the middle of the method printing instantly prints the rest of the string, rather than doing one letter at a time.

GBlodgett
  • 12,704
  • 4
  • 31
  • 45
  • ... I mean it sounds tedious just from the first go round. ;) Why don't you interrupt on the keypress and in your catch block just print the remainder of the string? – Roddy of the Frozen Peas Jan 10 '19 at 00:04
  • Java's console based input is basic at best. To do something like you want, you'd need to use a implementation of something like Curses – MadProgrammer Jan 10 '19 at 00:04
  • @RoddyoftheFrozenPeas Good idea, it sounds like what I'd need to do is to detect a keypress to interrupt, and then in the catch print x.charAt(i), x.charAt(i + 1), x.charAt(i+2), etc all the way up to x.charAt(i+(x.length-i)). How do I interrupt on the keypress though? – Nikhil Bansal Jan 10 '19 at 12:53
  • @MadProgrammer that sounds like a good idea, but I'm confused on how I would add Curses. I'm using atom text editor with the runner and java addon – Nikhil Bansal Jan 10 '19 at 12:55
  • The `substring` method would be the appropriate way to print the remainder of the string: `x.substring(i)`. And have the keypress throw an interrupt exception. – Roddy of the Frozen Peas Jan 10 '19 at 15:19
  • @NikhilBansal Curses as a library available on most *nix systems, I think there’s a version for windows. You’ll need to look around for java bindings – MadProgrammer Jan 10 '19 at 18:01
  • @RoddyoftheFrozenPeas Sorry I'm a beginner, how do I make the enter keypress throw an exception. I'm also assuming that I put substring in the catch? – Nikhil Bansal Jan 10 '19 at 19:05
  • Relevant to the Curses discussion: https://stackoverflow.com/questions/439799/whats-a-good-java-curses-like-library-for-terminal-applications – Roddy of the Frozen Peas Jan 10 '19 at 19:28

0 Answers0