弹珠游戏

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(30);
}
catch(InterruptedException e)
{
System.err.println("Thread iterrupted");
}
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("start");
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 arg0) {
// TODO Auto-generated method stub
for(int i=0;i<marbles.length;i++)
{
int xdir=i*(1-i*(int)Math.round(Math.random()))+v;
int ydir=i*(1-i*(int)Math.round(Math.random()))+v;
int x=(int)(getSize().width*Math.random());
int y=(int)(getSize().width*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 Main {
public static void main(String args[])
{
Table table=new Table();
}
}

原文地址:https://www.cnblogs.com/pengpenggege/p/8675276.html