用java写一个可计时的迷宫游戏
时间: 2023-12-09 21:02:37 浏览: 25
好的,我可以为你提供一个可计时的迷宫游戏的Java代码示例。以下是代码:
```java
import java.util.Scanner;
public class MazeGame {
private static char[][] maze = { // 迷宫地图
{'#', '#', '#', '#', '#', '#', '#', '#', '#', '#'},
{'#', '.', '.', '.', '#', '.', '.', '.', '.', '#'},
{'#', '.', '#', '.', '#', '.', '#', '#', '.', '#'},
{'#', '.', '#', '.', '.', '.', '.', '.', '.', '#'},
{'#', '.', '#', '#', '#', '.', '#', '#', '.', '#'},
{'#', '.', '.', '.', '#', '.', '.', '.', '.', '#'},
{'#', '.', '#', '.', '#', '#', '#', '.', '#', '#'},
{'#', '.', '.', '.', '.', '.', '.', '.', '.', '#'},
{'#', '#', '#', '#', '#', '#', '#', '#', '#', '#'}
};
private static int playerX = 1; // 玩家初始位置
private static int playerY = 1;
private static int timeLimit = 60; // 游戏时间限制(秒)
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long startTime = System.currentTimeMillis(); // 记录游戏开始时间
while (true) {
// 绘制地图
for (int y = 0; y < maze.length; y++) {
for (int x = 0; x < maze[y].length; x++) {
if (x == playerX && y == playerY) {
System.out.print('O'); // 玩家位置用 O 表示
} else {
System.out.print(maze[y][x]);
}
}
System.out.println();
}
// 判断是否到达终点
if (playerX == 8 && playerY == 8) {
System.out.println("Congratulations, you win!");
break;
}
// 判断时间是否超限
long currentTime = System.currentTimeMillis();
int elapsedSeconds = (int) ((currentTime - startTime) / 1000);
if (elapsedSeconds >= timeLimit) {
System.out.println("Game over, time's up!");
break;
}
// 获取用户输入移动方向
System.out.print("Enter direction (WASD): ");
String input = scanner.nextLine().toUpperCase();
char direction = input.length() > 0 ? input.charAt(0) : ' ';
// 移动玩家
int newX = playerX;
int newY = playerY;
switch (direction) {
case 'W': newY--; break;
case 'A': newX--; break;
case 'S': newY++; break;
case 'D': newX++; break;
}
if (maze[newY][newX] != '#') {
playerX = newX;
playerY = newY;
}
}
scanner.close();
}
}
```
在这个代码中,我们使用了一个二维字符数组来表示迷宫地图。玩家的位置用 `playerX` 和 `playerY` 两个变量记录。游戏时间限制设为60秒,游戏开始时记录当前时间戳,每次循环时判断时间是否超限。
在游戏循环中,我们首先绘制地图,然后判断玩家是否到达终点或者时间是否超限。接着获取用户输入的移动方向,根据方向计算出新的玩家位置(如果新位置不是墙壁),最后更新玩家位置。如果游戏结束,就输出相应的提示信息并结束程序。
你可以根据需要修改迷宫地图、玩家初始位置和游戏时间限制等参数。希望这个代码对你有所帮助!