Java Pong无法一次移动两个球拍 [英] Java pong can't move both paddles at once

查看:127
本文介绍了Java Pong无法一次移动两个球拍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图用Java制作乒乓球,但无法同时移动两个桨.您可以移动一个或另一个,但不能同时移动两者.我需要使用2个不同的面板创建2个线程吗?

Trying to make pong in java but can't move both paddles at once. You can move one or the other but not both at the same time. Do I need to create 2 threads with 2 different pannels?

这是我指定关键事件的地方

Here is where I am specifying the key events

public void keyPressed(KeyEvent e) {

        if(e.getKeyCode() == KeyEvent.VK_A || e.getKeyCode() == KeyEvent.VK_S || e.getKeyCode() == KeyEvent.VK_QUOTE || e.getKeyCode() == KeyEvent.VK_SEMICOLON){
               if(e.getKeyCode() == KeyEvent.VK_A){
                   y-=10;
               }

         if(e.getKeyCode() == KeyEvent.VK_S){
                        y+=10;
                }

        if(e.getKeyCode() == KeyEvent.VK_QUOTE){
                ytwo-=10;
        }
         if(e.getKeyCode() == KeyEvent.VK_SEMICOLON){
                        ytwo+=10;
                }

        }
        }

这是完整的代码

import java.awt.Color;
import java.awt.Event;
import java.awt.Graphics;
import java.util.Random;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class Pong extends JFrame implements ActionListener{

        //implement constants

        PongPanel pongPanel = new PongPanel();  

        //JFrame pong x and y coordinates 
        static final int jfpX = 150;
        static final int jfpY = 20;

        // JFrame pong width and height
        static final int jfpW = 800;
        static final int jfpH = 600;

        Thread thrd;

        public static void main(String[] args) {
                Pong jfp = new Pong();
                jfp.setVisible(true);

        }

        public Pong(){
                setBounds(jfpX,jfpY,jfpW,jfpH); 
                setTitle("Pong");
                setResizable(false);
                setDefaultCloseOperation(EXIT_ON_CLOSE);
                setBackground(Color.black);


                add(pongPanel);
                addKeyListener(pongPanel);
                thrd = new Thread (pongPanel);
        thrd.start();
        }

        public void actionPerformed(ActionEvent e) {

        }



}

class PongPanel extends JPanel implements Runnable, KeyListener{
        Random random = new Random();
        static final int jpW = 800;
        static final int jpH = 600;
        int paddleStart = (jpH/2)-35;
        int paddleStarttwo = (jpH/2)-35;
        int ballStartX = (jpW/2)-20;
        int ballStartY = (jpH/2)-20;
        int ytwo,x,y;
        int ballD = 30;
        int paddleW1 = 20;
        int paddleH1 = 100;
        int paddleW2 = 20;
        int paddleH2 = 100;
        int min = -2;
        int max = 2;
        int randomBallx, randomBally;
//        int randomBallx = random.nextInt(max-min+1)+min;
//        int randomBally = random.nextInt(max-min+1)+min;

        int rand1 = random.nextInt(2-1 + 1)+1; // random for function to determine ballx and bally
        int rand2 = random.nextInt(2-1+2)+1;
        int dx = 4;
        int dy = 4; //direction of y

        public void ballNotZero(){// makes sure the ball doesnt go straight up and down
        if (randomBallx ==0){
              randomBallx = random.nextInt(max-min+1)+min;
             }
             if(randomBally == 0){
              randomBally=random.nextInt(max-min+1)+min;
             }
//         if(rand1 ==1){
//         randomBallx=-1;
//         }
//         if(rand1 ==2){
//         randomBallx=1;
//         }
//         if(rand2 ==1){
//         randomBally =-1;
//         }
//         if(rand2==2){
//         randomBally = 1;
//         }

        }


        public PongPanel(){

        }

