0

So basically Im trying to find a way to execute a block of code when I press down a key instead of having to scan in a string then pressing enter to invoke it. This is my first time asking a question here, also Im not really advance when it comes to code. Just trying to learn new things that will advance my coding knowledge. Here is my current code:

Main method (Im trying to change the part where I scan in the variable "key"):

import java.util.Scanner;

public class testGame {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    dungeon numberOne = new dungeon();

    String key;
    numberOne.setPlayer();
    numberOne.printLayout();

    Scanner input = new Scanner(System.in);
    for(int x = 0; x < Integer.MAX_VALUE; x++)
    {
        key = input.next();
        if(key.equals("w"))
        {
            numberOne.moveUp();
            numberOne.printLayout();

        }
        else if(key.equals("d"))
        {
            numberOne.moveRight();
            numberOne.printLayout();

        }
        else if(key.equals("s"))
        {
            numberOne.moveDown();
            numberOne.printLayout();

        }
        else if(key.equals("a"))
        {
            numberOne.moveLeft();
            numberOne.printLayout();

        }
        else
        {
            numberOne.printLayout();
        }
    }
}
}

Helper Class:

public class dungeon {
    private monster[] randMonster = new monster [10];
    private String printDungeon ="";
    private int x = 17;
    private int y = 34;
    private String pastLayout = "H";
    private String currentPostion = "O";
    private String[][] layout = //I deleted this as it was long. It was an 
 ASCII art layout..


public void printLayout()
    {
        for(int x = 0; x < layout.length; x ++)
        {
            for(int y = 0; y < layout[0].length; y++)
            {
                printDungeon = printDungeon + layout[x][y];
            }
            System.out.println(printDungeon);
            printDungeon = "";
        }
    }
    public void setPlayer()
    {
        layout[x][y] = "O";
    }
    public void moveUp()
    {
        if(layout[x-1][y].equals("#"))
        {}
        else
        {
        layout[x][y]=pastLayout;
        pastLayout = layout[x-1][y];
        layout[x-1][y] = currentPostion;
        x--;
        }
    }
    public void moveDown()
    {
        if(layout[x+1][y].equals("#"))
        {}
        else
        {
        layout[x][y]=pastLayout;
        pastLayout = layout[x+1][y];
        layout[x+1][y] = currentPostion;
        x++;
        }
    }
    public void moveLeft()
    {
        if(layout[x][y-1].equals("#"))
        {}
        else
        {
        layout[x][y]=pastLayout;
        pastLayout = layout[x][y-1];
        layout[x][y-1] = currentPostion;
        y--;
        }
    }
    public void moveRight()
    {
        if(layout[x][y+1].equals("#"))
        {}
        else
        {
        layout[x][y]=pastLayout;
        pastLayout = layout[x][y+1];
        layout[x][y+1] = currentPostion;
        y++;
        }
    }
}
Bryce
  • 1
  • 1
    Possible duplicate of [Detect a key press in console](https://stackoverflow.com/questions/27381021/detect-a-key-press-in-console) (second answer is the important one for this question). – Turing85 Jun 01 '18 at 14:33

1 Answers1

0

EDIT: This assumes you are making a GUI using javafx. I'm not sure if it works in the command line, but probably not :/

EDIT 2: A minor thing, but if you are updating the layout after each case you can instead just update the layout outside the scope of the if/else. It is good practice to factor out code and avoid copy-paste coding

There is a very simple way to do this using EventHandlers and KeyEvents!

This is an implementation that uses a switch statement. You can replace the switch with an if/else block if that suits you better, but if you don't know switch statements and do want to advance your knowledge of coding definitely look into them!

import javafx.event.EventHandler;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
public class SomeClass {
    public SomeClass() {
        //constructor elided
    }
    //Within your class containing your methods, have this private class.
    private class KeyHandler implements EventHandler<KeyEvent> {
        @Override
        public void handle(KeyEvent e) {
            KeyCode keyPressed = e.getCode();

            switch (keyPressed) {

            case W:
                //do W thing
                break;
            case A:
                //do A thing
                break;
            case S:
                //do S thing
                break;
            case D:
                //do D thing
                break;
            default:
                break;
            }
        }
    }
}

Best of luck! Have fun coding! p.s. You can take out the "// TODO Auto-generated method stub" comment––That is just there as a note from the editing software that the method needs to be filled in!

  • When adding the import statements at the top, it gives me an error like "The type 'KeyEvent' is not API." Does this have to do with what program Im using to run this code? Also any possible fix? Thanks! – Bryce Jun 01 '18 at 14:50
  • I'm not sure, to be honest. Check the edit on my response. How is this project being implemented? Is it just printing to the command line? I've only been coding for a year, but the first semester of that was focused on GUI based java projects. Sorry I can't be of more help! – Will Glaser Jun 01 '18 at 14:57
  • Either way, still look into switch statements to handle the key event. In the short run, it doesn't matter too much, but it cleans up the code and helps runtime a little. In a larger project with more input, there is a definite run time improvement with them – Will Glaser Jun 01 '18 at 14:58
  • if you are using command line, check out this post: https://stackoverflow.com/questions/4608854/in-java-what-is-the-best-way-to-capture-a-tab-keystroke/4609067#4609067 – Will Glaser Jun 01 '18 at 15:02