Как мне сделать так, чтобы круг в этом кадре действительно перемещался автоматически? - PullRequest
0 голосов
/ 31 декабря 2018

Я не могу обойти эту проблему.Я создал этот кадр и панель с желаемым результатом.Единственное, что я не смог понять, так это как заставить мяч двигаться «автоматически».В моей идеальной игре мяч / круг выпадал бы в начале игры, возможно, одним нажатием кнопки или чего-то подобного.Как бы я поступил так?

Я пытался переместить шар с помощью клавиши E, но это было бы слишком неудобно для пользователя, поэтому я решил, что его перемещение без обработчика событий будет лучшим выбором.

    private int ballX, ballY, ballR;
private int score1, score2;
private JPanel panel;
private JFrame frame;
private DrawingArea canvas;
private int xpos, ypos,width,height;
private int xpos2, ypos2, width2, height2;
public Pong(){
    xpos = 300;
    ypos = 550;
    width = 100;
    height = 50;

    xpos2 = 300;
    ypos2 = 100;
    width2 = 100;
    height2 = 50;

    ballR = 50;
    ballX = 325; 
    ballY = 330;


}
public static void main(String[]args){
    Pong p = new Pong();
    p.run();
}
public void run(){
    frame = new JFrame("Pong");
    frame.setSize(700,700);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    canvas = new DrawingArea();     // create a panel to draw on
    canvas.setBackground(Color.WHITE);
    canvas.addFocusListener(this);
    canvas.addKeyListener(this);
    canvas.addMouseListener(this);


    frame.getContentPane().add(canvas);
    frame.setVisible(true);
}
class DrawingArea extends JPanel {
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor ( Color.blue );
        g.fillRect ( xpos, ypos, width, height );
        g.setColor(Color.red);
        g.fillRect(xpos2, ypos2, width2, height2);


        g.setColor(Color.black);
        g.fillRect(0,0,700,50);
        g.fillRect(0,630,700,50);

        g.fillOval(ballX,ballY,ballR, ballR);

    }
}
public void keyPressed ( KeyEvent e )    {
    int value = e.getKeyCode();

    switch ( value )    {
        case KeyEvent.VK_RIGHT:     xpos += 50; break;
        case KeyEvent.VK_LEFT:      xpos -= 50; break;
        case KeyEvent.VK_A:         xpos2 -= 50; break;
        case KeyEvent.VK_D:         xpos2 += 50; break;
        /*try to drop the ball with the space button
         * case KeyEvent.VK_SPACE:
            ballX+=25;
            ballY+=25;
            break;
        case KeyEvent.VK_ENTER:
            xpos = (int)( Math.random ( ) * ( 500 - (2 * radius) ) );
            ypos = (int)( Math.random ( ) * ( 500 - (2 * radius) ) );
            break; 
        */
    }
    if( (xpos < 0 || xpos >= 700) || (xpos2 < 0 || xpos2 >= 700)){
         if(xpos < 0 || xpos2 < 0){
            if(xpos < 0) xpos = 0;
            else if(xpos2 < 0) xpos2 = 0;
            return;
        }
        else if(xpos >= 700 || xpos2 >= 700){
            if(xpos >= 700)xpos = 550;
            else if(xpos2 >= 700) xpos2=550;
            return;
        }
    }

    canvas.repaint ( );
}

}

Я ожидаю, что на выходе мяч упадет до синего прямоугольника с началом игры / нажатием кнопки, но я не могу заставить это работать.

1 Ответ

0 голосов
/ 31 декабря 2018

Поскольку вы хотите автоматически перемещать мяч, в методе run () измените положение шара (ваши xpos, ypos, xpos1 и ypos2) с некоторыми значениями приращения (как вы делали в методе интерфейса keyPressed ()) dx,dy и т. д. и вызовите метод repaint () вашего JFrame.

public class BouncingBall extends JPanel {

  // Box height and width
  int width;
  int height;

  // Ball Size
  float radius = 40; 
  float diameter = radius * 2;

  // Center of Call
  float X = radius + 50;
  float Y = radius + 20;

  // Direction
  float dx = 3;
  float dy = 3;

  public BouncingBall() {

    Thread thread = new Thread() {
      public void run() {
        while (true) {

          width = getWidth();
          height = getHeight();

          X = X + dx ;
          Y = Y + dy;

          if (X - radius < 0) {
            dx = -dx; 
            X = radius; 
          } else if (X + radius > width) {
            dx = -dx;
            X = width - radius;
          }

          if (Y - radius < 0) {
            dy = -dy;
            Y = radius;
          } else if (Y + radius > height) {
            dy = -dy;
            Y = height - radius;
          }
          repaint();

          try {
            Thread.sleep(50);
          } catch (InterruptedException ex) {
          }

        }
      }
    };
    thread.start();
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.BLUE);
    g.fillOval((int)(X-radius), (int)(Y-radius), (int)diameter, (int)diameter);
  }

  public static void main(String[] args) {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("Bouncing Ball");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 200);
    frame.setContentPane(new BouncingBall());
    frame.setVisible(true);
  }
}

Поскольку я использовал время рендеринга 50 мс в Thread.sleep (), вы можете указать свое время.Так что для меня каждые 50 мс ваш JFrame обновляется.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...