1

I started with JAVA yesterday and I´m about to build a simple snake game in the console to get started without any tutorials. I´m familiar with JS though.

The challenge I´m facing is the user input. I´m using the class Scanner, however this requires to press enter to get the previously pressed keys.

Is it possible to listen to the user input and return the pressed key as soon as a key is pressed(basically skipping the enter) with the Scanner' class? Alternatives?

Here´s my code(feel free to give me advices, as I said above, I started yesterday):

package Snake;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Snake player = new Snake();
        Field field = new Field();
        field.drawField(player.positionX, player.positionY);
        Scanner scanner = new Scanner(System.in);

        boolean x = false;

        do {
            switch(scanner.nextLine().charAt(0)) {
            case 'a': 
                field.drawField(player.positionX-=1, player.positionY);
                break;
            case 'b':
                System.out.println("You said b");
                break;
            case 'x':
            System.out.println("Closed by pressing x");
            x = true;
            break;
        }
    } while(!x);
}
}
Faizy
  • 299
  • 2
  • 11
  • 3
    If you're writing a game, you should use a JFrame and a KeyListener instead of Scanner (unless you use a game library of course). – Steve Smith May 31 '17 at 12:59
  • or you can throw your test cases in a file and append `< file.txt` to your program. – nafas May 31 '17 at 13:01
  • You need to escape the `Enter` key pressed after entering the key. Refer this question [Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo) – Sanket Makani May 31 '17 at 13:01
  • scanner is not for real time input –  May 31 '17 at 13:06

0 Answers0