欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java迷宫生成

程序员文章站 2022-06-19 19:24:14
...

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&&currentPoint.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);
 }
 
}