2013-07-09 43 views
3

我做了一个简单的游戏(当然不是真正的游戏),玩家可以在4x20个字符的房间中移动。它在控制台中运行。如何在不按下每次输入的情况下获得输入?

但是在我的游戏循环中,我希望能够在房间内四处移动,而不必每次输入时都要输入。玩家应该可以按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

布尔禅!不要使用'while(foo == true)',只需使用'while(foo)'。避免使用== == true和== == false是很好的风格。 – fvrghl

+0

可能的重复[如何从Java控制台读取单个字符(用户键入它)?](http://stackoverflow.com/questions/1066318/how-to-read-a-single-char-从 - 控制台在Java中作为用户类型,它) –

+0

检查此 - http://stackoverflow.com/questions/1864076/equivalent-function-to-cs-getch-in-java –

回答

10

答案很简单

你不能这样做,

因为命令行环境是摆不同,如摆动可以做这样的事情,因为它与事件交易和对象,而命令行没有事件。

因此,也许这是离开命令行的正确时机。

相关问题