如何在不按每次输入的情况下获取输入? [英] How to get input without pressing enter every time?

查看:88
本文介绍了如何在不按每次输入的情况下获取输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个简单的游戏(当时还不是真正的游戏),玩家可以在4x20个字符的房间内移动。它在控制台中运行。

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.

但在我的游戏循环中,我希望能够在房间内四处移动,而不是每次想要移动时都按下输入。玩家应该可以按w / a / s / d并立即更新屏幕,但我不知道该怎么做。

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


推荐答案

答案很简单

因为命令行环境不同于swing,所以 swing 可以做这样的事情,因为它处理事件对象,而命令行没有事件。

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.

这篇关于如何在不按每次输入的情况下获取输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