import java.awt.*; import java.applet.*; public class Maze extends Applet { int maze[][]; public void init() { int x, y, n, d, dx[]={0,0,-1,1}, dy[]={-1,1,0,0}; int todo[]=new int[400], todonum=0; /* We want to create a maze on a grid. */ maze=new int[20][20]; /* We start with a grid full of walls. */ for(x=0;x<20;++x) for(y=0;y<20;++y) maze[x][y]=x==0||x==19||y==0||y==19?32:63; /* Select any square of the grid, to start with. */ x=(int)(1+Math.random()*18); y=(int)(1+Math.random()*18); /* Mark this square as connected to the maze. */ maze[x][y]&=~48; /* Remember the surrounding squares, as we will */ for(d=0;d<4;++d) if((maze[x+dx[d]][y+dy[d]]&16)!=0) { /* want to connect them to the maze. */ todo[todonum++]=((x+dx[d])<<16)|(y+dy[d]); maze[x+dx[d]][y+dy[d]]&=~16; } /* We won't be finished until all is connected. */ while(todonum>0) { /* We select one of the squares next to the maze. */ n=(int)(Math.random()*todonum); x=todo[n]>>16; y=todo[n]&65535; /* We will connect it, so remove it from the queue. */ todo[n]=todo[--todonum]; /* Select a direction, which leads to the maze. */ do d=(int)(Math.random()*4); while((maze[x+dx[d]][y+dy[d]]&32)!=0); /* Connect this square to the maze. */ maze[x][y]&=~((1<<d)|32); maze[x+dx[d]][y+dy[d]]&=~(1<<(d^1)); /* Remember the surrounding squares, which aren't */ for(d=0;d<4;++d) if((maze[x+dx[d]][y+dy[d]]&16)!=0) { /* connected to the maze, and aren't yet queued to be.*/ todo[todonum++]=((x+dx[d])<<16)|(y+dy[d]); maze[x+dx[d]][y+dy[d]]&=~16; } /* Repeat until finished. */ } /* One may want to add an entrance and exit. */ maze[1][1]&=~1; maze[18][18]&=~2; } public void paint(Graphics g) { int x, y; for(x=1;x<19;++x) for(y=1;y<19;++y) { if((maze[x][y]&1)!=0) g.drawLine(x*10 , y*10 , x*10+10, y*10 ); if((maze[x][y]&2)!=0) g.drawLine(x*10 , y*10+10, x*10+10, y*10+10); if((maze[x][y]&4)!=0) g.drawLine(x*10 , y*10 , x*10 , y*10+10); if((maze[x][y]&8)!=0) g.drawLine(x*10+10, y*10 , x*10+10, y*10+10); } } }
Image links
There are no pages that link to this image.
Search Encyclopedia
|
Featured Article
|