import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Main extends JFrame {
public static void main(String[] args) {
new Main();
}
private List list;
private boolean crash;
public Main() {
this.setSize(800, 600);
this.setResizable(false);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
initCircleList();
this.setVisible(true);
initRepaintThread();
}
private void initCircleList() {
list = new ArrayList<>();
Random random = new Random();
for (int i = 0; i < 4; i++) {
int x = random.nextInt(getWidth() - 200) + 100;
int y = random.nextInt(getHeight() - 200) + 100;
int r = random.nextInt(10) + 10;
Circle c = new Circle(x, y, r);
c.dx = random.nextInt(5) - 2;
c.dy = random.nextInt(5) - 2;
list.add(c);
}
}
public void paint(Graphics g) {
if (!crash) {
Image buffer = createImage(getWidth(), getHeight());
Graphics graphics = buffer.getGraphics();
paintBuffer(graphics);
graphics.dispose();
g.drawImage(buffer, 0, 0, null);
}
}
private void paintBuffer(Graphics g) {
for (Circle c : list) {
g.fillOval(c.x - c.r, c.y - c.r, c.r * 2, c.r * 2);
}
for (int i = 0; i < list.size(); i++) {
for (int j = i + 1; j < list.size(); j++) {
if (list.get(i).checkCrash(list.get(j))) {
crash = true;
}
}
}
for (Circle c : list) {
c.move();
c.checkRange(getWidth(), getHeight());
}
}
private void initRepaintThread() {
Thread thread = new Thread(new Runnable() {
public void run() {
while (!crash) {
sleep(10);
repaint();
}
}
private void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.setDaemon(true);
thread.start();
}
public static class Circle {
public int x;
public int y;
public int r;
public int dx;
public int dy;
public Circle(int x, int y, int r) {
this.x = x;
this.y = y;
this.r = r;
}
public void move() {
x += dx;
y += dy;
}
public void checkRange(int witdh, int height) {
if (x - r < 0) {
x = r * 2 - x;
dx = -dx;
} else if (x + r >= witdh) {
x = witdh * 2 - r * 2 - x;
dx = -dx;
}
if (y - r < 0) {
y = r * 2 - y;
dy = -dy;
} else if (y + r >= height) {
y = height * 2 - r * 2 - y;
dy = -dy;
}
}
public boolean checkCrash(Circle c) {
int mx = Math.abs(c.x - x);
int my = Math.abs(c.y - y);
int mr = c.r + r;
return mx * mx + my * my < mr * mr;
}
}
}