0

This is the code of my key listener for a game.The keys move a plank upwards and downwards for two players.The problem is when one player keeps a key pressed then the other key event does not execute.what i want to do is that both players should be able to move their planks simultaneously.

private class MyKeyBoardListner implements KeyListener
    {
        boolean flag=true;
        public void keyPressed(KeyEvent ke)
        {

    //    System.out.println(ke.getKeyCode());

        if(ke.getKeyCode()==10||ke.getKeyCode()==27)
        {

            if(flag==false)        //pause logic with ESC and return key
            {ba.t.suspend();
        flag=!flag;
            }
            else if(flag==true)
            {        ba.t.resume();
                    flag=!flag;
            }
        }
        if(flag==false)//if paused key events wont work
        {

                    if(ke.getKeyCode()==83)
            {

                    System.out.println(ke.getKeyCode());
                    if(dr.y+100<=dr.getHeight())
                dr.y=dr.y+40;

            else if(dr.y+15<dr.getHeight())
                 dr.y=dr.y+15;
        dr.repaint(plank1);

            }
                if(ke.getKeyCode()==87)
            {
                    System.out.println(ke.getKeyCode());
                    if(dr.y-40>=0)
                dr.y=dr.y-40;
                dr.repaint(plank1);

            }
                if(ke.getKeyCode()==40)
            {

                    System.out.println(ke.getKeyCode());
                    if(dr.w+100<=dr.getHeight())
                dr.w=dr.w+40;
                    else if(dr.w+15<=dr.getHeight())
                        dr.w=dr.w+15;

            dr.repaint(plank2);

            }
                if(ke.getKeyCode()==38)
            {
                    System.out.println(ke.getKeyCode());
                    if(dr.w-40>=0)
                dr.w=dr.w-40;
            dr.repaint(plank2);

            }

        }
        }
2
Contributors
1
Reply
2
Views
6 Years
Discussion Span
Last Post by NormR1
0

problem is when one player keeps a key pressed then the other key event does not execute

Is there a referee that could prevent one player from cheating?

What is the flow of events to the key listener? Are there only event coming from the pressed key until that key is released? If so, the controls would be at the OS level.

If you are getting events from both keys you could restrict the time between handling key presses on a single key by requiring a minimum time between presses by using the System.currentTimeMillis() values.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.