通过设计迷宫小游戏,理解数组;
定义数组确定迷宫的地图;
package com.javase;
import java.util.Scanner;
public class MingGong {
public static void main(String[] args) {
//声明数组
char [][] map= {
{'*','*','*','*','*','*','*','*','*','*','*','*','*','*','*','*','*','*','*','*','*'},
{'*','|','*','|','*','*','|','*','|','*','*','*','*','*','|','*','|','*','*','|','*'},
{'*','|','*','|','*','*','|','*','|','|','|','|','*','*','|','*','|','*','*','|','*'},
{'*','|','*','|','*','*','|','*','*','*','*','|','*','*','|','*','|','|','*','|','*'},
{'*','|','*','|','*','*','|','*','*','*','*','|','*','*','|','*','*','|','*','|','*'},
{'*','|','*','|','*','*','|','*','*','*','*','|','*','*','|','*','*','|','*','|','*'},
{'*','|','*','|','|','|','|','|','|','|','|','|','*','*','|','*','*','|','*','|','*'},
{'*','|','*','*','*','*','|','*','*','*','*','*','*','*','|','*','*','|','*','|','*'},
{'*','|','*','*','*','*','|','*','*','*','*','*','*','*','|','*','|','|','*','|','*'},
{'*','|','|','|','*','*','|','*','*','*','*','|','|','|','|','*','|','|','|','|','*'},
{'*','*','*','|','*','*','*','*','*','*','*','|','*','*','|','|','|','|','*','|','*'},
{'*','*','*','|','|','|','|','|','|','*','*','|','*','*','*','*','*','|','*','|','*'},
{'*','*','*','*','*','*','*','*','|','*','*','|','*','*','*','*','*','|','*','|','*'},
{'*','*','*','|','|','|','|','|','|','*','*','|','*','*','*','*','*','|','*','|','*'},
{'*','*','*','|','*','*','*','*','*','*','|','|','|','|','|','*','*','|','*','|','*'},
{'*','*','*','|','|','|','|','|','|','|','|','*','*','*','|','|','|','|','*','|','*'},
{'*','*','*','|','*','*','*','*','*','*','*','*','*','*','*','*','*','*','*','A','*'},
{'*','*','*','|','*','*','*','*','*','*','*','*','*','*','*','*','*','*','*','|','*'}
};
//得到人物A的坐标
int xP=16;
int yP=19;
//得到出口的坐标
int endX=16;
int endY=3;
//在控制台打印地图
int ii=0;
int jj=0;
for(ii=0;ii<map.length;ii++){
for (jj=0;jj<map[ii].length;jj++){
System.out.print(map[ii][jj]+" ");
}
System.out.println();
}
//给用户提示
Scanner sc=new Scanner(System.in);
while (true){
System.out.println("请输入wasd,来控制人物A,上下左右,移动!");
//得到用户输入的值,第一个字母
char c = sc.next().charAt(0);
switch (c){
case 'w':
//A的上一位,不是 墙“*”
if(map[xP-1][yP]!='*'){
char temp;
temp=map[xP][yP];
map[xP][yP]=map[xP-1][yP];
map[xP-1][yP]=temp;
xP-=1;
}
break;
case 's':
if(xP+1<map.length && map[xP+1][yP]!='*'){
char temp;
temp=map[xP][yP];
map[xP][yP]=map[xP+1][yP];
map[xP+1][yP]=temp;
xP+=1;
}
break;
case 'a':
if(map[xP][yP-1]!='*'){
char temp;
temp=map[xP][yP];
map[xP][yP]=map[xP][yP-1];
map[xP][yP-1]=temp;
yP-=1;
}
break;
case 'd':
if(map[xP][yP+1]!='*'){
char temp;
temp=map[xP][yP];
map[xP][yP]=map[xP][yP+1];
map[xP][yP+1]=temp;
yP+=1;
}
break;
default:
System.out.println("请输入wasd!");
break;
}
//把地图重新打印一下
//在控制台打印地图
for(int i=0;i<map.length;i++){
for (int j=0;j<map[i].length;j++){
System.out.print(map[i][j]+" ");
}
System.out.println();
}
//判断用户是否走出迷宫
if(xP==endX && yP==endY){
System.out.println("你太厉害了,竟然走出了迷宫!!!!!");
return;
}
}
}
}