Java-Gaming.org    
Featured games (79)
games approved by the League of Dukes
Games in Showcase (477)
Games in Android Showcase (106)
games submitted by our members
Games in WIP (533)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  How to listen multiple Key presses?  (Read 1190 times)
0 Members and 1 Guest are viewing this topic.
Offline Andre Lopes
« Posted 2013-03-18 03:42:56 »

Hello Forum!
Im having issues!

In my game, the player controls a snake, but i cant make it move right and up at the same time, or down and left, etc;;;

It can only go one direction at a time...
I researched a lot, but couldnt make it work.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
 @Override
    public void keyPressed(KeyEvent e) {
       
        boolean setaPraCima = false;
        boolean setaPraBaixo = false;
        boolean setaPraDireita = false;
        boolean setaPraEsquerda = false;
       
        //System.out.println("Pressed : Key Code :: " + e.getKeyCode() + " == " + e.getKeyChar());
       if (e.getKeyCode() == 38) { // Seta pra cima
           setaPraCima = true;
            gameUpdate.moveSnakeUp();
        } else
            if (e.getKeyCode() == 40)
            {
                setaPraBaixo = true;
                gameUpdate.moveSnakeDown();
            }else
                if(e.getKeyCode() == 39)
                {
                    setaPraDireita = true;
                    gameUpdate.moveSnakeRight();
                } else
                    if(e.getKeyCode() == 37)
                    {
                        setaPraEsquerda = true;
                        gameUpdate.moveSnakeLeft();
             
                    }
       
        gameUpdate.GameUpdate();

    }
Offline ReBirth
« Reply #1 - Posted 2013-03-18 07:18:07 »

Remove the ELSE.

Offline davidc

Senior Member


Medals: 5
Projects: 2



« Reply #2 - Posted 2013-03-18 11:25:38 »

I would change the way you're responding to key events by not implementing any game logic within the event listeners. Your program really shouldn't be driven by these event methods, as you will only receive one event a time. You also don't want to be updating the game entities every time an event is received - this leaves the program at the mercy of how rapidly the player can hammer the keyboard.

An alternative is to do only one simple thing during key event handlers, and that's register the fact that a key has been pressed (or released). The idea is that you have a boolean variable for each key that you're interested in. Or an array of booleans if you want to capture lots of different keystrokes. You then listen for keyDown and keyUp events. When a keyDown is received, set the variable to true. When a keyUp is received, set the variable for that key to false.

Your main program loop then only has to check the state of these variables to see what is being pressed and act accordingly. Your game loop (which runs in its own thread) might do something along these lines:

1  
2  
3  
4  
5  
while (not finished)
  1. figure out what the player wants to do by looking at these key variables
  2. calculate what the game entities want to do, by applying AI logic
  3. update the scene, checking for collisions etc
  4. render everything


Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Andre Lopes
« Reply #3 - Posted 2013-03-18 13:47:17 »

Thanks for the answers m8's;

I just made the game update in the control because i waas learning how to make it render in screen.
This time, im making the thread to do the gameloop.

Also,I took of the else too for a test, and it still happened.

I tried something like this :

"An alternative is to do only one simple thing during key event handlers, and that's register the fact that a key has been pressed (or released). The idea is that you have a boolean variable for each key that you're interested in. Or an array of booleans if you want to capture lots of different keystrokes. You then listen for keyDown and keyUp events. When a keyDown is received, set the variable to true. When a keyUp is received, set the variable for that key to false."

But it didnt work.. I made a list and worked on it, and was a mess!!!
Do you have any implementation example ,please?

Ty guys!!
Offline davidc

Senior Member


Medals: 5
Projects: 2



« Reply #4 - Posted 2013-03-18 14:10:43 »

This is a very basic keyboard handler class that you can use to listen for multiple key presses. It will respond to the first 128 key codes as defined in the KeyEvent class. If you need to respond to codes above this range, just increase the array size accordingly. You can see all of the codes here:
http://docs.oracle.com/javase/6/docs/api/constant-values.html#java.awt.event.KeyEvent.CHAR_UNDEFINED

