java PING PONG capture keys

1

I'm doing a ping pong game in java. The project has just started so that only the 2 rackets can be moved at the moment.

The problem is when moving the rackets. The first moves up and down with the keys W and S respectively, the second racket moves with the arrow keys up and down respectively. Rackets move correctly if only one moves at a time; However, when moving both at the same time, one stops the other. I would like to know how I could make them move independently so that one does not affect the movement of the other.

package juego.ping.pong;

import java.awt.Color;
import javax.swing.*;
import java.awt.event.*;

public class JuegoPingPong extends JFrame implements ActionListener
{
    // componentes swing
    private JMenuBar jMBMenu;
    private JMenu jMJuego;
    private JMenu jMPuntuaciones;
    private JMenuItem jMIJuegoNuevo;
    private JMenuItem jMIPuntuaciones;

    private JLabel jLLinea1;  
    private JLabel jLLinea2;
    private JLabel jLLineaPunteada;
    private JLabel jLRaqueta1;
    private JLabel jLRaqueta2;
    private JLabel jLPelota;
    private JLabel jLAvatarJ1;
    private JLabel jLAvatarJ2;
    private JLabel jLPuntuacionJ1;
    private JLabel jLPuntuacionJ2;
    private JLabel jLVs;
    private JLabel jLFondo;

    // variables internas
    private String Jugador1;
    private String Jugador2;
    private int tipoJuego;
    private int puntuacionJ1;
    private int puntuacionJ2;

    // ActionListener para los menos

    public void actionPerformed(ActionEvent e) 
    {
        if (e.getSource() == jMIJuegoNuevo) 
        {
            System.out.println("juego");
        }

        if (e.getSource() == jMIPuntuaciones) 
        {
            System.out.println("puntos");
        }
    }

    // Constructor
    public JuegoPingPong()
    {
        super("The Cerdo´s Pong");
        setLayout(null);

        initComponents();

        // Menus
        jMJuego = new JMenu("Juego");
        jMJuego.setForeground( Color.WHITE );

        jMIJuegoNuevo = new JMenuItem( "Juego Nuevo" );     
        jMIJuegoNuevo.addActionListener(this);
        jMJuego.add(jMIJuegoNuevo);

        jMPuntuaciones = new JMenu("Puntuaciones");   
        jMPuntuaciones.setForeground( Color.WHITE );

        jMIPuntuaciones = new JMenuItem("Puntuacion Total");    
        jMIPuntuaciones.addActionListener(this);
        jMPuntuaciones.add( jMIPuntuaciones );

        jMBMenu = new JMenuBar();
        jMBMenu.setLocation( 0,0 );
        jMBMenu.setVisible( true );
        jMBMenu.setSize( 1244, 20 );
        jMBMenu.setBackground( new Color( 0, 15, 22) );
        add( jMBMenu );

        jMBMenu.add( jMJuego );
        jMBMenu.add( jMPuntuaciones );

        // labels 

        jLVs = new JLabel();
        jLVs.setIcon(new ImageIcon (  
getClass().getResource("/Imagenes/vs.png" ) ) );  
        jLVs.setLocation( 607, 65 );
        jLVs.setSize( 30,  29 );
        add(jLVs);

        jLLinea1 = new JLabel();
        jLLinea1.setIcon(new ImageIcon (  
getClass().getResource("/Imagenes/linea.png" ) ) ); 
        jLLinea1.setSize( 1166, 20 );
        jLLinea1.setLocation( 39,100 );
        add(jLLinea1);

        jLLinea2 = new JLabel();
        jLLinea2.setIcon(new 
ImageIcon(getClass().getResource("/Imagenes/linea.png")));
        jLLinea2.setSize(1166, 20);
        jLLinea2.setLocation(39, 630);
        add(jLLinea2);

        jLLineaPunteada = new JLabel();
        jLLineaPunteada.setIcon(new 
ImageIcon(getClass().getResource("/Imagenes/linea punteada.png")));
        jLLineaPunteada.setSize(22, 524);
        jLLineaPunteada.setLocation(611, 112);
        add(jLLineaPunteada);

        jLAvatarJ1 = new JLabel();
        jLAvatarJ1.setSize( 72,70 );
        jLAvatarJ1.setIcon(new 
ImageIcon(getClass().getResource("/Imagenes/brown.png")));
        jLAvatarJ1.setLocation( 500, 25  );
        add(jLAvatarJ1);

        jLAvatarJ2 = new JLabel();
        jLAvatarJ2.setSize(72, 70);
        jLAvatarJ2.setIcon(new 
ImageIcon(getClass().getResource("/Imagenes/lobillo.png")));
        jLAvatarJ2.setLocation(700, 25);
        add(jLAvatarJ2);


        jLRaqueta1 = new JLabel();
        jLRaqueta1.setOpaque( true );
        jLRaqueta1.setBackground( Color.WHITE );
        jLRaqueta1.setSize( 31, 102 );
        jLRaqueta1.setLocation( 30, 345 );
        add(jLRaqueta1);

        jLRaqueta2 = new JLabel();
        jLRaqueta2.setOpaque( true );
        jLRaqueta2.setBackground( Color.WHITE );
        jLRaqueta2.setSize(31, 102);
        jLRaqueta2.setLocation(1200, 345);
        add(jLRaqueta2);

        // Fondo

        jLFondo = new JLabel();
        jLFondo.setSize( 1244,  690 );
        jLFondo.setOpaque( true );
        jLFondo.setLocation( 0,0 );
        jLFondo.setBackground( new Color( 0,15,22 ) );
        add( jLFondo );


    }


