import javax.swing.*;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
public class Main {
public static void main(String[] args) {
JFrame window = new JFrame();
window.setBounds(300, 300, 600, 600);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MySuperGame mySuperGame = new MySuperGame();
window.setContentPane(mySuperGame);
window.setVisible(true);
}
}
class MySuperGame extends JPanel {
Timer timer;
static long prevTimestamp = 0;
static long duration = 0;
ArrayList<Circle> circles = new ArrayList<>(Arrays.asList(
new Circle(100, 100, 50),
new Circle(0, 0, 100),
new Circle(400, 100, 90)
));
public MySuperGame() {
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
ArrayList<Circle> deletingCircle = new ArrayList<>();
for (Circle circle : circles){
if (circle.isIntersect(e.getX(), e.getY())){
circle.color = new Color(0, 255, 0);
deletingCircle.add(circle);
}
}
for (Circle circle : deletingCircle) {
circles.remove(circle);
}
}
});
Random random = new Random();
timer = new Timer(10, e -> {
long delta = e.getWhen() - prevTimestamp;
duration += delta;
if (duration >= 1_000){
int x = random.nextInt(0, 600);
int y = random.nextInt(0, 600);
int r = random.nextInt(30, 100);
circles.add(new Circle(x, y, r, randomColor()));
duration = 0;
}
repaint();
prevTimestamp = e.getWhen();
});
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Circle circle : circles){
circle.draw(g);
}
}
Color randomColor() {
Random random = new Random();
return new Color(random.nextInt(0, 255), random.nextInt(0, 255), random.nextInt(0, 255));
}
}
class Circle {
int x, y, r;
Color color;
public Circle(int x, int y, int r) {
this(x, y, r, new Color(255, 0, 0));
}
public Circle(int x, int y, int r, Color color) {
this.x = x;
this.y = y;
this.r = r;
this.color = color;
}
public boolean isIntersect(Circle circle) {
int distX = circle.x - this.x;
int distY = circle.y - this.y;
return circle.r + this.r < Math.sqrt(distX * distX + distY * distY);
}
public boolean isIntersect(int pointX, int pointY) {
int distX = pointX - this.x;
int distY = pointY - this.y;
return Math.sqrt(distX * distX + distY * distY) <= r;
}
public void draw(Graphics g) {
g.setColor(new Color(0, 0, 0));
g.fillOval(x - r, y - r, r * 2, r * 2);
g.setColor(color);
g.fillOval(x - r + 3, y - r + 3, r * 2 - 6, r * 2 - 6);
}
}