环境: Notepad++
分析:使用cmd命令窗口模拟出一个迷宫,效果图如下:
1,A代表影响,可上下左右移动
2,星星代表墙壁,英雄无法穿越
3,WSAD,分别代表上下左右
4,英雄移动到右下角,就代表移动成功
5,步数记录走了多少步
代码:
/**
迷宫
*/
import java.util.Scanner;
import java.io.IOException;
class Maze4{
static int tempi = 0;
static int tempj = 0;
static int[][] m = {
{2,1,1,1,1,1},
{0,0,0,0,0,1},
{1,1,0,1,1,1},
{1,1,0,0,0,1},
{1,0,0,1,0,3},
{1,1,1,1,1,1}
};
public static void cls() throws IOException, InterruptedException{
new ProcessBuilder("cmd", "/c", "cls")
.inheritIO()
.start()
.waitFor();
}
public static void getMap(){
//输出迷宫
for(int i = 0; i < m.length ; i++){
for(int j = 0; j < m[i].length; j++){
if(m[i][j]==1){
System.out.print(" *");
}else if(m[i][j]==0){
System.out.print(" ");
}else if(m[i][j]==3){
System.out.print(" O");
}else{
System.out.print(" A");
tempi = i;
tempj = j;
}
}
System.out.println();
}
}
public static void main(String[] args) throws IOException,InterruptedException{
int step = 0;
System.out.println("\n请通过输入“w”“s”“a”“d”,控制A走出迷宫(走到O)");
getMap();
while(true){
//行走
Scanner sc = new Scanner(System.in);
String walk = sc.nextLine();
step = step+1;
if (walk.equals("w")) {
cls();
System.out.println("请通过输入“w”“s”“a”“d”,控制A走出迷宫(走到O)");
if(m[tempi-1][tempj] == 1){
System.out.println("这是墙,不能通过,请重新输入");
}else{
System.out.println();
m[tempi][tempj] = 0;
m[tempi-1][tempj] = 2;
}
getMap();
}else if (walk.equals("s")) {
cls();
System.out.println("请通过输入“w”“s”“a”“d”,控制A走出迷宫(走到O)");
if(m[tempi+1][tempj] == 1){
System.out.println("这是墙,不能通过,请重新输入");
}else{
System.out.println();
m[tempi][tempj] = 0;
m[tempi+1][tempj] = 2;
}
getMap();
}else if (walk.equals("a")) {
cls();
System.out.println("请通过输入“w”“s”“a”“d”,控制A走出迷宫(走到O)");
if(m[tempi][tempj-1] == 1){
System.out.println("这是墙,不能通过,请重新输入");
}else{
System.out.println();
m[tempi][tempj] = 0;
m[tempi][tempj-1] = 2;
}
getMap();
}else if (walk.equals("d")) {
cls();
System.out.println("请通过输入“w”“s”“a”“d”,控制A走出迷宫(走到O)");
if(m[tempi][tempj+1] == 1){
System.out.println("这是墙,不能通过,请重新输入");
}else if(m[tempi][tempj+1] == 3){
System.out.println("恭喜您走出迷宫,您走出迷宫用了"+step+"步");
m[tempi][tempj] = 0;
m[tempi][tempj+1] = 2;
}else{
System.out.println();
m[tempi][tempj] = 0;
m[tempi][tempj+1] = 2;
}
getMap();
}else{
System.out.println("输入错误,请输入“w”“s”“a”“d”,控制A走出迷宫(走到O)");
}
}
}
}
代码运行结果: