/// <summary> /// Generate a perfect maze in map /// </summary> void HuntAndKill() { bool flag = true; List <Block> usefulBlocks = new List <Block>(); for (int i = 0; i < width; i++) { for (int j = 0; j < length; j++) { if (gmap[i][j].block == ConstNum.WALL) { usefulBlocks.Add(gmap[i][j]); } } } while (usefulBlocks.Count > 0) { Block block = new Block(); flag = true; for (int i = 0; i < width; i++) { for (int j = 0; j < length; j++) { if (!flag) { break; } if (gmap[i][j].block == ConstNum.WALL) { if (i != width - 1) //下搜索 { if (gmap[i + 1][j].block == ConstNum.ROAD) { block = gmap[i][j]; block.bottom = ConstNum.ROAD; block.block = ConstNum.ROAD; gmap[i + 1][j].top = ConstNum.ROAD; flag = false; break; } } if (j != length - 1)//左搜索 { if (gmap[i][j + 1].block == ConstNum.ROAD) { block = gmap[i][j]; block.right = ConstNum.ROAD; block.block = ConstNum.ROAD; gmap[i][j + 1].left = ConstNum.ROAD; flag = false; break; } } if (j != 0)//右搜索 { if (gmap[i][j - 1].block == ConstNum.ROAD) { block = gmap[i][j]; block.left = ConstNum.ROAD; block.block = ConstNum.ROAD; gmap[i][j - 1].right = ConstNum.ROAD; flag = false; break; } } if (i != 0)//上搜索 { if (gmap[i - 1][j].block == ConstNum.ROAD) { block = gmap[i][j]; block.top = ConstNum.ROAD; block.block = ConstNum.ROAD; gmap[i - 1][j].bottom = ConstNum.ROAD; flag = false; break; } } } if (!flag) { break; } } } if (flag) { block = RandomTool <Block> .RollItem(ref usefulBlocks, ref rd); } else { usefulBlocks.Remove(block); } //找一个格子进行搜索,如果找不到现有连接那么随机掷一个 flag = false; while (!flag) { List <Block> bk = new List <Block>(); if (block.y != 0) { if (gmap[block.y - 1][block.x].block == ConstNum.WALL) { bk.Add(gmap[block.y - 1][block.x]); } } if (block.x != 0) { if (gmap[block.y][block.x - 1].block == ConstNum.WALL) { bk.Add(gmap[block.y][block.x - 1]); } } if (block.y != width - 1) { if (gmap[block.y + 1][block.x].block == ConstNum.WALL) { bk.Add(gmap[block.y + 1][block.x]); } } if (block.x != length - 1) { if (gmap[block.y][block.x + 1].block == ConstNum.WALL) { bk.Add(gmap[block.y][block.x + 1]); } } if (bk.Count != 0) { Block temp = RandomTool <Block> .RollItem(ref bk, ref rd); usefulBlocks.Remove(temp); gmap[temp.y][temp.x].block = ConstNum.ROAD; if (temp.x == block.x) { if (temp.y > block.y) { gmap[temp.y][temp.x].top = ConstNum.ROAD; gmap[block.y][block.x].bottom = ConstNum.ROAD; } else if (temp.y < block.y) { gmap[temp.y][temp.x].bottom = ConstNum.ROAD; gmap[block.y][block.x].top = ConstNum.ROAD; } } else if (temp.x > block.x) { gmap[temp.y][temp.x].left = ConstNum.ROAD; gmap[block.y][block.x].right = ConstNum.ROAD; } else if (temp.x < block.x) { gmap[temp.y][temp.x].right = ConstNum.ROAD; gmap[block.y][block.x].left = ConstNum.ROAD; } block = gmap[temp.y][temp.x]; } else { flag = true; } } } }