Search code examples
javapacman

keep reading input while program runs


I'm trying to code a simple pacman/snake game for my upcoming test. Since we won't be using GUI (it's not taught yet, I don't understand it, and I don't know if they allow it), the game will run on console/command line. How can I make my pacman or snake keep moving while the program reads my input? for example, if I press right arrow or 'D', snake or pacman will head right, and it will keep on running right until I press another button (in my program, it means that X coordinate in my array will keep increasing by 1) I don't know if it's even possible, any help is appreciated

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

Solution

  • It seems like a listener is the thing that you might be looking for. You need to make the class that you've decided should handle input implements KeyListener and then override one or more of the following methods to get your desired behavior. On top of this, you need to make sure that your program won't exit on the first run through, so a game loop is needed. There is a more complete example on how to write a KeyListener in the Java docs.

    If you want pacman to keep going in a direction, you could set a currentDirection variable that moves him each frame in the direction needed, that's set when you press the key.

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