两球相撞程序如下:
public class Draw {
public static void main(String[] args){
JFrame frame=new JFrame();
frame.setSize(1024,768);
Color bgColor=Color.BLACK;
frame.setBackground(bgColor);
Ball w=new Ball();
frame.add(w);
frame.getContentPane().setBackground(Color.white);
Thread t=new Thread(w);
t.start();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}
class Ball extends Panel implements Runnable{
int y1=0,x1=0,y2=((int)(Math.random()*500))+200,x2=((int)(Math.random()*800))+200;
int i=10,j=110,z=10,i2=0,j2=100,z2=0;
int X1_juge=1,Y1_juge=1,X1_temp=1,Y1_temp=1;
int X2_juge=1,Y2_juge=1,X2_temp=1,Y2_temp=1;
//X_juge判断小球水平方向是否撞墙,Y_juge判断竖直方向是否撞墙,temp判 断juge是否变化
Color colo=new Color(i, j, z);
Color colo2=new Color(i2,j2,z2);
public void paint(Graphics g){
if(X1_temp!=X1_juge) //当小球水平撞墙后给该小球随机取颜色,并将temp=juge
{
i=(int)(Math.random()*100);
j=(int)(Math.random()*100);
z=(int)(Math.random()*100);
X1_temp=X1_juge;
}
if(Y1_temp==Y1_juge) ;
else
{
i=(int)(Math.random()*100);
j=(int)(Math.random()*100);
z=(int)(Math.random()*100);
Y1_temp=Y1_juge;
}
colo=new Color(i,j,z);
g.setColor(colo);
//g.setFont(new Font("",0,30));
g.fillOval(x1, y1, 20, 20);
if(!(X2_temp==X2_juge))
{
i2=(int)(Math.random()*100);
j2=(int)(Math.random()*100);
z2=(int)(Math.random()*100);
X2_temp=X2_juge;
}
if(Y2_temp==Y2_juge) ;
else
{i2=(int)(Math.random()*100);
j2=(int)(Math.random()*100);
z2=(int)(Math.random()*100);
Y2_temp=Y2_juge;
}
colo2=new Color(i2,j2,z2);
g.setColor(colo2);
g.fillOval(x2, y2, 20, 20);
}
public void run()
{
while(true)
{
if(X1_juge==1&&Y1_juge==1){
y1++;
x1++;
if(x1>1000) X1_juge=0; //当小球撞墙时juge变化
if(y1>720) Y1_juge=0;
try{
Thread.sleep(5);
}catch(Exception ex){}
repaint();
}
else if(X1_juge!=1&&Y1_juge==1)
{
y1++;x1--;
if(x1<10) X1_juge=1;
if(y1>720) Y1_juge=0;
try{
Thread.sleep(5);
}catch(Exception ex){}
repaint();
}
else if(X1_juge==1&&Y1_juge!=1){
x1++;
y1--;
if(x1>1000) X1_juge=0;
if(y1<10) Y1_juge=1;
try{
Thread.sleep(5);
}catch(Exception ex){}
repaint();
}
else{
x1--;
y1--;
if(x1<10) X1_juge=1;
if(y1<10) Y1_juge=1;
try{
Thread.sleep(5);
}catch(Exception ex){}
repaint();
}
if(Math.abs(x1-x2)<=20&&Math.abs(y1-y2)<=20){
//当两小球球心间距小于等于20时判定相撞
if(X1_juge==0) X1_juge=1;
else X1_juge=0;
if(Y1_juge==0) Y1_juge=1;
else Y1_juge=0;
if(X2_juge==0) X2_juge=1;
else X2_juge=0;
if(Y2_juge==0) Y2_juge=1;
else Y2_juge=0;
try{
Thread.sleep(5);
}catch(Exception ex){}
repaint();
}
if(X2_juge==1&&Y2_juge==1){
y2--;
x2--;
if(x2<10) X2_juge=0;
if(y2<10) Y2_juge=0;
try{
Thread.sleep(5);
}catch(Exception ex){}
repaint();
}
else if(X2_juge!=1&&Y2_juge==1)
{
y2--;x2++;
if(x2>1000) X2_juge=1;
if(y2<10) Y2_juge=0;
try{
Thread.sleep(5);
}catch(Exception ex){}
repaint();
}
else if(X2_juge==1&&Y2_juge!=1){
x2--;
y2++;
if(x2<10) X2_juge=0;
if(y2>720) Y2_juge=1;
try{
Thread.sleep(5);
}catch(Exception ex){}
repaint();
}
else{
x2++;
y2++;
if(x2>1000) X2_juge=1;
if(y2>720) Y2_juge=1;
try{
Thread.sleep(5);
}catch(Exception ex){}
repaint();}}}}
网友评论