使用Java写一个走迷宫游戏
import java. util. Scanner ;
public class MazeGame {
private static char [ ] [ ] maze = {
{ '#' , '#' , '#' , '#' , '#' , '#' , '#' , '#' , '#' , '#' } ,
{ '#' , 'S' , ' ' , ' ' , '#' , ' ' , ' ' , ' ' , ' ' , '#' } ,
{ '#' , '#' , '#' , ' ' , '#' , ' ' , '#' , '#' , ' ' , '#' } ,
{ '#' , '#' , '#' , ' ' , ' ' , ' ' , '#' , '#' , ' ' , '#' } ,
{ '#' , ' ' , ' ' , ' ' , '#' , '#' , '#' , '#' , ' ' , '#' } ,
{ '#' , '#' , '#' , '#' , '#' , '#' , '#' , '#' , ' ' , '#' } ,
{ '#' , '#' , '#' , '#' , '#' , '#' , '#' , '#' , ' ' , '#' } ,
{ '#' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , '#' } ,
{ '#' , '#' , '#' , '#' , '#' , '#' , '#' , '#' , '#' , '#' } ,
} ;
private static int startRow = 1 ;
private static int startCol = 1 ;
public static void main ( String [ ] args) {
playMazeGame ( ) ;
}
private static void playMazeGame ( ) {
int row = startRow;
int col = startCol;
while ( true ) {
printMaze ( maze) ;
System . out. println ( "请输入移动方向:(W上、S下、A左、D右)" ) ;
Scanner scanner = new Scanner ( System . in) ;
String direction = scanner. nextLine ( ) . toUpperCase ( ) ;
int newRow = row;
int newCol = col;
switch ( direction) {
case "W" :
newRow-- ;
break ;
case "S" :
newRow++ ;
break ;
case "A" :
newCol-- ;
break ;
case "D" :
newCol++ ;
break ;
default :
System . out. println ( "请输入有效的移动方向!" ) ;
continue ;
}
if ( isPositionValid ( newRow, newCol) && maze[ newRow] [ newCol] != '#' ) {
if ( maze[ newRow] [ newCol] == ' ' ) {
maze[ newRow] [ newCol] = 'X' ;
} else if ( maze[ newRow] [ newCol] == 'G' ) {
System . out. println ( "恭喜你成功走出迷宫!" ) ;
break ;
}
maze[ row] [ col] = ' ' ;
row = newRow;
col = newCol;
} else {
System . out. println ( "无法向该方向移动!" ) ;
}
}
}
private static boolean isPositionValid ( int row, int col) {
return row >= 0 && row < maze. length && col >= 0 && col < maze[ 0 ] . length;
}
private static void printMaze ( char [ ] [ ] maze) {
for ( char [ ] row : maze) {
for ( char cell : row) {
System . out. print ( cell + " " ) ;
}
System . out. println ( ) ;
}
System . out. println ( ) ;
}
}
说明:在地图上随便替换一个外围的# 为 G,作为出口,游戏就可以玩出啦,如图: