📄 mapgenerator.java
字号:
import java.util.*;
/**
生成迷宫状的dungeonmap的类
*/
public class MapGenerator {
private static int width; // map的横尺寸
private static int height; // map的纵尺寸
private static int mapData[][]; // 保存mapdate的排列
private static Random rand
= new Random(System.currentTimeMillis()); // Random对象
/**
用int型的2次方排列返回mapdate
参量的高与宽必须都是奇数
*/
public static int[][] getMap(int w, int h) {
width = w;
height = h;
mapData = new int[height][width]; // 生成mapdate用的排列
// 初始状态设定全部为壁(=0)
for(int y = 0; y < height; y++) {
for(int x = 0; x < width; x++) {
mapData[y][x] = 0;
}
}
mapData[1][1] = 1; // 设定左上角道路(=1)
generateRoute(1, 1, 0, 1); // 从左上角开始向下方开始生成迷宫
setItems(); // 设定壁与道路适用的image的index号码
return mapData;
}
/*
从(x, y)坐标开始向指定的方向生成道路
(这个方法被称为重归的)
*/
private static void generateRoute(int x, int y, int dx, int dy) {
int nextX = x + dx * 2;
int nextY = y + dy * 2;
// 移动后的坐标如超出区域则不进行任何处理
if(nextX < 0 || nextX >= width || nextY < 0 || nextY >= height) {
return;
}
// 移动后坐标如遇到已存在道路则不做任何处理移
if(mapData[nextY][nextX] == 1) {
return;
}
// 在移动后的坐标设定道路
mapData[nextY][nextX] = 1;
// 在移动后和移动前设定道路
mapData[y + dy][x + dx] = 1;
// 到达右下角后停止前进
if(nextX == width - 2 && nextY == height - 2) { return; }
//debugOut(); // 输出目前mapdate状态
// 随机决定下面前讲的方向
Vector directions = new Vector();
for(int i = 0; i < 4; i++) {
directions.addElement(new Integer(i));
}
while(!directions.isEmpty()) {
int index = Math.abs(rand.nextInt()) % directions.size();
int nextDirection = ((Integer)directions.elementAt(index)).intValue();
directions.removeElementAt(index);
switch(nextDirection) {
case 0: generateRoute(nextX, nextY, 1, 0); break; // 向右移动
case 1: generateRoute(nextX, nextY, -1, 0); break; // 向左移动
case 2: generateRoute(nextX, nextY, 0, 1); break; // 向下移动
case 3: generateRoute(nextX, nextY, 0, -1); break; // 向上移动
}
}
}
/**
设定壁与道路适用的image的index号码
*/
private static void setItems() {
for(int y = 0; y < height; y++) {
for(int x = 0; x < width; x++) {
if(mapData[y][x] == 0) {
// 设置壁号码为4或者5
mapData[y][x] = Math.abs(rand.nextInt()) % 2 + 4;
} else {
// 设定道路号码为1到3
mapData[y][x] = Math.abs(rand.nextInt()) % 3 + 1;
}
}
}
mapData[1][1] = 6; // 在左上角设置下降台阶
mapData[width - 2][height - 2] = 7; // 在右下角设置上升台阶
}
/**
输出debug用的map状态
*/
public static void debugOut() {
System.out.println("-----------");
for(int y = 0; y < height; y++) {
for(int x = 0; x < width; x++) {
System.out.print(mapData[y][x]);
}
System.out.println("");
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -