项目目标和主要内容
1)迷宫游戏是非常经典的游戏,在该题中要求随机生成一个迷宫,并求解迷宫。
项目的主要功能
1)要求游戏支持玩家走迷宫,和系统走迷宫路径两种模式。玩家走迷宫,通过键盘方向键控制;系统走迷宫路径要求基于A*算法实现,输出走迷宫的最优路径并显示。
2)设计交互友好的游戏图形界面。
项目总体框架
Prime迷宫生成算法的原理:
系统详细设计
Java Swing搭建的GUI
1)迷宫游戏的网格大小为25*25
2)以网格大小为基准控制整个界面的大小
3)用户操控的小球、迷宫墙体与最优路线的显示
4)游戏结束时的弹窗显示
键盘监听
1)通过“W”“A”“S”“D”或小键盘区的上下左右控制小球的移动
2)通过“空格”实现最优路线的显示与隐藏
迷宫的随机生成
1)通过prime算法生成迷宫
寻路
1)当小球移动到右下角时游戏结束
2)通过A*算法实现系统寻路
关键算法分析
A*算法是一种启发式搜索算法,利用包含问题启发式信息的评价函数对节点进行排序,使搜索方向朝着最有可能找到目标并产生最优解的方向。
·启发函数的确定
A*算法中引入了评估函数:
f(n)=g(n)+h(n)
其中:n是搜索中遇到的任意状态。g(n)是从起始状态到n的代价。h(n)是对n到目标状态代价的启发式估计。即评估函数f (n) 是从初始节点到达节点n 处已经付出的代价与节点n到达目标节点的接近程度估价值的总和。
定义n点到目标点的最小实际距离为h(n)*,A*算法要满足的条件为:
h(n)< =h(n)*
迷宫每次只能走一步,代价为1,采用的估价函数为当前节点到目标节点的曼哈顿距离,即:
h(n)=|end.x – n.x|+ |end.y – n.y|
end表示迷宫的目标点,n表示当前点。
显然h(n)<=h(n)*。
g(n)容易表示,即每走一步的代价是1,所以利用f(n)=g(n)+h(n)这种策略,我们可以不断地逼近目标点,从而找到问题的解。
源代码
类Yard:
package 迷宫;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Stack;
import javax.swing.JOptionPane;
class Yard extends Frame {
private static final long serialVersionUID = 1L;
public static final int BLOCK = 25;
public static final int BLOCK_SIZE = 30;
public static final int Xpadding = 30;
public static final int Ypadding = 50;
public static int X = 0;
public static int Y = 0;
public static boolean drawPath = false;
private Lattice[][] maze;
Image offScreenImage = null;
public void launch() {
this.setLocation(400, 30);//窗口位置
this.setSize(Xpadding * 2 + BLOCK * BLOCK_SIZE, Ypadding * 2 + BLOCK * BLOCK_SIZE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
this.setVisible(true);
this.setTitle("迷宫");
maze = new Lattice[BLOCK][BLOCK];
for (int i = 0; i <= BLOCK - 1; i++) {
for (int j = 0; j <= BLOCK - 1; j++) {
maze[i][j] = new Lattice(i, j);
}
}
createMaze();
this.setFocusable(true);
setKeyListener();
}
@Override
public void paint(Graphics g) {
g.setColor(Color.white);//背景颜色
g.fillRect(30, 50, BLOCK * BLOCK_SIZE, BLOCK * BLOCK_SIZE);
g.setColor(Color.black);//迷宫线的颜色
//画出横线竖线
for (int i = 1; i < BLOCK + 2; i++) {
g.drawLine(30, 20 + BLOCK_SIZE * i, 30 + BLOCK * BLOCK_SIZE, 20 + BLOCK_SIZE * i);
}
for (int i = 1; i < BLOCK + 2; i++) {
g.drawLine(BLOCK_SIZE * i, 50, BLOCK_SIZE * i, 50 + BLOCK * BLOCK_SIZE);
}
for (int i = BLOCK - 1; i >= 0; i--) {
for (int j = BLOCK - 1; j >= 0; j--) {
Lattice f = maze[i][j].getFather();
if (f != null) {
int fx = f.getX(), fy = f.getY();
Clear(i, j, fx, fy, g);
}
}
}
g.drawLine(Xpadding, Ypadding + 1, Xpadding, Ypadding + BLOCK_SIZE - 1);
g.drawLine(Xpadding + BLOCK * BLOCK_SIZE, Ypadding + BLOCK * BLOCK_SIZE - 1, Xpadding + BLOCK * BLOCK_SIZE, Ypadding + BLOCK * BLOCK_SIZE - BLOCK_SIZE + 1);
g.setColor(Color.black);//球的颜色
g.fillOval(getCenterX(Y) - BLOCK_SIZE / 3, getCenterY(X) - BLOCK_SIZE / 3, BLOCK_SIZE / 2, BLOCK_SIZE / 2);
if (drawPath == true) {
drawPath(g);
}
}
public int getCenterX(int x) {
return Xpadding + x * BLOCK_SIZE + BLOCK_SIZE / 2;
}
public int getCenterY(int y) {
return Ypadding + y * BLOCK_SIZE + BLOCK_SIZE / 2;
}
public int getCenterX(Lattice p) {
return Xpadding + p.getY() * BLOCK_SIZE + BLOCK_SIZE / 2;
}
public int getCenterY(Lattice p) {
return Ypadding + p.getX() * BLOCK_SIZE + BLOCK_SIZE / 2;
}
private boolean Out(int x, int y) {
return (x > BLOCK - 1 || y > BLOCK - 1 || x < 0 || y < 0) ? true : false;
}
public void update(Graphics g) {
if (offScreenImage == null) {
offScreenImage = this.createImage(60 + BLOCK * BLOCK_SIZE, 80 + BLOCK * BLOCK_SIZE);
}
Graphics gOff = offScreenImage.getGraphics();
paint(gOff);
g.drawImage(offScreenImage, 0, 0, null);
}
public boolean Stop(int x, int y) {
if (!Out(X, Y) && (maze[x][y].getFather() == maze[X][Y] || maze[X][Y].getFather() == maze[x][y])) {
return true;
} else {
return false;
}
}
private void checkWin() {
if (X == BLOCK - 1 && Y == BLOCK - 1) {
JOptionPane.showMessageDialog(null, "游戏结束", "恭喜你走出迷宫", JOptionPane.PLAIN_MESSAGE);
System.exit(0);
}
}
class Lattice {
private int x = 0;
private int y = 0;
private boolean check = false;
private Lattice father = null;
public Lattice(int x, int y) {
this.x = x;
this.y = y;
}
public void setCheck(boolean c) {
check = c;
}
public void setFather(Lattice f) {
father = f;
}
public Lattice getFather() {
return father;
}
public boolean getcheck() {
return check;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
private void Clear(int i, int j, int fx, int fy, Graphics g) {
int sx = Xpadding + ((j > fy ? j : fy) * BLOCK_SIZE),
sy = Ypadding + ((i > fx ? i : fx) * BLOCK_SIZE),
dx = (i == fx ? sx : sx + BLOCK_SIZE),
dy = (i == fx ? sy + BLOCK_SIZE : sy);
if (sx != dx) {
sx++;
dx--;
} else {
sy++;
dy--;
}
g.setColor(Color.white);//网格颜色
g.drawLine(sx, sy, dx, dy);
}
private void createMaze() {
Random random = new Random();
int rx = 0;//Math.abs(random.nextInt()) % BLOCK;
int ry = 0;//Math.abs(random.nextInt()) % BLOCK;
Stack<Lattice> s = new Stack<Lattice>();
Lattice p = maze[rx][ry];
Lattice e[] = null;
s.push(p);
while (!s.isEmpty()) {
p = s.pop();
p.setCheck(true);
e = Ergodic(p);
int ran = Math.abs(random.nextInt()) % 4;
for (int a = 0; a <= 3; a++) {
ran++;
ran %= 4;
if (e[ran] == null || e[ran].getcheck() == true) {
continue;
}
s.push(e[ran]);
e[ran].setFather(p);
}
}
}
private Lattice[] Ergodic(Lattice p) {
final int[] adds = {-1, 0, 1, 0, -1};// 顺序为上右下左
if (Out(p.getX(), p.getY())) {
return null;
}
Lattice[] ps = new Lattice[4];// 顺序为上右下左
int xt;
int yt;
for (int i = 0; i <= 3; i++) {
xt = p.getX() + adds[i];
yt = p.getY() + adds[i + 1];
if (Out(xt, yt)) {
continue;
}
ps[i] = maze[xt][yt];
}
return ps;
}
synchronized private void move(int c) {
int tx = X, ty = Y;
switch (c) {
case KeyEvent.VK_LEFT:
ty--;
break;
case KeyEvent.VK_A:
ty--;
break;
case KeyEvent.VK_RIGHT:
ty++;
break;
case KeyEvent.VK_D:
ty++;
break;
case KeyEvent.VK_UP:
tx--;
break;
case KeyEvent.VK_W:
tx--;
break;
case KeyEvent.VK_DOWN:
tx++;
break;
case KeyEvent.VK_S:
tx++;
break;
case KeyEvent.VK_SPACE:
if (drawPath == true) {
drawPath = false;
} else {
drawPath = true;
}
break;
default:
}
if (Stop(tx, ty)) {
X = tx;
Y = ty;
}
}
//**键盘监听
private void setKeyListener() {
this.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int c = e.getKeyCode();
move(c);
repaint();
checkWin();
}
});
}
class Solve {
int startx = X, starty = Y;
int endx = BLOCK - 1, endy = BLOCK - 1;
List<Position> open;
Solve(Graphics g) {
Position start = new Position(startx, starty, null);
Position end = null;
open.add(start);
while (true) {
Position chosed = open.remove(0);
if (chosed.x == endx && chosed.y == endy) {
end = chosed;
break;
}
if (Stop(chosed.x - 1, chosed.y)) {
addToOpenList(new Position(chosed.x - 1, chosed.y, chosed));
}
if (Stop(chosed.x + 1, chosed.y)) {
addToOpenList(new Position(chosed.x + 1, chosed.y, chosed));
}
if (Stop(chosed.x, chosed.y - 1)) {
addToOpenList(new Position(chosed.x, chosed.y - 1, chosed));
}
if (Stop(chosed.x, chosed.y + 1)) {
addToOpenList(new Position(chosed.x, chosed.y + 1, chosed));
}
}
Position tmp = end;
while (tmp != null) {
g.drawLine(getCenterX(tmp.x), getCenterY(tmp.y), getCenterX(tmp.lastPosition.x), getCenterY(tmp.lastPosition.x));
tmp = tmp.lastPosition;
}
}
class Position {
int x;
int y;
Position lastPosition;
int pastDistance = 0;
int predictDistance;
Position(int x, int y, Position lastPosition) {
this.x = x;
this.y = y;
this.lastPosition = lastPosition;
if (lastPosition != null) {
pastDistance = lastPosition.pastDistance + 1;
}
predictDistance = BLOCK * 2 - 2 - this.x - this.y;
}
int distance() {
return pastDistance + predictDistance;
}
}
void addToOpenList(Position q) {
Iterator<Position> itr = open.iterator();
int index = -1;
while (itr.hasNext()) {
Position tmp = itr.next();
index++;
if (q.distance() <= tmp.distance()) {
open.add(index, q);
return;
}
}
open.add(q);
}
}
private void drawPath(Graphics g) {
Color PATH_COLOR = Color.gray;
g.setColor(PATH_COLOR);
Lattice p = maze[BLOCK - 1][BLOCK - 1];
while (p.getFather() != null) {
p = p.getFather();
}
p = maze[BLOCK - 1][BLOCK - 1];
while (p.getFather() != null) {
g.drawLine(getCenterX(p), getCenterY(p), getCenterX(p.getFather()),
getCenterY(p.getFather()));
p = p.getFather();
}
g.setColor(PATH_COLOR);
p = maze[BLOCK - 1][BLOCK - 1];
while (p.getFather() != null) {
g.drawLine(getCenterX(p), getCenterY(p), getCenterX(p.getFather()),
getCenterY(p.getFather()));
p = p.getFather();
}
}
}
类Maze:
package 迷宫;
public class Maze {
public static void main(String[] args) {
new Yard().launch();
}
}
迷宫界面展示