Как я могу заставить круги сжаться до точки, а затем они исчезнут в этой функции - PullRequest
0 голосов
/ 09 июля 2020

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

 import java.awt.*;       // Using AWT's Graphics and Color
import java.awt.event.*; // Using AWT's event classes and listener interface
import java.util.Random;
import javax.swing.*;    // Using Swing's components and containers
/**
 * Custom Graphics Example: Using key/button to move a line left or right.
 */
@SuppressWarnings("serial")

public class CGMoveALine extends JFrame {
   // Define constants for the various dimensions
   public static final int CANVAS_WIDTH = 500;
   public static final int CANVAS_HEIGHT = 500;

 

   private int x1 = (CANVAS_WIDTH / 2) -25;
   private int y1 = (CANVAS_HEIGHT / 2)-25;
   private int x2 = x1;
   private int y2 = y1;

   private DrawCanvas canvas;// The custom drawing canvas (an innder class extends JPanel)
     int latime = 500, inaltime = 500;
    Minge m;
    Graphics g;
    GenerareMinge mg;
   // Constructor to set up the GUI components and event handlers
   public CGMoveALine() {
       
     
      
   
       
      // Set up a panel for the buttons
     JPanel btnPanel = new JPanel(new FlowLayout());
//     JButton btnLeft = new JButton("Move Left ");
//      btnPanel.add(btnLeft);
//      btnLeft.addActionListener(new ActionListener() {
//         public void actionPerformed(ActionEvent evt) {
//            x1 -= 10;
//            x2 -= 10;
//            canvas.repaint();
//            requestFocus(); // change the focus to JFrame to receive KeyEvent
//         }
//      });
//      JButton btnRight = new JButton("Move Right");
//      btnPanel.add(btnRight);
//      btnRight.addActionListener(new ActionListener() {
//         public void actionPerformed(ActionEvent evt) {
//            x1 += 10;
//            x2 += 10;
//            canvas.repaint();
//            requestFocus(); // change the focus to JFrame to receive KeyEvent
//         }
//      });
 
      // Set up a custom drawing JPanel
      canvas = new DrawCanvas();
      canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
      // Add both panels to this JFrame's content-pane
      Container cp = getContentPane();
      cp.setLayout(new BorderLayout());
      cp.add(canvas, BorderLayout.CENTER);
      cp.add(btnPanel, BorderLayout.SOUTH);
  
      // "super" JFrame fires KeyEvent
      addKeyListener(new KeyAdapter() {
         @Override
         public void keyPressed(KeyEvent evt) {
            switch(evt.getKeyCode()) {
               case KeyEvent.VK_LEFT:
                  x1 -= 10;
                  x2 -= 10;
                  repaint();
                  break;
               case KeyEvent.VK_RIGHT:
                  x1 += 10;
                  x2 += 10;
                  repaint();
                  break;
                  case KeyEvent.VK_DOWN:
                  y1 += 10;
                  y2 += 10;
                  repaint();
                  break;
                  case KeyEvent.VK_UP:
                  y1 -= 10;
                  y2 -= 10;
                  repaint();
                  break;
            }
         }
      });
 
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Handle the CLOSE button
      setTitle("Move a Line");
      pack();           // pack all the components in the JFrame
      setVisible(true); // show it
      requestFocus();   // set the focus to JFrame to receive KeyEvent
   }
 
   /**
    * Define inner class DrawCanvas, which is a JPanel used for custom drawing.
    */
    
       
   
  
   class DrawCanvas extends JPanel {
      @Override
      public void paintComponent(Graphics g) {
         super.paintComponent(g);
         setBackground(Color.WHITE);
         g.setColor(Color.red);
         g.fillOval(x1, y1, 50, 50); // Draw the line
    g = canvas.getGraphics();

        Random rand = new Random();
        
        Color randomColor = new Color(1,1,1);

        int latime = canvas.getWidth(), inaltime = canvas.getHeight();

        mg = new GenerareMinge(inaltime, latime, true, g, randomColor);
        mg.start();

      }
   }
 
   // The entry main() method
   public static void main(String[] args) {
      // Run GUI codes on the Event-Dispatcher Thread for thread safety
      SwingUtilities.invokeLater(new Runnable() {
         @Override
         public void run() {
            new CGMoveALine(); // Let the constructor do the job
         }
      });
   }
}

Мой другой класс с использованием Thread

public class GenerareMinge extends Thread {

    boolean finish;
    int inaltime;
    int latime;
    Graphics g;
    Color color;

    public GenerareMinge(int inaltime, int latime, boolean finish, Graphics g, Color color) {
        this.finish = finish;
        this.latime = latime;
        this.inaltime = inaltime;
        this.g = g;
        this.color = color;
    }

    @Override
    public void run() {

        while (finish) {

            try {
                Random rand = new Random();
                int random=rand.nextInt(4);

               switch(random) {
  case 0:
 color = new Color(255,0,0);
    break;
  case 1:
 color = new Color(255,255,0);
    break;
   case 2:
 color = new Color(0,0,255);
    break;
      case 3:
 color = new Color(0,255,0);
    break;
}
//                color = new Color(random);
//                
                Cerc c = new Cerc(rand.nextInt(inaltime), rand.nextInt(latime), rand.nextInt(90-30)+30, g, color);
                c.deseneaza();

                Minge m = new Minge(c, true);
                m.start();

                sleep(2000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Minge.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

    }
}

Другой класс который сжимает круги

public class Minge extends Thread{
   
    Cerc c;
boolean finish;
    public Minge(Cerc c,boolean finish) {
        this.c = c;
       this.finish=finish;
    }

    @Override
    public void run() {
      
            
               while(finish){
           c.micsoreaza();
        
          
                    try {
                        sleep((int)(50*Math.random()));
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Minge.class.getName()).log(Level.SEVERE, null, ex);
                    }
           
       }
            
        }
    }

И мой круг

public class Cerc {

    public int score = 0;
    int x, y, r;
    Graphics g;
    Color c;

    public Cerc(int x, int y, int r, Graphics g, Color c) {
        this.x = x;
        this.y = y;
        this.r = r;
        this.g = g;
        this.c = c;
    }

    public Cerc(Graphics g) {

    }

    void deseneaza() {
    
        g.drawOval(x - r, y - r, 2 * r, 2 * r);
        g.fillOval(x - r, y - r, 2 * r, 2 * r);
    }

    void afiseaza() {
        g.setColor(c);
        deseneaza();
    }

    void sterge() {
        g.setColor(Color.white);
             g.fillOval(x-r , y-r , 2 * r, 2 * r);
        g.drawOval(x-r , y-r , 2 * r, 2 * r);
   
    }

    void micsoreaza() {
       
        sterge();


        r -= 1;
        
      
     

        afiseaza();
    }

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