        protected void paintComponent(Graphics g) 
        {
        super.paintComponent(g);

        Color ball;
        Color paddleOne;
        Color paddleTwo;
        ball = new Color(255,0,255);
        paddleOne = new Color(255,0,0);
        paddleTwo = new Color(0,0,255);


        g.setColor(ball);
        g.fillOval(ballStartX+randomBallx,ballStartY+randomBally,ballD,ballD);

        g.setColor(paddleOne);
        g.fillRect(20,paddleStart+y,paddleW1,paddleH1);

        g.setColor(paddleTwo);
        g.fillRect(760,paddleStarttwo+ytwo,paddleW2,paddleH2);



        }
        public void run() {
                while(true){
                ballNotZero(); 
                detectPaddle();
                randomBall();
                ballMove();
                repaint();
        try {Thread.sleep(75); } catch(Exception e){

        };

                }
        }
        public static boolean intervallContains(int low, int high, int n) { //determines if something is in a certain range
            return n >= low && n <= high;
        }
        public void detectPaddle(){  //determines if ball is close enough to paddle for detection
        int withinY = (paddleStart+y) -(ballStartY+randomBally);
        int withinY1 = (paddleStarttwo+ytwo)-(ballStartY+randomBally);

        if (ballStartX+randomBallx <=20  &&  intervallContains(-50,50,withinY)){
        dx = -dx;
        }
        if(ballStartX+randomBallx >=760 && intervallContains(-50,50,withinY1)){
        dx = -dx;
        }
        }

        public void randomBall(){
        if(randomBallx >=0 ){
        randomBallx+=dx;
        }
        if(randomBallx<0){
        randomBallx-=dx;
        }
        if(randomBally>=0){
        randomBally+=dy;
        }
        if(randomBally<0){
        randomBally-=dy;
        }
//                randomBallx+=randomBallx;
//                randomBally+=randomBally;
        }
        public void ballMove(){
        if(ballStartY+randomBally > jpH-60){
        dy= -dy;

        }
        if(ballStartY+randomBally <0){
        dy = -dy;
        }
        }

        public void keyPressed(KeyEvent e) {

        if(e.getKeyCode() == KeyEvent.VK_A || e.getKeyCode() == KeyEvent.VK_S || e.getKeyCode() == KeyEvent.VK_QUOTE || e.getKeyCode() == KeyEvent.VK_SEMICOLON){
               if(e.getKeyCode() == KeyEvent.VK_A){
                   y-=10;
               }

         if(e.getKeyCode() == KeyEvent.VK_S){
                        y+=10;
                }

        if(e.getKeyCode() == KeyEvent.VK_QUOTE){
                ytwo-=10;
        }
         if(e.getKeyCode() == KeyEvent.VK_SEMICOLON){
                        ytwo+=10;
                }

        }
        }



        public void keyTyped(KeyEvent e) {

        }

        @Override
        public void keyReleased(KeyEvent e) {
                // TODO Auto-generated method stub

        }

}

推荐答案

  • 不使用while (true),而是使用Swing计时器.
  • 不使用KeyListeners,而是使用Key Bindings.
  • 考虑打开一个Swing计时器(可以用作后台线程"),当绑定程序检测到已按下正确的键时,该计时器将移动一个桨,
  • 并在释放同一键时停止移动桨的计时器.
  • 与另一个拨片相同,但是当然它的动作会响应另一对键的绑定.
  • 在尝试使这种工作正常进行时,请尝试首先使其在一个非常简单的程序中运行,一个程序没有主程序所需的所有其他垃圾,但是一个程序可以让您测试和证明您的概念.然后,如果您可以在小型程序中正常工作,那么可以将功能添加到主程序中.而且,如果您的小型程序代码无法正常工作并且需要我们的帮助,则可以在此处发布小型独立程序( sscce )供我们测试和修改.
    • Don't use while (true) but rather a Swing timer.
    • Don't use KeyListeners but rather Key Bindings.
    • Consider turning on a Swing Timer (which can act as your "background thread") that moves one paddle when the bindings detect the correct key has been pressed,
    • and stopping the timer that moves the paddle when the same key is released.
    • Same for the other paddle but of course having its actions respond to a bindings of a different pair of keys.
    • When attempting to get something like this working, try to get it working in a very simple program first, one without all the other junk required for your main program, but one which will allow you to test and prove your concept. Then if you get things working in your small program, great, you add the functionality to your main program. And if your small program code doesn't work and you need our help, you can post the small self-contained program here (an sscce) for us to test and modify.
    • 这篇关于Java Pong无法一次移动两个球拍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