1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
| import javax.swing.*;
public class OsmosGame {
public static void main(String[] args) {
JFrame frame = new JFrame("Osmos");
GamePanel panel = new GamePanel();
frame.setContentPane(panel);
frame.setSize(1600, 1000);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class GamePanel extends JPanel implements ActionListener, MouseListener {
private boolean initialized = false;
private final Timer timer;
private List<Particle> particles = new CopyOnWriteArrayList<>();
private final Player player;
public GamePanel() {
this.setBackground(Color.BLACK);
this.setFocusable(true);
this.addMouseListener(this);
player = new Player(400, 300, 30);
particles = new ArrayList<>();
timer = new Timer(16, this); // ~60 FPS
timer.start();
this.setFocusable(true);
this.requestFocusInWindow(); // заставляем получить фокус
SwingUtilities.invokeLater(() -> requestFocusInWindow());
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (!initialized && getWidth() > 0 && getHeight() > 0) {
for (int i = 0; i < 20; i++) {
particles.add(Particle.randomParticle(getWidth(), getHeight()));
}
initialized = true;
}
player.draw(g);
for (Particle p : particles) {
p.draw(g);
}
}
@Override
public void actionPerformed(ActionEvent e) {
// double gravityStrength = 0.015; // сила гравитации, поэкспериментируй
double gravityStrength = 0.000001 * player.getMass(); // масштабируем силу гравитации от массы
// player.move();
player.moveWithinBounds(getWidth(), getHeight());
for (Particle p : particles) {
// p.move();
// Притягиваются к игроку, если это не выброшенная масса
if (!(p instanceof EjectedParticle)) {
p.applyGravityFrom(player, gravityStrength);
}
p.moveWithinBounds(getWidth(), getHeight());
}
// Удаляем исчезнувшие выбросы массы
particles.removeIf(p -> (p instanceof EjectedParticle) && ((EjectedParticle) p).isDead());
// Проверка столкновений
Iterator<Particle> iter = particles.iterator();
while (iter.hasNext()) {
Particle p = iter.next();
if (player.checkCollision(p)) {
if (player.radius >= p.radius) {
player.absorb(p);
iter.remove();
} else {
// Игрок проиграл
timer.stop();
JOptionPane.showMessageDialog(this, "Game Over!");
System.exit(0);
}
}
}
repaint();
// Проверка, остались ли обычные частицы (кроме выброшенной массы)
boolean noRealParticles = particles.stream()
.noneMatch(p -> !(p instanceof EjectedParticle));
if (noRealParticles) {
// Сброс игрока
player.radius = 30;
player.vx = 0;
player.vy = 0;
// Очистка частиц
particles.clear();
// Генерация новых частиц
for (int i = 0; i < 30; i++) {
particles.add(Particle.randomParticle(getWidth(), getHeight(), player.x, player.y, player.radius * 2));
}
// Можно показать сообщение
JOptionPane.showMessageDialog(this, "Новый раунд!");
}
}
@Override
public void mouseClicked(MouseEvent e) {
double dx = player.x - e.getX();
double dy = player.y - e.getY();
double len = Math.sqrt(dx * dx + dy * dy);
player.vx += dx / len * 1.5;
player.vy += dy / len * 1.5;
player.radius -= 1.0; // потери массы
if (len > 1e-6 && player.radius > 5) {
dx /= len;
dy /= len;
double ejectSpeed = 3;
double impulse = 1.5;
double ejectRadius = 4;
// Реактивный импульс
player.vx += dx * impulse;
player.vy += dy * impulse;
player.radius -= 0.5;
// Выброшенная частица
EjectedParticle ep = new EjectedParticle(
player.x - dx * (player.radius + ejectRadius), // позади
player.y - dy * (player.radius + ejectRadius),
ejectRadius,
-dx * ejectSpeed,
-dy * ejectSpeed
);
particles.add(ep);
}
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
}
import java.awt.*;
import java.util.Random;
public class Particle {
public static Particle randomParticle(int width, int height, double avoidX, double avoidY, double minDistance) {
Random r = new Random();
double x, y;
do {
x = r.nextInt(Math.max(1, width));
y = r.nextInt(Math.max(1, height));
} while (Math.hypot(x - avoidX, y - avoidY) < minDistance); // избегаем слишком близкого появления
double radius = 5 + r.nextDouble() * 20;
return new Particle(x, y, radius, Color.GRAY);
}
protected double x, y, vx, vy, radius;
protected Color color;
public Particle(double x, double y, double radius, Color color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
Random r = new Random();
this.vx = r.nextDouble() * 2 - 1;
this.vy = r.nextDouble() * 2 - 1;
}
public static Particle randomParticle(int width, int height) {
Random r = new Random();
double x = r.nextInt(width);
double y = r.nextInt(height);
double radius = 5 + r.nextDouble() * 20;
return new Particle(x, y, radius, Color.GRAY);
}
public void move() {
x += vx;
y += vy;
}
public void draw(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
// g2d.setColor(color);
// g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, color.getAlpha() / 255f));
// g2d.fillOval((int) (x - radius), (int) (y - radius), (int) (2 * radius), (int) (2 * radius));
// g2d.dispose();
int size = (int) (2 * radius);
int drawX = (int) (x - radius);
int drawY = (int) (y - radius);
// Создаём градиент: светлый в центре, тёмный по краям
Color centerColor = new Color(color.getRed(), color.getGreen(), color.getBlue(), 200);
Color edgeColor = new Color(0, 0, 0, 100);
Color color = new Color(100, 200, 255, 180); // с прозрачностью
RadialGradientPaint gradient = new RadialGradientPaint(
new Point(drawX + size / 2, drawY + size / 2),
(float) radius,
new float[]{0f, 1f},
new Color[]{centerColor, edgeColor}
);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, color.getAlpha() / 255f));
// Мягкая оболочка ****** можно убрать
g2d.setColor(new Color(color.getRed(), color.getGreen(), color.getBlue(), 60));
for (int i = 0; i < 3; i++) {
int glowSize = size + i * 6;
g2d.fillOval(drawX - i * 3, drawY - i * 3, glowSize, glowSize);
}
//****
// Выбрасываемые частицы пульсирующие *** можно убрать
if (this instanceof EjectedParticle) {
radius += Math.sin(System.nanoTime() * 1e-9 * 5) * 0.3;
} // *************
g2d.setPaint(gradient);
g2d.fillOval(drawX, drawY, size, size);
g2d.dispose();
}
public boolean intersects(Particle other) {
double dx = this.x - other.x;
double dy = this.y - other.y;
double dist = Math.sqrt(dx * dx + dy * dy);
return dist < (this.radius + other.radius);
}
public void applyGravityFrom(Particle other, double G) {
if (this == other) {
return;
}
double dx = other.x - this.x;
double dy = other.y - this.y;
double distSq = dx * dx + dy * dy;
if (distSq < 1) {
return;
}
double force = G * other.getMass() / distSq;
double dist = Math.sqrt(distSq);
double ax = force * dx / dist;
double ay = force * dy / dist;
this.vx += ax;
this.vy += ay;
}
public void moveWithinBounds(int width, int height) {
x += vx;
y += vy;
double r = radius;
if (x - r < 0) {
x = r;
vx = -vx;
}
if (x + r > width) {
x = width - r;
vx = -vx;
}
if (y - r < 0) {
y = r;
vy = -vy;
}
if (y + r > height) {
y = height - r;
vy = -vy;
}
}
public double getMass() {
return Math.PI * radius * radius;
}
}
import java.awt.*;
public class Player extends Particle {
public Player(double x, double y, double radius) {
super(x, y, radius, Color.CYAN);
this.vx = 0;
this.vy = 0;
}
public void absorb(Particle other) {
// Увеличиваем радиус в зависимости от площади
double areaSelf = Math.PI * radius * radius;
double areaOther = Math.PI * other.radius * other.radius;
radius = Math.sqrt((areaSelf + areaOther) / Math.PI);
}
public void moveWithinBounds(int width, int height) {
x += vx;
y += vy;
double r = radius;
// Отражение от краёв
if (x - r < 0) {
x = r;
vx = -vx;
}
if (x + r > width) {
x = width - r;
vx = -vx;
}
if (y - r < 0) {
y = r;
vy = -vy;
}
if (y + r > height) {
y = height - r;
vy = -vy;
}
// Замедление
vx *= 0.99;
vy *= 0.99;
}
public boolean checkCollision(Particle p) {
return this.intersects(p);
}
}
import java.awt.*;
public class EjectedParticle extends Particle {
private int life = 255; // начальная прозрачность
public EjectedParticle(double x, double y, double radius, double vx, double vy) {
super(x, y, radius, new Color(100, 200, 255, 255));
this.vx = vx;
this.vy = vy;
}
@Override
public void moveWithinBounds(int width, int height) {
super.moveWithinBounds(width, height);
// Плавное исчезновение
life -= 2;
if (life < 0) {
life = 0;
}
color = new Color(100, 200, 255, life);
}
public boolean isDead() {
return life <= 0 || radius < 1;
}
} |