小弹子碰撞程序


import java.awt.*;
import java.awt.event.*;
/*定义弹子类*/
class Marble extends Thread{
	Table table = null;
	int x,y,xdir,ydir;
	public Marble(Table _table,int _x,int _y,int _xdir,int _ydir){
		table = _table;
		x=_x;
		y=_y;
		xdir=_xdir;
		ydir=_ydir;
	}
	public void run(){
		while(true){
			if((x>(table.getSize().width)-25)||(x<0))
				xdir*=-1;
			if(y>(table.getSize().width)-25||(y<0))
				ydir*=-1;
			x+=xdir;
			y+=ydir;
			try{
				sleep(100);
			}catch(InterruptedException e){
				System.err.println("Thread interrupted");
			}
			table.repaint();//重绘图形
		}	
	}
	public void draw(Graphics g){
		g.setColor(Color.black);
		g.fillOval(x, y, 30, 30);
		g.setColor(Color.white);
		g.fillOval(x+5, y+5, 8, 6);
	}
}

/*定义台球桌类*/
class Table extends Frame implements ActionListener{
	Button start=new Button("开始");
	Marble marbles[]=new Marble[5];//建立弹子线程类对象数组
	int v=2;//设置速度最小值
	public Table(){
		super("弹子台球");
		setSize(300,300);
		setBackground(Color.cyan);
		setVisible(true);
		setLayout(new FlowLayout());
		add(start);
		start.addActionListener(this);
		validate();
		addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent e){
				System.exit(0);
			}
		});
	}
	public void actionPerformed(ActionEvent ae){
		for(int i=0;i<marbles.length;i++){
			int xdir=i*(i-i*(int)Math.round(Math.random()))+v;
			int ydir=i*(i-i*(int)Math.round(Math.random()))+v;
			System.out.println(xdir);
			System.out.println(ydir);
			int x=(int)(getSize().width*Math.random());
			int y=(int)(getSize().height*Math.random());
			//上面随产生弹子的速度和初始坐标位置
			marbles[i]=new Marble(this,x,y,xdir,ydir);
			marbles[i].start();
		}
	}
	public void paint(Graphics g){
		for(int i=0;i<marbles.length;i++){
			if(marbles[i]!=null)
				marbles[i].draw(g);
		}
	}
}

public class Ex {
	public static void main(String[] args){
		Table table=new Table();
	}
}


此程序只考虑了各个弹子与墙壁碰撞后改变方向,而没有考虑弹子之间的碰撞。各个弹子都是一个独立的线程,而没有编写线程通信方面的程序。下一阶段是做线程通信方面的工作。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值