    public static void main(String[] args) 
    {
        JuegoPingPong juego = new JuegoPingPong();
        juego.setVisible(true);
        juego.setSize(1244, 715);
        juego.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        juego.setResizable(false);
        juego.setLocationRelativeTo(null);

    }

    private void initComponents() {
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) 
            {
                formKeyPressed(evt);
            }

        });
    }

    private void formKeyPressed(java.awt.event.KeyEvent evt) 
    {
        if (evt.getKeyCode() == KeyEvent.VK_W) 
        {
            jLRaqueta1.setLocation( jLRaqueta1.getX(), jLRaqueta1.getY() - 
10);
        }

        if (evt.getKeyCode() == KeyEvent.VK_S) 
        {
            jLRaqueta1.setLocation(jLRaqueta1.getX(), jLRaqueta1.getY() + 
10);
        }

        if (evt.getKeyCode() == KeyEvent.VK_UP) 
        {
            jLRaqueta2.setLocation(jLRaqueta2.getX(), jLRaqueta2.getY() - 
10);
        }

        if (evt.getKeyCode() == KeyEvent.VK_DOWN) 
        {
            jLRaqueta2.setLocation(jLRaqueta2.getX(), jLRaqueta2.getY() + 
10);
        }


    }

}
    
asked by Abner 19.05.2017 в 08:52
source

2 answers

1

This is the solution to your problem. I have generated an EventSelector class responsible for handling the click events on the screen.

If the click event is among the allowed ones and has not been previously registered, it adds it to a synchronized list of events. When the event ceases to exist. Something that is controlled in the method, keyReleased. That event is deleted from the list.

Finally I put the cursors in a class in charge of updating the positions so that the code is easier to maintain.

The update speed of the cursors is handled with the time set in Thread.sleep (). In this case it is 20 milliseconds

import java.awt.Color;

import javax.swing.*;

import java.awt.event.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.awt.event.KeyEvent;

public class TesTest extends JFrame implements ActionListener
{

    public class EventSelector implements Runnable, KeyListener{

        Raqueta left;
        Raqueta right;
        List<KeyEvent> list = Collections.synchronizedList(new ArrayList());

        EventSelector(Raqueta left, Raqueta right){
            this.left = left;
            this.right = right;
        }

        @Override
        public void run() {
            while(true){
                try {
                    Thread.sleep(20L);
                    if(!list.isEmpty()){
                        for (KeyEvent event : list) {
                            if(left.isInRaqueta(event.getKeyCode())){
                                left.formKeyPressed(event);
                            }else if(right.isInRaqueta(event.getKeyCode())){
                                right.formKeyPressed(event);
                            }
                        }
                    }

                } catch (InterruptedException e) {
                }
            }
        }

        @Override
        public void keyPressed(KeyEvent arg0) {
            if(containsEvent(arg0)<0){
                list.add(arg0);
            }
        }

        private int containsEvent(KeyEvent arg0) {
            int pos = 0;
            for (KeyEvent event : list) {
                if(event.getKeyCode()==arg0.getKeyCode()){
                    return pos;
                }
                pos++;
            }
            return -1;
        }

        @Override
        public void keyReleased(KeyEvent arg0) {
            list.remove(containsEvent(arg0));
        }

        @Override
        public void keyTyped(KeyEvent arg0) {
        }

    }

    // componentes swing
    private JMenuBar jMBMenu;
    private JMenu jMJuego;
    private JMenu jMPuntuaciones;
    private JMenuItem jMIJuegoNuevo;
    private JMenuItem jMIPuntuaciones;

    private JLabel jLLinea1;  
    private JLabel jLLinea2;
    private JLabel jLLineaPunteada;
    private JLabel jLRaqueta1;
    private JLabel jLRaqueta2;
    private JLabel jLPelota;
    private JLabel jLAvatarJ1;
    private JLabel jLAvatarJ2;
    private JLabel jLPuntuacionJ1;
    private JLabel jLPuntuacionJ2;
    private JLabel jLVs;
    private JLabel jLFondo;

    // variables internas
    private String Jugador1;
    private String Jugador2;
    private int tipoJuego;
    private int puntuacionJ1;
    private int puntuacionJ2;

    private EventSelector selector;

    // ActionListener para los menos

    public void actionPerformed(ActionEvent e) 
    {
        if (e.getSource() == jMIJuegoNuevo) 
        {
            System.out.println("juego");
        }

        if (e.getSource() == jMIPuntuaciones) 
        {
            System.out.println("puntos");
        }
    }

