Nenad
~Choco Coronet~ Omnomnom
- Reaction score
- 137
Well, looked around the interwebs and tried a few solutions nothing seems to work so far. I need to detect when a key is pressed, specifically the arrow keys. For now, I've got this method (There are other methods in but they have no relations with this one).
That is my entire code, and once again it would be helpful to explain what we're doing here. The main problem now is to get the actions keys to respond. Also, if anyone has any suggestions about improving the said code up top i don't mind that as well, but i would like to keep the focus on the main problem. Without this i won't really get far ^^
Edit: Oh and yeah, whenever i press a key nothing happens, i added a debugger before that prints a line but it doesn't activate, so my method does not in fact register the keys.
Code:
import java.awt.event.KeyEvent;
import acm.program.*;
public class Sokoban extends ConsoleProgram {
int xpos = 0;
int ypos = 0;
char mc = '@';
char hold = ' ';
char[][] grid = new char[7][9]; //Creates the grid based of the Level base imaginary two dimensional array in comments.
public void createlevel()
{
String Levelbase = ("########## $ .## ## ## @ ### #$$ ### #. .###########");
// "#########"
// "# $ .#"
// "# ## #"
// "# @ ##"
// "# #$$ ##"
// "# #. .##"
// "#########"
int k = -1; //Counts characters in Level Base.
for (int i=0; i<grid.length; i++)
{
for (int j=0; j<grid[i].length; j++)
{
k=k+1;
grid[i][j] = Levelbase.charAt(k);
if (j == 8) //Prints out the level.
{
println(grid[i][j]);
}
else
{
print(grid[i][j]);
}
}
}
xpos = 3; // Set x of main char;
ypos = 3; // Set y of main char;
}
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
switch( keyCode ) {
case KeyEvent.VK_UP:
mc = grid[xpos][ypos];
hold = grid[xpos][ypos-1];
mc = grid[xpos][ypos-1];
hold = grid[xpos][ypos];
break;
case KeyEvent.VK_DOWN:
mc = grid[xpos][ypos];
hold = grid[xpos][ypos+1];
mc = grid[xpos][ypos+1];
hold = grid[xpos][ypos];
break;
case KeyEvent.VK_LEFT:
mc = grid[xpos][ypos];
hold = grid[xpos-1][ypos];
mc = grid[xpos-1][ypos];
hold = grid[xpos][ypos];
break;
case KeyEvent.VK_RIGHT :
mc = grid[xpos][ypos];
hold = grid[xpos+1][ypos];
mc = grid[xpos+1][ypos];
hold = grid[xpos][ypos];
break;
}
}
public void run ()
{
createlevel();
}
}
That is my entire code, and once again it would be helpful to explain what we're doing here. The main problem now is to get the actions keys to respond. Also, if anyone has any suggestions about improving the said code up top i don't mind that as well, but i would like to keep the focus on the main problem. Without this i won't really get far ^^
Edit: Oh and yeah, whenever i press a key nothing happens, i added a debugger before that prints a line but it doesn't activate, so my method does not in fact register the keys.