📄 firetree.java
字号:
// 程序:烟火树粒子
// 范例文件:FireTree.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class FireTree extends Applet implements Runnable
{
final int Max = 1000;
ftparticle p[]; // 烟火树粒子
int AppletWidth,AppletHeight,XCenter,YCenter;
Image OffScreen;
Graphics drawOffScreen;
Thread pThread;
public void init()
{
setBackground(Color.black); // 设定背景为黑色
p = new ftparticle[Max]; // 建立粒子
// 取得显像区域
AppletWidth = getSize().width;
AppletHeight = getSize().height;
// 烟火初始位置
XCenter = AppletWidth/2;
YCenter = 2*AppletHeight/3;
// 产生并初始化粒子
for(int i=0; i<Max; i++)
p[i] = new ftparticle(XCenter,YCenter);
// 建立次画面
OffScreen = createImage(AppletWidth,AppletHeight);
drawOffScreen = OffScreen.getGraphics();
}
public void start()
{
pThread = new Thread(this);
pThread.start();
}
public void stop()
{
pThread = null;
}
public void update(Graphics g)
{
paint(g);
}
public void paint(Graphics g)
{
g.drawImage(OffScreen,0,0,this);
}
public void run()
{
int i;
while(true)
{
// 重清画面
drawOffScreen.clearRect(0,0,AppletWidth,AppletHeight);
drawOffScreen.setColor(Color.white);
drawOffScreen.fillRect(XCenter,YCenter,5,AppletHeight/3);
for(i=0; i<Max; i++)
{
// 如果超出显像区域,重设粒子
if(p[i].Y > AppletHeight)
p[i].reset(XCenter,YCenter);
// 绘制粒子
drawOffScreen.setColor(p[i].color);
drawOffScreen.fillOval((int)p[i].X,(int)p[i].Y,3,3);
// 粒子水平移动
p[i].X += p[i].Vx;
// 粒子受重力影响
p[i].Y += p[i].Vy;
// 粒子垂直速度受重力影响
p[i].Vy += 9.8*p[i].time/5;
p[i].time++;
}
// 重绘画面
repaint();
// 暂停线程200 毫秒
try {
Thread.sleep(200);
}
catch (InterruptedException e) { }
}
}
}
// 烟火树粒子类
class ftparticle
{
double X,Y; // 粒子的位置
double Vx,Vy; // 粒子水平与垂直速度
int time;
Color color; // 粒子颜色
// 建构子,初始粒子
public ftparticle(int x,int y)
{
X = x;
Y = y;
reset(x,y);
}
// 重设粒子状态
public void reset(int x, int y)
{
X = x;
Y = y;
// 使用随机数决定水平与垂直速度
Vx = (int)(Math.random()*10 - Math.random()*10);
Vy = (int)(-Math.random()*20 - 1);
time = 0;
// 使用随机数决定粒子颜色
color = new Color((int)(Math.random()*255),
(int) (Math.random()*255),
(int) (Math.random()*255));
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -