用java写一个迷宫小游戏代码
时间: 2023-12-07 11:55:38 浏览: 100
java小游戏(迷宫).zip
好的,以下是一个用 Java 编写的迷宫小游戏代码,希望能对您有所帮助:
```
import java.util.Scanner;
public class MazeGame {
static int[][] maze = {
{1,1,1,1,1,1,1,1,1,1},
{1,0,0,1,0,0,0,1,0,1},
{1,0,0,1,0,0,0,1,0,1},
{1,0,0,0,0,1,1,0,0,1},
{1,0,1,1,1,0,0,0,0,1},
{1,0,0,0,1,0,0,0,0,1},
{1,0,1,0,0,0,1,0,0,1},
{1,0,1,1,1,0,1,1,0,1},
{1,1,0,0,0,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1}
};
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("欢迎来到迷宫游戏!请输入您的名字:");
String name = scanner.nextLine();
System.out.println("您好," + name + "!游戏开始!");
int x = 1, y = 1; // 初始位置
while (true) {
printMaze(x, y);
System.out.println("请输入您的移动方向(上下左右),输入 exit 退出游戏:");
String input = scanner.nextLine();
if (input.equals("exit")) {
System.out.println("游戏结束!");
break;
}
int dx = 0, dy = 0; // 移动方向
if (input.equals("上")) {
dy = -1;
} else if (input.equals("下")) {
dy = 1;
} else if (input.equals("左")) {
dx = -1;
} else if (input.equals("右")) {
dx = 1;
} else {
System.out.println("输入有误,请重新输入!");
continue;
}
if (maze[y+dy][x+dx] == 0) {
x += dx;
y += dy;
} else {
System.out.println("您不能往那个方向移动!");
}
if (x == 8 && y == 8) { // 判断是否到达终点
printMaze(x, y);
System.out.println("恭喜您到达终点!");
break;
}
}
}
static void printMaze(int x, int y) {
for (int i = 0; i < maze.length; i++) {
for (int j = 0; j < maze[i].length; j++) {
if (i == y && j == x) {
System.out.print("人 ");
} else if (maze[i][j] == 1) {
System.out.print("█ ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
```
阅读全文