    // Constructor
    public TesTest(Raqueta left, Raqueta right)
    {
        super("The Cerdo´s Pong");
        setLayout(null);

        selector = new EventSelector(left, right);
        left.addToFrame(this);
        right.addToFrame(this);
        new Thread(selector).start();

        // Menus
        jMJuego = new JMenu("Juego");
        jMJuego.setForeground( Color.WHITE );

        jMIJuegoNuevo = new JMenuItem( "Juego Nuevo" );     
        jMIJuegoNuevo.addActionListener(this);
        jMJuego.add(jMIJuegoNuevo);

        jMPuntuaciones = new JMenu("Puntuaciones");   
        jMPuntuaciones.setForeground( Color.WHITE );

        jMIPuntuaciones = new JMenuItem("Puntuacion Total");    
        jMIPuntuaciones.addActionListener(this);
        jMPuntuaciones.add( jMIPuntuaciones );

        jMBMenu = new JMenuBar();
        jMBMenu.setLocation( 0,0 );
        jMBMenu.setVisible( true );
        jMBMenu.setSize( 1244, 20 );
        jMBMenu.setBackground( new Color( 0, 15, 22) );
        add( jMBMenu );

        jMBMenu.add( jMJuego );
        jMBMenu.add( jMPuntuaciones );

        // labels 

        jLVs = new JLabel();
        jLVs.setIcon(new ImageIcon ( getClass().getResource("/Imagenes/vs.png" ) ) );  
        jLVs.setLocation( 607, 65 );
        jLVs.setSize( 30,  29 );
        add(jLVs);

        jLLinea1 = new JLabel();
        jLLinea1.setIcon(new ImageIcon ( getClass().getResource("/Imagenes/linea.png" ) ) ); 
        jLLinea1.setSize( 1166, 20 );
        jLLinea1.setLocation( 39,100 );
        add(jLLinea1);

        jLLinea2 = new JLabel();
        jLLinea2.setIcon(new ImageIcon(getClass().getResource("/Imagenes/linea.png")));
        jLLinea2.setSize(1166, 20);
        jLLinea2.setLocation(39, 630);
        add(jLLinea2);

        jLLineaPunteada = new JLabel();
        jLLineaPunteada.setIcon(new ImageIcon(getClass().getResource("/Imagenes/linea punteada.png")));
        jLLineaPunteada.setSize(22, 524);
        jLLineaPunteada.setLocation(611, 112);
        add(jLLineaPunteada);

        jLAvatarJ1 = new JLabel();
        jLAvatarJ1.setSize( 72,70 );
        jLAvatarJ1.setIcon(new ImageIcon(getClass().getResource("/Imagenes/brown.png")));
        jLAvatarJ1.setLocation( 500, 25  );
        add(jLAvatarJ1);

        jLAvatarJ2 = new JLabel();
        jLAvatarJ2.setSize(72, 70);
        jLAvatarJ2.setIcon(new ImageIcon(getClass().getResource("/Imagenes/lobillo.png")));
        jLAvatarJ2.setLocation(700, 25);
        add(jLAvatarJ2);

        // Fondo

        jLFondo = new JLabel();
        jLFondo.setSize( 1244,  690 );
        jLFondo.setOpaque( true );
        jLFondo.setLocation( 0,0 );
        jLFondo.setBackground( new Color( 0,15,22 ) );
        add( jLFondo );

        addKeyListener(selector);

    }


    public static void main(String[] args) 
    {

        Raqueta left = new Raqueta(30, 345, KeyEvent.VK_W, KeyEvent.VK_S);
        Raqueta right = new Raqueta(1200, 345, KeyEvent.VK_UP, KeyEvent.VK_DOWN);

        TesTest juego = new TesTest(left,right);

        juego.setVisible(true);
        juego.setSize(1244, 715);
        juego.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        juego.setResizable(false);
        juego.setLocationRelativeTo(null);

    }
}

class Raqueta{

    private JLabel raqueta;
    private int up;
    private int down;

    public Raqueta(int x, int y, int up, int down){
        raqueta = new JLabel();
        raqueta.setOpaque( true );
        raqueta.setBackground( Color.WHITE );
        raqueta.setSize( 31, 102 );
        raqueta.setLocation( x, y );
        this.up = up;
        this.down = down;
    }

    public void addToFrame(TesTest tesTest) {
        tesTest.add(raqueta);
    }

    public boolean isInRaqueta(int keyCode) {
        return  keyCode == up || keyCode == down;
    }

    public void formKeyPressed(java.awt.event.KeyEvent evt) 
    {
        if (evt.getKeyCode() == up) 
        {
            raqueta.setLocation( raqueta.getX(), raqueta.getY() - 10);
        }

        if (evt.getKeyCode() == down) 
        {
            raqueta.setLocation(raqueta.getX(), raqueta.getY() +10);
        }
    }
}
    
answered by 19.05.2017 / 11:32
source
-1

In java to do 2 things at once you have no choice but to go to threads

Example: link

The most advisable thing is that both threads capture the keyPressed, only that the first will only treat the W and the S and the other the arrows.

    
answered by 19.05.2017 в 09:22