And now for Keyboard.java:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Keyboard {

    private static boolean[] pressed = new boolean[128];

    public static boolean isPressed(int key) {
        return pressed[key];
    }
 
   public static KeyListener listener = new KeyAdapter() {

        @Override
        public void keyPressed(KeyEvent e) {
            int code = e.getKeyCode();
            if (code < pressed.length) {
                pressed[code] = true;
            }
        }

        @Override
        public void keyReleased(KeyEvent e) {
            int code = e.getKeyCode();
            if (code < pressed.length) {
                pressed[code] = false;
            }
        }
    };
}


The class defines a static member which is the listener, and can be added to your JPanel (or Applet) as follows:
1  
panel.addKeyListener(KeyBoard.listener);


Checking if a key has been pressed in your thread is as easy as:
1  
2  
3  
4  
5  
6  
if (Keyboard.isKeyPressed(KeyEvent.VK_LEFT)) {
    ...
}
if (Keyboard.isKeyPressed(KeyEvent.VK_DOWN)) {
    ...
}


One known limitation of this code is that if a key is pressed and released before your main game loop thread has a chance to read its state, then it will be missed. I have a solution to this, but have edited it out just to make the example a lot simpler to follow. It isn't such a big deal.[/code][/code]
Offline StonePickaxes

JGO Coder


Medals: 4
Projects: 2


Nathan Kramber


« Reply #5 - Posted 2013-03-18 17:45:34 »

Here's the listener that I use. I got it from Notch.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
public class Input implements KeyListener {

   public List<Key> keys = new ArrayList<Key>();
   
   public Key up = new Key();
   public Key down = new Key();
   public Key left = new Key();
   public Key right = new Key();
   public Key exit = new Key();
   
   public Input(Main game) {
      game.addKeyListener(this);
   }
   
   @Override
   public void keyPressed(KeyEvent e) {
      toggle(e, true);
   }

   @Override
   public void keyReleased(KeyEvent e) {
      toggle(e, false);
   }

   @Override
   public void keyTyped(KeyEvent e) { }
   
   private void toggle(KeyEvent e, boolean pressed) {
      if (e.getKeyCode() == KeyEvent.VK_UP) up.toggle(pressed);
      if (e.getKeyCode() == KeyEvent.VK_DOWN) down.toggle(pressed);
      if (e.getKeyCode() == KeyEvent.VK_LEFT) left.toggle(pressed);
      if (e.getKeyCode() == KeyEvent.VK_RIGHT) right.toggle(pressed);
      if (e.getKeyCode() == KeyEvent.VK_ESCAPE) exit.toggle(pressed);
   }
   
   public void releaseAll() {
      for (Key key : keys) key.down = false;
   }
   
   
   public class Key {
      public boolean down;
     
      public Key() {
         keys.add(this);
      }
     
      public void toggle(boolean pressed) {
         if (pressed != down) down = pressed;
      }
   }
}

Check out my website!
Offline Andre Lopes
« Reply #6 - Posted 2013-03-25 16:47:21 »

IT WORKED!
Like a charm!!!!

I love you xD
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

pw (24 views)
2014-07-24 01:59:36

Riven (24 views)
2014-07-23 21:16:32

Riven (18 views)
2014-07-23 21:07:15

Riven (21 views)
2014-07-23 20:56:16

ctomni231 (50 views)
2014-07-18 06:55:21

Zero Volt (45 views)
2014-07-17 23:47:54

danieldean (36 views)
2014-07-17 23:41:23

MustardPeter (39 views)
2014-07-16 23:30:00

Cero (55 views)
2014-07-16 00:42:17

Riven (55 views)
2014-07-14 18:02:53
HotSpot Options
by dleskov
2014-07-08 03:59:08

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:58:24

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:47:22

How do I start Java Game Development?
by ra4king
2014-05-17 11:13:37

HotSpot Options
by Roquen
2014-05-15 09:59:54

HotSpot Options
by Roquen
2014-05-06 15:03:10

Escape Analysis
by Roquen
2014-04-29 22:16:43

Experimental Toys
by Roquen
2014-04-28 13:24:22
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!