1.项目概述
1.1项目内容与要求
实验内容:
- 迷宫游戏是非常经典的游戏,在该题中要求随机生成一个迷宫,并求解迷宫;
2) 要求查找并理解迷宫生成的算法,并尝试用两种不同的算法来生成随机的迷宫。
3)要求迷宫游戏支持玩家走迷宫,和系统走迷宫路径两种模式。玩家走迷宫,通过键盘方向键控制,并在行走路径上留下痕迹;系统提示迷宫路径要求基于A*算法实现,输出玩家当前位置到迷宫出口的最优路径。设计交互友好的游戏图形界面。
2.项目设计
深度优先遍历(DFS)
(1)访问顶点v;
(2)从v的未被访问的邻接点中选取一个顶点w,重复第一步,如果v没有未访问的邻接点,回溯至上一顶点;
(3)重复上述两步,直至图中所有和v有路径相通的顶点都被访问到。
迷宫生成策略:利用深度遍历的思想。访问到一个节点时,搜索这个节点没有被访问过的相邻节点,选择一个继续做同样的操作,直到没有邻节点为止再回溯到上一个访问的节点,并选择另外的邻节点。
A*算法走迷宫
在计算机科学中,A*算法作为Dijkstra(迪杰斯特拉)算法的扩展,是一种静态路网中求解最短路径有效的直接搜索方法,因其高效性被广泛应用于寻路及图的遍历中。
A*算法流程
重复以下步骤,直到遍历到终点 End:
1、选取当前 open 列表中评价值 F 最小的节点,将这个节点称为 S;
对于与 S 相邻的每一块可移动的相邻节点 T:如果 T 在 closed 列表中,忽略;如果 T 不在 open 列表中,添加它然后计算出它的评价值 F;如果 T 已经在 open 列表中,当我们从 S 到达 T 时,检查是否能得到 更小的 F 值,如果是,更新它的 F 值和它的前继(parent = S)
代码
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Random;
import java.util.Stack;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
// 格子
class Lattice {
static final int InTree = 1;
static final int NotInTree = 0;
private final int x; // 格子的位置,在第几行
private final int y; // 第几列
private int flag = NotInTree; // flag,标识格子是否已加入树中
private Lattice father = null; // 格子的父亲节点
public Lattice(int a, int b) {
x = a;
y = b;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getFlag() {
return flag;
}
public Lattice getFather() {
return father;
}
public void setFather(Lattice dad) {
father = dad;
}
public void setFlag(int f) {
flag = f;
}
public String toString() {
return "(" + x + "," + y + ")\n";
}
}
public class Labyrinth extends JPanel {
private final int num;// num:迷宫大小;
private final int width;//width:每个格子的宽度和高度
private final int padding;
private final Lattice[][] maze;
private int ball_X, ball_Y; // 球的位置,在第几行第几列格子上
private boolean drawPath = false; // flag,标识是否画出路径
private boolean drawRun = false; //flag,自动寻路
Labyrinth(int n, int w, int p) {
num = n;
width = w;
padding = p;
maze = new Lattice[num][num];
for (int i = 0; i <= num - 1; i++)
for (int j = 0; j <= num - 1; j++)
maze[i][j] = new Lattice(i, j);
createMaze();
setKeyListener();
this.setFocusable(true);
}
// 初始化游戏,重开一局时使用
private void init() {
for (int i = 0; i <= num - 1; i++)
for (int j = 0; j <= num - 1; j++) {
maze[i][j].setFather(null);
maze[i][j].setFlag(Lattice.NotInTree);
}
ball_X = 0;
ball_Y = 0;
drawPath = false;
drawRun = false;
createMaze();
// setKeyListener();
this.setFocusable(true);
repaint();
}
// 由格子的行数,得到格子中心点的像素X座标
public int getCenterX(int x) {
return padding + x * width + width / 2;
}
// 由格子的列数,得到格子中心点的像素Y座标
public int getCenterY(int y) {
return padding + y * width + width / 2;
}
public int getCenterX(Lattice p) {
return padding + p.getY() * width + width / 2;
}
public int getCenterY(Lattice p) {
return padding + p.getX() * width + width / 2;
}
// 检查是否到达最后一个格子,若是则走出了迷宫,重开一局游戏
private void checkIsWin() {
if (ball_X == num - 1 && ball_Y == num - 1) {
JOptionPane.showMessageDialog(null, "YOU WIN !", "你走出了迷宫。",
JOptionPane.PLAIN_MESSAGE);
init();
}
}
// 移动小球,c为按键码
synchronized private void move(int c) {
int tx = ball_X, ty = ball_Y;
// System.out.println(c);
switch (c) {
case KeyEvent.VK_A -> ty--;
case KeyEvent.VK_D -> ty++;
case KeyEvent.VK_W -> tx--;
case KeyEvent.VK_S -> tx++;
case KeyEvent.VK_ESCAPE -> drawRun = !drawRun;
case KeyEvent.VK_SPACE -> drawPath = !drawPath;
default -> {
}
}
// 若移动后未出界且格子之间有路径,则进行移动,更新小球位置,否则移动非法
if (!isOutOfBorder(tx, ty)
&& (maze[tx][ty].getFather() == maze[ball_X][ball_Y]
|| maze[ball_X][ball_Y].getFather() == maze[tx][ty])) {
ball_X = tx;
ball_Y = ty;
}
}
private void setKeyListener() {
this.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int c = e.getKeyCode();
move(c);
repaint();
checkIsWin();
}
});
}
// 是否出界
private boolean isOutOfBorder(Lattice p) {
return isOutOfBorder(p.getX(), p.getY());
}
private boolean isOutOfBorder(int x, int y) {
return x > num - 1 || y > num - 1 || x < 0 || y < 0;
}
// 获取格子的邻居格子
private Lattice[] getNeIs(Lattice p) {
final int[] adds = {-1, 0, 1, 0, -1};
if (isOutOfBorder(p)) {
return null;
}
Lattice[] ps = new Lattice[4]; // 四个邻居格子,顺序为上右下左,出界的邻居为null
int xt;
int yt;
for (int i = 0; i <= 3; i++) {
xt = p.getX() + adds[i];
yt = p.getY() + adds[i + 1];
if (isOutOfBorder(xt, yt))
continue;
ps[i] = maze[xt][yt];
}
return ps;
}
// 构建随机树,创建迷宫
private void createMaze() {
// 随机选一个格子作为树的根
Random random = new Random();
int rx = Math.abs(random.nextInt()) % num;
int ry = Math.abs(random.nextInt()) % num;
// 深度优先遍历
Stack<Lattice> s = new Stack<>();
Lattice p = maze[rx][ry];
Lattice[] NeIs;
s.push(p);
while (!s.isEmpty()) {
p = s.pop();
p.setFlag(Lattice.InTree);
NeIs = getNeIs(p);
int ran = Math.abs(random.nextInt()) % 4;
for (int a = 0; a <= 3; a++) {
ran++;
ran %= 4;
assert NeIs != null;
if (NeIs[ran] == null || NeIs[ran].getFlag() == Lattice.InTree)
continue;
s.push(NeIs[ran]);
NeIs[ran].setFather(p);
}
}
}
// 抹掉两个格子之间的边
private void clearFence(int i, int j, int fx, int fy, Graphics g) {
int sx = padding + ((Math.max(j, fy)) * width),
sy = padding + ((Math.max(i, fx)) * width),
dx = (i == fx ? sx : sx + width),
dy = (i == fx ? sy + width : sy);
if (sx != dx) {
sx++;
dx--;
} else {
sy++;
dy--;
}
g.drawLine(sx, sy, dx, dy);
}
// 画迷宫
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// 画NUM*NUM条黑线
for (int i = 0; i <= num; i++) {
g.drawLine(padding + i * width, padding, padding + i * width,
padding + num * width);
}
for (int j = 0; j <= num; j++) {
g.drawLine(padding, padding + j * width, padding + num * width,
padding + j * width);
}
// 使用背景色,在有路径的格子之间画边,把墙抹掉
g.setColor(this.getBackground());
for (int i = num - 1; i >= 0; i--) {
for (int j = num - 1; j >= 0; j--) {
Lattice f = maze[i][j].getFather();
if (f != null) {
int fx = f.getX(), fy = f.getY();
clearFence(i, j, fx, fy, g);
}
}
}
// 画左上角的入口
g.drawLine(padding, padding + 1, padding, padding + width - 1);
int last = padding + num * width;
// 画右下角出口
g.drawLine(last, last - 1, last, last - width + 1);
// 画小球
g.setColor(Color.RED);
g.fillOval(getCenterX(ball_Y) - width / 3, getCenterY(ball_X) - width / 3,
width / 2, width / 2);
if (drawPath)
drawPath(g);
if (drawRun)
drawRun(g);
}
private void drawPath(Graphics g) {
Color PATH_COLOR = Color.ORANGE, BOTH_PATH_COLOR = Color.PINK;
if (drawPath)
g.setColor(PATH_COLOR);
else
g.setColor(this.getBackground());
Lattice p = maze[num - 1][num - 1];
while (p.getFather() != null) {
p.setFlag(2);
p = p.getFather();
}
g.fillOval(getCenterX(p) - width / 3, getCenterY(p) - width / 3,
width / 2, width / 2);
p = maze[0][0];
while (p.getFather() != null) {
if (p.getFlag() == 2) {
p.setFlag(3);
g.setColor(BOTH_PATH_COLOR);
}
g.drawLine(getCenterX(p), getCenterY(p), getCenterX(p.getFather()),
getCenterY(p.getFather()));
p = p.getFather();
}
g.setColor(PATH_COLOR);
p = maze[num - 1][num - 1];
while (p.getFather() != null) {
if (p.getFlag() == 3)
break;
g.drawLine(getCenterX(p), getCenterY(p), getCenterX(p.getFather()),
getCenterY(p.getFather()));
p = p.getFather();
}
}
private void drawRun(Graphics g) {
Color RUN_COLOR = Color.BLUE;
if (drawRun)
g.setColor(RUN_COLOR);
else
g.setColor(this.getBackground());
}
public static void main(String[] args) {
final int n = 30, width = 600, padding = 20, LX = 200, LY = 100;
JPanel p = new Labyrinth(n, (width - padding - padding) / n, padding);
JFrame frame = new JFrame("迷宫(按空格键显示或隐藏路径)");
frame.getContentPane().add(p);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(width + padding, width + padding + padding);
frame.setLocation(LX, LY);
frame.setVisible(true);
}
}
分析:
1,迷宫游戏的大体功能得以实现;
2,设置了画出路径和隐藏路径按钮,方便玩家取得游戏的胜利;
3,加入了有趣的图片和唯美的背景图,增加了游戏的可玩性。
不足:
不能显示出玩家走过的全部路径,只能显示成功到达迷宫出口的最短路径。