程序运行时继续读取输入

时间:2014-09-29 08:53:09

标签: java pacman

我试图为即将进行的测试编写一个简单的pacman / snake游戏。由于我们不会使用GUI(它还没有被教授,我不理解它,而且我不知道他们是否允许它),游戏将在控制台上运行/命令行。当程序读取我的输入时,如何让我的pacman或snake继续移动? 例如,如果我按向右箭头或者D',蛇或者pacman会向右转,并且它会一直向右运行,直到我按下另一个按钮(在我的程序中,它表示我的数组中的X坐标)将继续增加1)我不知道它是否可能,任何帮助表示赞赏

static void mapInit(){ // this is the map. I use 10x10 array. I made it so any blank space that pacman or snake can move have 0 value
        for (int i = 0; i < map.length; i++) {
            for (int j = 0; j < map.length; j++) {
                if(i == 0 || i == 9)
                map[i][j] = rand.nextInt(9)+1;
                else if(i != 0 && i != 9){
                 if( j == 9 || j == 0) map[i][j] = rand.nextInt(9)+1;
                }//else if
                } //second for
            } // top for

    } //mapInit
    static void world(){ // this prints out the map and the snake
        for (int i = 0; i < map.length; i++) {
            for (int j = 0; j < map.length; j++) {
                if(i == y && j == x) {  // X and Y is the coordinate of my snake or pacman
                    System.out.print("C");
                    System.out.print(" ");
                }
                    else if (map[i][j] == 0) {
                        System.out.print(" ");
                        System.out.print(" ");


                    }
                        else {
                        System.out.print(map[i][j]);
                        System.out.print(" "); 
                        }
            }
            System.out.println();
        }


    } // world

1 个答案:

答案 0 :(得分:2)

似乎listener是您可能正在寻找的东西。您需要使您已决定应该处理输入implements KeyListener的类,然后重写以下一个或多个方法以获得所需的行为。除此之外,您需要确保您的程序在第一次运行时不会退出,因此需要游戏循环。有关如何在Java docs中编写KeyListener的更完整示例。

如果你想让pacman继续向一个方向前进,你可以设置一个currentDirection变量,让每个帧按照所需的方向移动,当你按下键时就会设置。

public void keyTyped(KeyEvent e) {
    displayInfo(e, "KEY TYPED: ");
}

/** Handle the key-pressed event from the text field. */
public void keyPressed(KeyEvent e) {
    displayInfo(e, "KEY PRESSED: ");
}

/** Handle the key-released event from the text field. */
public void keyReleased(KeyEvent e) {
    displayInfo(e, "KEY RELEASED: ");
}