3

I made a simple game(well not really a game yet) in which the player can move in a room 4x20 characters in size. It runs in console.

But in my game loop I want to be able to move around in the room without pressing enter every time I want to move. The player should be able to press w/a/s/d and have the screen update instantly, but I don't know how to do that.

public class Main{
public static void main(String[] args){
    MovementLoop();
}
public static void MovementLoop(){

    Scanner input = new Scanner(System.in);

    int pos=10, linepos=2;
    String keypressed;
    boolean playing = true;

    while(playing == true){
        display dObj = new display(linepos, pos);
        dObj.drawImage();
        keypressed=input.nextLine();
        if(keypressed.equals("w")){
            linepos -= 1;
        }
        else if(keypressed.equals("s")){
            linepos += 1;
        }
        else if(keypressed.equals("a")){
            pos -= 1;
        }
        else if(keypressed.equals("d")){
            pos += 1;
        }
        else if(keypressed.equals("q")){
            System.out.println("You have quit the game.");
            playing = false;
        }
        else{
            System.out.println("\nplease use w a s d\n");
        }
    }
}
}

public class display{

private String lines[][] = new String[4][20];
private String hWalls = "+--------------------+";
private String vWalls = "|";
private int linepos, pos;


public display(int linepos1, int pos1){
    pos = pos1 - 1;
    linepos = linepos1 - 1;
}
public void drawImage(){

    for(int x1=0;x1<lines.length;x1++){
        for(int x2=0;x2<lines[x1].length;x2++){
            lines[x1][x2]="#";
        }
    }
    lines[linepos][pos]="O";

    System.out.println(hWalls);
    for(int x2=0;x2<lines.length;x2++){
        System.out.print(vWalls);
        for(int x3=0;x3<lines[x2].length;x3++){
        System.out.print(lines[x2][x3]);
        }
        System.out.println(vWalls);
    }
    System.out.println(hWalls);
}
}
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Jaanus Sepp
  • 31
  • 1
  • 2
  • 3
    Boolean zen! Don't ever use `while(foo == true)`, just use `while(foo)`. It's good style to avoid `== true` and `== false`. – fvrghl Jul 09 '13 at 18:59
  • possible duplicate of [How to read a single char from the console in Java (as the user types it)?](http://stackoverflow.com/questions/1066318/how-to-read-a-single-char-from-the-console-in-java-as-the-user-types-it) – Xavi López Jul 09 '13 at 19:11
  • check this - http://stackoverflow.com/questions/1864076/equivalent-function-to-cs-getch-in-java – SSaikia_JtheRocker Jul 09 '13 at 20:01

1 Answers1

13

The answer is simple

You can't do that

Because command line environment is different from swing, as swing can do such a thing as it deals with events and object, whereas, command line have no events.

So, maybe it's a right time to leave command line.

Community
  • 1
  • 1
Azad
  • 5,047
  • 20
  • 38