Java华容道游戏源代码
时间: 2023-08-18 21:06:45 浏览: 178
以下是Java华容道游戏的源代码,希望能对你有所帮助:
```java
import java.util.*;
public class HuaRongDao {
static int[][] map = new int[5][4];
static int[] s = new int[10];
static int[] fx = {0, -1, 1, 0, 0}; // 上下左右
static int[] fy = {0, 0, 0, -1, 1};
static String[] name = {"", "曹操", "关羽", "张飞", "赵云", "黄忠", "马超", "魏延", "兵1", "兵2"};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
init();
while (true) {
printMap();
if (checkOver()) {
System.out.println("恭喜您,游戏通关!");
break;
}
System.out.print("请输入移动的人物编号和方向:");
int n = sc.nextInt();
int d = sc.nextInt();
if (n >= 1 && n <= 8 && d >= 1 && d <= 4) {
move(n, d);
} else {
System.out.println("输入不合法!");
}
}
sc.close();
}
// 初始化地图
public static void init() {
map[0][0] = map[0][3] = map[4][0] = map[4][3] = 1;
map[2][1] = map[3][1] = map[2][2] = map[3][2] = 2;
map[0][1] = map[0][2] = 3;
map[1][1] = map[1][2] = 4;
map[2][0] = map[3][0] = 5;
map[2][3] = map[3][3] = 6;
map[1][0] = 7;
map[1][3] = 8;
for (int i = 1; i <= 8; i++) {
s[i] = i;
}
}
// 打印地图
public static void printMap() {
System.out.println("华容道:");
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(name[map[i][j]] + "\t");
}
System.out.println();
}
}
// 移动人物
public static void move(int n, int d) {
int x = 0, y = 0;
// 找到人物所在的位置
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 4; j++) {
if (map[i][j] == n) {
x = i;
y = j;
break;
}
}
}
// 计算移动后的位置
int nx = x + fx[d];
int ny = y + fy[d];
// 判断是否可以移动
if (nx >= 0 && nx < 5 && ny >= 0 && ny < 4 && map[nx][ny] == 0) {
map[nx][ny] = n;
map[x][y] = 0;
} else {
System.out.println("不能移动!");
}
}
// 检查是否通关
public static boolean checkOver() {
return map[3][1] == 1 && map[3][2] == 1;
}
}
```
阅读全文