java 球_java两个球在框里运动,当两球碰到一起时结束?

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;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值