2013-07-09 2 views
3

나는 플레이어가 방 크기로 4x20 문자를 움직일 수있는 단순한 게임을 만들었다. 그것은 콘솔에서 실행됩니다.매번 누르지 않고 입력을받는 방법?

하지만 내 게임 루프에서 나는 내가 움직이기를 원할 때마다 enter를 누르지 않고 방안을 돌아 다닐 수 있기를 원합니다. 플레이어는 w/a/s/d를 눌러 즉시 화면을 업데이트 할 수 있어야하지만 어떻게해야할지 모르겠다.

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); 
} 
} 
+2

부울 zen! 'while (foo == true)'를 사용하지 말고'while (foo)'만 사용하십시오. '== true'와'== false'를 피하는 것이 좋습니다. – fvrghl

+0

가능한 복제본 [Java에서 콘솔에서 단일 문자를 읽는 방법 (사용자가 입력 할 때)?] (http://stackoverflow.com/questions/1066318/how-to-read-a-single-char- 콘솔에서 자바로 사용자 유형 - 그것) –

+0

이것을 확인하십시오 - http://stackoverflow.com/questions/1864076/equivalent-function-to-cs-getch-in-java –

답변

10

대답은 간단

당신은 할 수 없습니다

명령 줄 환경이 이벤트을 다루는으로 그런 일을 할 수 스윙으로 스윙 다르기 때문에 및 개체 반면 명령 줄에는 이벤트가 없습니다.

그래서 명령 줄을 종료하는 것이 적절한시기 일 수 있습니다.

관련 문제