Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (539)
Games in Android Showcase (132)
games submitted by our members
Games in WIP (603)
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  
  pressing 2 keys on the keyboard at the same time?  (Read 2178 times)
0 Members and 1 Guest are viewing this topic.
Offline VeNOM

Senior Newbie




[ G.O.A.T ] 4 life


« Posted 2003-02-17 05:47:00 »

:-/
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?
Offline princec

« JGO Spiffy Duke »


Medals: 434
Projects: 3
Exp: 16 years


Eh? Who? What? ... Me?


« Reply #1 - Posted 2003-02-17 08:12:40 »

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

1  
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 Smiley

Offline VeNOM

Senior Newbie




[ G.O.A.T ] 4 life


« Reply #2 - Posted 2003-02-17 11:33:19 »

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)?

Grin

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline princec

« JGO Spiffy Duke »


Medals: 434
Projects: 3
Exp: 16 years


Eh? Who? What? ... Me?


« Reply #3 - Posted 2003-02-17 12:24:33 »

Sure, this works just fine. Just try it.

Cas Smiley

Offline Abuse

JGO Knight


Medals: 14


falling into the abyss of reality


« Reply #4 - Posted 2003-02-17 17:07:52 »

cas, u need to correct your code sample Cheesy

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

when using bytes, you do something like this...
1  
dx = controls[RIGHT] - controls[LEFT];


if you use booleans, you've gotta do 1 of these instead...

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


or

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


Both of which are less efficient, and considerably more messy Cheesy

if only booleans in java could be interpretted as numeric values  Angry

Make Elite IV:Dangerous happen! Pledge your backing at KICKSTARTER here! https://dl.dropbox.com/u/54785909/EliteIVsmaller.png
Offline princec

« JGO Spiffy Duke »


Medals: 434
Projects: 3
Exp: 16 years


Eh? Who? What? ... Me?


« Reply #5 - Posted 2003-02-17 19:00:46 »

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

Cas Smiley

Offline erikd

JGO Ninja


Medals: 16
Projects: 4
Exp: 14 years


Maximumisness


« Reply #6 - Posted 2003-02-17 19:08:50 »

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

Offline Abuse

JGO Knight


Medals: 14


falling into the abyss of reality


« Reply #7 - Posted 2003-02-17 21:15:39 »

bah - you must all be insane Grin

Make Elite IV:Dangerous happen! Pledge your backing at KICKSTARTER here! https://dl.dropbox.com/u/54785909/EliteIVsmaller.png
Offline VeNOM

Senior Newbie




[ G.O.A.T ] 4 life


« Reply #8 - Posted 2003-02-18 08:32:55 »

Embarrassed 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..
Offline JuddMan

Senior Devvie


Medals: 1


Your Ad Here


« Reply #9 - Posted 2003-02-18 11:49:47 »

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.


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  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
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.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline VeNOM

Senior Newbie




[ G.O.A.T ] 4 life


« Reply #10 - Posted 2003-02-18 12:22:15 »

Cheesy
thanks going to test it and se if i can use it  Grin
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.

rwatson462 (30 views)
2014-12-15 09:26:44

Mr.CodeIt (23 views)
2014-12-14 19:50:38

BurntPizza (50 views)
2014-12-09 22:41:13

BurntPizza (84 views)
2014-12-08 04:46:31

JscottyBieshaar (45 views)
2014-12-05 12:39:02

SHC (59 views)
2014-12-03 16:27:13

CopyableCougar4 (57 views)
2014-11-29 21:32:03

toopeicgaming1999 (123 views)
2014-11-26 15:22:04

toopeicgaming1999 (114 views)
2014-11-26 15:20:36

toopeicgaming1999 (32 views)
2014-11-26 15:20:08
Resources for WIP games
by kpars
2014-12-18 10:26:14

Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50
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!