pressing 2 keys on the keyboard at the same time?

:-/
Im working on a game that needs to be able to handle if more than one button is pressed on the keyboard. The problem now is that when i press 2 buttons like e and r the comp thakes the last one of the keys that is pressed and just repeat it. like reeeeeeeeeee… i want rerererer and so on… can this be fixed?

Yes. What you want to do is keep a big list of key states in a boolean array:


boolean[] keyDown = new boolean[256];

Instead of looking at keyTyped events you want to look at keyPressed and keyReleased events instead; in those events you set and unset the corresponding boolean.

In your game loop you don’t listen for events directly, you just look at the state of the boolean array for the keys you’re interested in.

Cas :slight_smile:

So if you hold down a key (a for an example) and it types out “aaaaaaa” on the screen, you actually press down and release the a key?

But does this enable other keys to used, so the program recognise 2 different buttons at the same time, and then handles them seperately?

I mean, that if you press down the r and e key, the program can recognise a “press down” and “release” on the r key and then also the e key (and so forth)?

;D

Sure, this works just fine. Just try it.

Cas :slight_smile:

cas, u need to correct your code sample :smiley:

also, I find a byte[256] is more useful - for instance…

when using bytes, you do something like this…


dx = controls[RIGHT] - controls[LEFT];

if you use booleans, you’ve gotta do 1 of these instead…


if(controls[LEFT]^controls[RIGHT])
{
   if(controls[LEFT]) dx = -1;
   else dx =1;
}

or


dx=0;
if(controls[LEFT]) dx--;
if(controls[RIGHT]) dx++;

Both of which are less efficient, and considerably more messy :smiley:

if only booleans in java could be interpretted as numeric values >:(

Fixed it :slight_smile:
I prefer the way Java handles booleans. Your last code example is very easy to understand the meaning of.

Cas :slight_smile:

Yes, I agree the last code is best.
Efficiency is not an issue here, readability always is.

bah - you must all be insane ;D

:-[ i dont get the picture… how am i going to impliment it? Does anyone have a adress to a page with an exampel on it?
i really greatful for ur help. :wink: u r really nice taking time to answer all of the questions…

Working demo (altered for this thread). 2 classes, just save into the one java file as BufferStrat.java…

this is probably not the best way to do keylistener but it works very nicely for me. you’d possibly want to extend that array and make it track every key on the keyboard but i don’t plan to let my users change their key config for now…

here, it’s used in the render() method though for most purposes you’d put it somewhere else.


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.image.BufferStrategy; 
 
 
public class BufferStrat 
{ 
      final int SPEED = 10;
      JFrame mainFrame; 
      BufferStrategy bufferStrategy; 
      int ScreenWidth; 
      int ScreenHeight; 
      boolean Running = true; 
      JPanel cp;
      int n = 0;
      int buffers = 2;
      long oldTime;
      long newTime;
      int ticks = 0;
      int lastTicks = 0;
      XKListener keys = new XKListener();
      public BufferStrat() 
      {
            //------
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); 
            GraphicsDevice gd = ge.getDefaultScreenDevice(); 
            GraphicsConfiguration gc = gd.getDefaultConfiguration(); 
            mainFrame = new JFrame(gc);
            cp = (JPanel)mainFrame.getContentPane();
            cp.setLayout(null);
            mainFrame.setIgnoreRepaint(true);
            mainFrame.setResizable(false);
            ScreenWidth = 520;
            ScreenHeight = 568;
            mainFrame.setSize(new Dimension(ScreenWidth, ScreenHeight)); 
            mainFrame.show();
            mainFrame.createBufferStrategy( 2 );
            bufferStrategy = mainFrame.getBufferStrategy();
            
            long oldTime = System.currentTimeMillis();
            
            //*****
            mainFrame.addKeyListener(keys);
            mainFrame.addWindowListener(new WindowAdapter() {
                  public void windowClosing(WindowEvent e) {
                        System.exit(0);
                  }
            });
            GT.start();
      }
      
      public void go()
      {
            //do game loop stuff here... i.e if left is pressed, move dude left.
            //would be if(keys.keyStates[2])
            // sprite.moveLeft() (or something)
            render();
      }
      int i = 0;
      private void render() 
      { 
            if( !bufferStrategy.contentsLost() ) 
            { 
                  Graphics g = bufferStrategy.getDrawGraphics(); 
                  
                  // Clear the drawing buffer to white 
                  g.setColor( Color.white ); 
                  g.fillRect( 0, 0, ScreenWidth, ScreenHeight ); 
                  
                  g.setColor(Color.blue);
                  g.drawString("Use the arrow keys", 150, 200);
                  
                  if(keys.keyStates[0])
                  g.fillRect( 250, 250, 40, 40 );
                  else g.drawRect( 250, 250, 40, 40 ); 
                  if(keys.keyStates[1])
                  g.fillRect( 250, 300, 40, 40 );
                  else g.drawRect( 250, 300, 40, 40 ); 
                  if(keys.keyStates[2])
                  g.fillRect( 200, 300, 40, 40 );
                  else g.drawRect( 200, 300, 40, 40 ); 
                  if(keys.keyStates[3])
                  g.fillRect( 300, 300, 40, 40 );
                  else g.drawRect( 300, 300, 40, 40 ); 
                  
                  
                  bufferStrategy.show(); 
                  g.dispose(); 
            } 
      }
      public static void main( String[] args ) 
      { 
            BufferStrat test = new BufferStrat(); 
      } 
      ///timer
      ActionListener clickLsn = new ActionListener()
            {
                  public void actionPerformed(ActionEvent e)
                  {
                        go();
                  }
            };
      Timer GT = new Timer(SPEED, clickLsn);
} 


class XKListener implements KeyListener
{
      public boolean keyStates[] = new boolean[4];
      //cause we are checking 4 keys... you probably want more.
      int keyCode;
      char c;
      public XKListener()
      {
            //initialise all the keys as not pressed.
            for (int i=0; i<keyStates.length; i++)
            keyStates[i] = false;
      }
      // Handle the key typed event. does nothing.
      //this is how you would have been previously doing it
      public void keyTyped(KeyEvent e){}

      /** Handle the key pressed event. */
      public void keyPressed(KeyEvent e)
      {
            setBoolean(e, true);
      }

      /** Handle the key released event. */
      public void keyReleased(KeyEvent e)
      {
            setBoolean(e, false);
      }
      
      protected void setBoolean(KeyEvent e, boolean isPressed)
      {
            c = e.getKeyChar();
            keyCode = e.getKeyCode();
            switch (keyCode)
            {
            case (KeyEvent.VK_UP):
            keyStates[0] = isPressed;
            break;
            case (KeyEvent.VK_DOWN):
            keyStates[1] = isPressed;
            break;
            case (KeyEvent.VK_LEFT):
            keyStates[2] = isPressed;
            break;
            case (KeyEvent.VK_RIGHT):
            keyStates[3] = isPressed;
            break;
            default:
            System.out.println("Not using that key");
            }
      }
}


it’s a bit long cause it’s part of another demo that i used … so you also have a double buffering demo here as well if you need it, tho it’s shown off doing more flashy stuff in another thread here.

:smiley:
thanks going to test it and se if i can use it ;D