views:

65

answers:

1

OK so, is there an efficient way to detect on what array you're currently on by using the KeyListener?

My code: http://www.javadan.pastebin.com/X68VyuGL

What I am trying to do here is see if the current tile I am on is BLOCKED.

Thanks.

+2  A: 

I'm guessing you don't want to have to traverse the entire matrix every time to find out what tile the users on after a key event. Why not keep the state of the last position of the player on the board and use it when you're updating for each key event that occurs?

Alright, you wanted some more information on how to do this, I'll seed the answer for you and you can finish it :

public class tileGen extends Applet implements KeyListener  {

    Image[] tiles; // tile arrays
    Image player; // player image
    int x, y, px, py, tx, ty; // x tile - y tile // player x - player y // tile x - tile y
    boolean left, right, down, up, canMove; // is true?
    int[][] board; // row tiles for ultimate mapping experience!
    final int NUM_TILES = 25; // how many tiles are we implementing?
    Label lx, ly; // to see where we are!
    public final int BLOCKED = 1;

    int lastX, int lastY;  // <=== new member fields to track last X and last Y


    public void keyPressed(KeyEvent e) {

  //  UPDATE LAST X AND LAST Y IN THIS METHOD 
            if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                    left = true;
                    px = px - 32;
            }
            if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                    right = true;
                    px = px + 32;
            }
            if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                    down = true;
                    py = py + 32;
            }
            if (e.getKeyCode() == KeyEvent.VK_UP) {
                    up = true;
                    py = py - 32;
            }

            repaint();
    }


 }
Amir Afghani
How do I do that?
Dan
You can declare two new member fields in your tileGen class, lastX, and lastY, and use them accordingly. After an update, you set lastX and lastY, and upon entering an update, check the values of lastX and lastY.
Amir Afghani
member fields as in INT fields? But liek I said... how do I detect lastX and lastY?
Dan
Yes, I know that... but do you have any IDEA on how I would even do it?
Dan
Dan, are you looking for someone to finish this assignment for you? What specifically is your question? I outlined an approach for you - which part of my outline did you not understand?
Amir Afghani
I understand it all. I just don't know how I go about getting the current tile number they are on.
Dan
Isn't the value of px and py as computed in keyPressed method the current tile after the user pushes the arrow key?
Amir Afghani