java迷宫生成
public class DeepPri extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
private int gap=100;
private int width=25;
public DeepPri(){
getContentPane().setBackground(Color.gray);
setVisible(true);
setSize(800,800);
setResizable(false);
setCenter();
}
public void setCenter(){
Toolkit kit=Toolkit.getDefaultToolkit();
Dimension d=kit.getScreenSize();
int wid=(int) d.getWidth();
int hei=(int) d.getHeight();
this.setLocation((wid-getWidth())/2, (hei-getHeight())/2);
}
@Override
public void paint(Graphics g){
super.paint(g);
int w=getWidth();
int length=w-2*gap;
for(int i=0;i<length/width+1;i++){
g.setColor(Color.green);
g.drawLine(gap+i*width, gap, gap+i*width, gap+length);
g.drawLine(gap, gap+i*width, gap+length, gap+i*width);
}
generateMaze();
}
public void generateMaze(){
Point currentPoint=new Point(gap,gap);
Stack<Point> route=new Stack<Point>();
List<Point> havePassed=new ArrayList<Point>();
route.add(currentPoint);
havePassed.add(currentPoint);
Color color=getContentPane().getBackground();
Graphics g=getGraphics();
g.setColor(color);
int w=getWidth();
g.drawLine(gap, gap, gap, gap+width);
g.drawLine(w-gap, w-gap, w-gap, w-gap-width);
//look for next point
while(true){
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
int x=(int)currentPoint.getX();
int y=(int)currentPoint.getY();
int endX=getWidth()-gap;
int endY=getHeight()-gap;
List<Integer> list=new ArrayList<Integer>();
if(x+width<endX&&!havePassed.contains(new Point(x+width,y)))
list.add(1);
if(y+width<endY&&!havePassed.contains(new Point(x,y+width)))
list.add(2);
if(x-width>=gap&&!havePassed.contains(new Point(x-width,y)))
list.add(3);
if(y-width>=gap&&!havePassed.contains(new Point(x,y-width)))
list.add(4);
if(list.size()==0){
currentPoint =route.pop();
if(currentPoint.getX()==gap&¤tPoint.getY()==gap){
System.out.println("get out");
break;
}
continue;
}
int s = list.get(new Random().nextInt(list.size()));
switch(s){
case 1:g.drawLine(x+width, y+1, x+width, y+width-1);currentPoint=new Point(x+width,y);break;
case 2:g.drawLine(x+1, width+y, x+width-1, y+width);currentPoint=new Point(x,y+width);break;
case 3:g.drawLine(x,y+1,x,y+width-1);currentPoint=new Point(x-width,y);break;
case 4:g.drawLine(x+1, y, x+width-1, y);currentPoint=new Point(x,y-width);break;
default: break;
}
havePassed.add(currentPoint);
route.add(currentPoint);
}
}
/* public void crossMaze(){
Point p=new Point(gap,gap);
Graphics g=getGraphics();
}*/
public static void main(String[] args) {
DeepPri dp=new DeepPri();
dp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
上一篇: 怎么吃燕窝效果最好?
下一篇: 鸡毛菜带给人体的功效有哪些