面向对象与设计模式-Java实验四

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

随机迷宫游戏 (面向对象)

1.实验要求

编程题:我们之前已经实现了幻方、猜数等小游戏,请再开发一个迷宫游戏,随机生成一个迷宫,系统使用回溯或递归的方法找出从入口到出口的路径。迷宫可以简单用一个二维数组来表示(不要求一定要可视化),迷宫的路径存放在一个LinkedList 中,每一步可以存为一个Point 对象(有x 和y 坐标,分别代表二维数组的行和列)。2 设计及实现

2.1 设计思想

类图:

2.2 核心算法

public Load goUp()

//向上走

{

Load nextlocation;

nextlocation =new Load(); nextlocation.locationi=location.locationi-1;

nextlocation.locationj=location.locationj;

return nextlocation;

}

public Load goDown() //向下走

{

Load nextlocation;

nextlocation =new Load();

nextlocation.locationi=location.locationi+1;

nextlocation.locationj=location.locationj;

return nextlocation;

}

public Load goRight() //向右走

{

Load nextlocation;

nextlocation =new Load();

nextlocation.locationi=location.locationi;

nextlocation.locationj=location.locationj+1;

return nextlocation;

}

public Load goLeft() //向左走

{

Load nextlocation;

nextlocation =new Load();

nextlocation.locationi=location.locationi;

nextlocation.locationj=location.locationj-1;

return nextlocation;

}

//迷宫找路径方法

public boolean findTheWay(int[][] maze)

{

Stack seekStack =new Stack(); //探查堆栈

while(location.locationi!=9||location.locationj!=8

&&0<=location.locationi&&location.locationi<=9

&&0<=location.locationj&&location.locationj<=9) //当还没到达出口*/

{

if(visted[location.locationi][location.locationj]==false)

{

seekStack.push(location); //位置入栈

visted[location.locationi][location.locationj]=true; //该位置已被访问

}

if(maze[location.locationi][location.locationj+1]==

0&&visted[location.locationi][location.locationj+1]==false) //该位置向右可通

{

maze[location.locationi][location.locationj]=2; //用→表示该位置向右可通

location=goRight();//移动到右侧下一位置

}

Else if(maze[location.locationi+1][location.locationj]== 0&&visted[location.locationi+1][location.locationj]==false)

{

maze[location.locationi][location.locationj]=3; //表示该处向下可通

location=goDown(); //移动到下一位置

}

Else if(maze[location.locationi][location.locationj-1]== 0&&visted[location.locationi][location.locationj-1]==false) //表示改点可通且未被访问

{

maze[location.locationi][location.locationj]=4; //表示向左可通

location=goLeft(); //向左移动到下一位置

}

else if (location.locationi!=0&&maze[location.locationi-1][location.locationj]== 0&&visted[location.locationi-1][location.locationj]==false) //向上可通并且未被访问

{

maze[location.locationi][location.locationj]=5; //表示向上可通

location=goUp(); //移动到上一个相邻的位置

}

else //该位置不通

{

Load die;

die=(Load)seekStack.pop(); //将该位置从堆栈中退出

maze[die.locationi][die.locationj]=0;

if (seekStack.empty()==true)

{

break;

}

location=(Load) seekStack.peek();

}

}

if (location.locationi==9&&location.locationj==8)

{

return true;

}

else

{

System.out.println("没有出路,游戏结束!");

return false;

}

}

}

2.3运行后可得第一界面如下:

相关文档
最新文档