📄 automaze.java
字号:
// 程序:自动产生迷宫
// 范例文件:AutoMaze.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class AutoMaze extends Applet
{
int GridX=15,GridY=15;
int Si,Sj,Ei,Ej;
int[][] maze = new int[30][30];
int enter=20,width=20;
Button btn;
Panel p;
Image wall1, wall2;
MediaTracker MT;
public void init()
{
MT = new MediaTracker(this);
wall1 = getImage(getDocumentBase(),"Images/wall1.gif");
wall2 = getImage(getDocumentBase(),"Images/wall2.gif");
MT.addImage(wall1,0);
MT.addImage(wall2,0);
try
{
showStatus("图像载入中(Loading Images)...");
MT.waitForAll();
}
catch(InterruptedException E){ }
btn = new Button("建立迷宫");
btn.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e)
{
int i,j;
Si=1;Sj=1;Ei=GridY;Ej=GridX;
for (i=0;i<=GridY+1;i++) {
for (j=0;j<=GridX+1;j++) {
if (i==0 || j==0 ||
i==GridY+1 || j==GridX+1)
maze[i][j]=15;
else
maze[i][j]=3;
}
}
genmaze(Ei,Ej);
maze[Ei][Ej]=maze[Ei][Ej] & 0xd;
repaint();
}
}
);
p = new Panel();
p.add(btn);
setLayout(new BorderLayout());
add(p, "South");
}
public void genmaze(int i, int j)
{
int n;
maze[i][j] |= 0x4;
while (maze[i][j+1]==3 || maze[i+1][j]==3 ||
maze[i][j-1]==3 || maze[i-1][j]==3)
{
n=(int)(4*Math.random()+1);
if (n==1 && maze[i][j+1]==3) {
maze[i][j] &= 0xd;
genmaze(i,j+1);
}
else if (n==2 && maze[i-1][j]==3) {
maze[i][j] &= 0xe;
genmaze(i-1,j);
}
else if (n==3 && maze[i][j-1]==3) {
maze[i][j-1] &= 0xd;
genmaze(i,j-1);
}
else if (n==4 && maze[i+1][j]==3) {
maze[i+1][j] &= 0xe;
genmaze(i+1,j);
}
}
}
public void paint(Graphics g)
{
int x, y, i, j;
g.clearRect(0,0,(GridX+3)*width,(GridY+6)*width);
g.drawImage(wall1,enter,enter,(GridX+1)*width,2*width,0,0,100,100,this);
g.drawImage(wall2,0,2*width,width,(GridY+1)*width+5,0,0,100,100,this);
g.drawImage(wall1,enter,(GridY+1)*width,(GridX+1)*width,(GridY+2)*width,0,0,100,100,this);
g.drawImage(wall2,GridX*width,width,(GridX+1)*width,GridY*width,0,0,100,100,this);
for (i=1;i<=GridY;i++) {
for (j=1;j<=GridX;j++) {
x=(j-1)*width+enter;
y=(i-1)*width+enter;
if ((maze[i][j] & 1)==1)
g.drawImage(wall1,x-width/5,y,x+width,y+width,0,0,100,100,this);
if ((maze[i][j] & 2)==2)
g.drawImage(wall2,x,y,x+width,y+width,0,0,100,100,this);
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -