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