import java.awt.*;
import java.awt.event.*;
public class AlgoVisualizer {
private Object data;
private Circle[] circles;
private AlgoFrame frame;
private boolean isAnmiated = true;
public AlgoVisualizer(int sceneWidth, int sceneHeight, int N){
circles = new Circle[N];
int R = 50;
for(int i = 0; i < N; i++)
{
int x = (int)(Math.random()*(sceneWidth-2*R)) + R;
int y = (int)(Math.random()*(sceneHeight-2*R)) + R;
int vx = (int)(Math.random()*11) - 5;
int vy = (int)(Math.random()*11) - 5;
circles[i] = new Circle(x, y, R, vx, vy);
}
EventQueue.invokeLater(()->{
frame = new AlgoFrame("Welcome-Java", sceneWidth, sceneHeight);
frame.addKeyListener(new AlgoKeyListener());
frame.addMouseListener(new AlgoMouseListener());
new Thread(()->{run();}).start();
});
}
public AlgoVisualizer(int sceneWidth, int sceneHeight, int N, String centerLael){
Circle.showLabel = true;
circles = new Circle[N];
int R = 50;
for(int i = 0; i < N; i++)
{
int x = (int)(Math.random()*(sceneWidth-2*R)) + R;
int y = (int)(Math.random()*(sceneHeight-2*R)) + R;
int vx = (int)(Math.random()*11) - 5;
int vy = (int)(Math.random()*11) - 5;
circles[i] = new Circle(x, y, R, vx, vy);
circles[i] = new Circle(x, y, R, vx, vy, centerLael.charAt(i) + "");
}
EventQueue.invokeLater(()->{
frame = new AlgoFrame("Welcome-Java", sceneWidth, sceneHeight);
frame.addKeyListener(new AlgoKeyListener());
frame.addMouseListener(new AlgoMouseListener());
new Thread(()->{
run();
}).start();
});
}
private void run(){
while(true)
{
//绘制当前数据
frame.render(circles);
AlgoVisHelper.pause(20);
//更新数据
if(isAnmiated)
{
for(Circle circle:circles)
circle.move(0, 0, frame.getCanvasWidth(), frame.getCanvasHeight());
}
}
}
private class AlgoKeyListener extends KeyAdapter {
@Override
public void keyReleased(KeyEvent event)
{
if(event.getKeyChar() == ' ')
{
isAnmiated = !isAnmiated;
}
}
}
private class AlgoMouseListener extends MouseAdapter{
@Override
public void mousePressed (MouseEvent event)
{
event.translatePoint(0,
// (frame.getBounds().height -frame.getCanvasHeight()));
-(frame.getBounds().height -frame.getCanvasHeight()));
// System.out.println(event.getPoint());
for(Circle circle:circles)
{
if(circle.contain(event.getPoint())){
circle.isFilled = !circle.isFilled;
}
}
}
}
public static void main(String[] args) {
String poemData = "三月七日沙湖道中遇雨。雨具先去,同行皆狼狈,余独不觉。已而遂晴,故作此词 \n" +
"莫听穿林打叶声,何妨吟啸且徐行。竹杖芒鞋轻胜马,谁怕? 一蓑烟雨任平生。\n" +
"料峭春风吹酒醒,微冷,山头斜照却相迎。回首向来萧瑟处,归去,也无风雨也无晴。";
int sceneWidth = 800;
int sceneHeight = 800;
int N = 15;
// AlgoVisualizer visualizer = new AlgoVisualizer(sceneWidth, sceneHeight, N);
AlgoVisualizer visualizer = new AlgoVisualizer(sceneWidth, sceneHeight, N, poemData);
}
}
|