达内跑泡泡项目,eating函数不调用为什么呀??
package ball;
import java.awt.Color;
import java.awt.Graphics2D;
public class Ball {
double x;
double y ;
int d;
int r;
int g;
int b;
Color color;
double offsetX;
double offsetY;
public Ball() {
d = (int)(Math.random()*(35-2)+2);
x = Math.random()*(800-d);
y = Math.random()*(600-d);
r = (int)(Math.random()*256);
g = (int)(Math.random()*256);
b = (int)(Math.random()*256);
color = new Color(r,g,b);
offsetX = Math.random()*(12-1)*1;
offsetY = Math.random()*(12-1)*1;
offsetX = Math.random()>0.5 ? offsetX : -offsetX;
offsetY = Math.random()>0.5 ? offsetY : -offsetY;
}
public void move() {
x += offsetX;
y += offsetY;
if(x > 800-d) {
offsetX = -offsetX;
x = 800-d;
}else if(y > 600-d){
offsetY = -offsetY;
y = 600-d;
}else if (x < 0) {
offsetX = -offsetX;
x = 0;
}else if (y < 0) {
offsetY = -offsetY;
y = 0;
}
}
public boolean eat(Ball ball) {
double X = x, Y = y, D = d;
double x = ball.x, y = ball.y, d = ball.d;
if(d>D) {
return false;
}
double a = (x + d / 2) - (X + D / 2);
double b = (x + D / 2) - (X + d / 2);
double c = Math.sqrt(a * a + b * b);
boolean eaten = c < (D / 2 - d / 2);
if(eaten) {
double R = D/2, r = d/2;
double area = Math.PI * R * R +Math.PI * r * r;
R = Math.sqrt(area/Math.PI);
this.d = (int)(R * 2);
}
return eaten;
}
public void paint(Graphics2D g) {
g.setColor(color);
g.fillOval((int)x,(int)y,d,d);
}
}
package ball;
import java.awt.Graphics2D;
import java.util.Arrays;
import cn.tedu.util.App;
public class BallApp extends App{
Ball[] balls = new Ball[100];
public BallApp() {
for(int i = 0;i < balls.length;i++) {
balls[i] = new Ball();
}
}
public void painting(Graphics2D g) {
for (int i = 0;i<balls.length;i++) {
balls[i].move();
balls[i].paint(g);
}
eating();
}
public void eating() {
Ball[] big = balls;
Ball[] small = balls;
boolean[] eaten = new boolean[small.length];//默认为false。
int n = 0;//记录有没有球被吃掉
for(int i = 0; i<big.length;i++) {//每一个大球
//如果大球已经被吃掉
if(eaten[i]) {
continue;
}
for(int j = 0;j<small.length;j++) {
//自己不能吃自己
if(i==j) {
continue;
}
//如果小球已经被吃掉
if(eaten[j]) {
continue;
}
if(big[i].eat(small[j])) {
//把小球位置设置为true
eaten[j] = true;
n++;
}
}
}
if(n==0) {
return;
}
//缩容处理
Ball[] arr = new Ball[small.length];
int index = 0;
for(int i=0;i<small.length;i++) {
if(!eaten[i]) {
arr[index++] = small[i];
}
}
balls = Arrays.copyOf(arr, arr.length-n);
}
public static void main(String[] args) {
BallApp app = new BallApp();
app.start();
}
}