一、实验目的
开发一个迷宫游戏,要求迷宫是自动生成的,具有随机性,掌握A*算法
二、实验器材
通过Java运行输出
三、实验内容
3、基于A*搜索算法迷宫游戏开发
实验内容:
1)迷宫游戏是非常经典的游戏,在该题中要求随机生成一个迷宫,并求解迷宫;
2) 要求查找并理解迷宫生成的算法,并尝试用两种不同的算法来生成随机的迷宫。
3)要求迷宫游戏支持玩家走迷宫,和系统走迷宫路径两种模式。玩家走迷宫,通过键盘方向键控制,并在行走路径上留下痕迹;系统提示迷宫路径要求基于A*算法实现,输出玩家当前位置到迷宫出口的最优路径。设计交互友好的游戏图形界面。
四、实验要点
①随机生成迷宫
②可以实现系统走迷宫和玩家走迷宫
五、实验步骤
用prime算法生成迷宫,用A*算法寻路
Prime迷宫生成算法的原理:
(1)初始地图所有位置均设为墙
(2)任意插入一个墙体进墙队列
(3)判断此时墙体是否可以设置为路(判断依据在于上下左右四个位置是否只有一个位置是路)
(4)若设置为路,则将该位置周围(上下左右)的所有墙插入队列,接着执行(5);若无法设置为路,直接执行(5)
(5)从墙队列中删去当前位置所在节点
(6)若墙队列不为空,则从队列中随机选取一面墙重新执行(3),直到墙队列为空
A*算法寻路
A*算法是人工智能中的一种搜索算法,是一种启发式搜索算法,它不需遍历所有节点,只是利用包含问题启发式信息的评价函数对节点进行排序(Node Ordering),使搜索方向朝着最有可能找到目标并产生最优解的方向。它的独特之处是检查最短路径中每个可能的节点时引入了全局信息,对当前节点距终点的距离做出估计,并作为评价节点处于最短路线上的可能性的度量。
I.启发函数的确定
A*算法中引入了评估函数,评估函数如下:
f(n)=g(n)+h(n)
其中:n是搜索中遇到的任意状态。g(n)是从起始状态到n的代价。h(n)是对n到目标状态代价的启发式估计。即评估函数f ( n) 是从初始节点到达节点n 处已经付出的代价与节点n 到达目标节点的接近程度估价值的总和[10]。
这里我们定义n点到目标点的最小实际距离为h(n)*,A*算法要满足的条件为:
h(n)<=h(n)*
由前面的迷宫问题的描述我们可以知道,迷宫走的时候只能往上下左右走,每走一步,代价为1,这里我们采用的估价函数为当前节点到目标节点的曼哈顿距离,即:
h(n)=|end.x – n.x|+ |end.y – n.y|[11]
这里end表示迷宫的目标点,n表示当前点,很明显这里h(n)<=h(n)*。
g(n)容易表示,即每走一步的代价是1,所以利用f(n)=g(n)+h(n)这种策略,我们可以不断地逼近目标点,从而找到问题的解。
运行环境是JAVA,调用的类是Maze1,两个类都放在迷宫包里
运行代码
类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 = 19;
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(500,100);
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.pink);
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.setColor(Color.PINK);
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.white);
g.fillOval(getCenterX(Y) - BLOCK_SIZE / 3, getCenterY(X) - BLOCK_SIZE / 3,BLOCK_SIZE / 2, BLOCK_SIZE / 2);
if (drawPath == true) {
drawPath(g);
//new Solve(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);
}
}
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.PINK);
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_RIGHT :
ty++;
break;
case KeyEvent.VK_UP :
tx--;
break;
case KeyEvent.VK_DOWN :
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.BLUE, BOTH_PATH_COLOR = Color.PINK;
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.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[BLOCK - 1][BLOCK - 1];
while (p.getFather() != null) {
g.drawLine(getCenterX(p), getCenterY(p), getCenterX(p.getFather()),
getCenterY(p.getFather()));
p = p.getFather();
}
}
}
类Maze1
package 迷宫;
public class Maze1 {
public static void main(String[] args) {
new Yard().launch();
}
}
运行结果
白色小球,黑色墙,键盘输键移动小球
系统走迷宫
按空格键系统提示最优解