迷宫生成:Sidewinder算法

http://weblog.jamisbuck.org/2011/2/7/maze-generation-algorithm-recap
#include <stdlib.h>
#include <stdio.h>

#define N   1 
#define S   2
#define E   4
#define W   8
#define width     16
#define height    8
#define weight    2

typedef unsigned char u8;
typedef unsigned int u32;

static u8 grid[height][width];

#define _rand(MAX) (rand()%(MAX))
#define print(str) printf("%s",(str))

void prt_maze()
{
	u32 x, y;
	print(" ");
	for(x = 0; x < width*2-1; x++)
		print("_");
	print("\n");
	for(y = 0; y < height; y++)
	{
		print("|");
		for(x = 0; x < width; x++)
		{
			u8 cell = grid[y][x];
			// last row or not
			if(cell == 0 && (y+1) < height && grid[y+1][x] == 0)
				print(" ");
			else
				print((cell & S) ? " " : "_");
			// last col or not
			if(cell == 0 && (x+1) < width && grid[y][x+1] == 0)
				print(((y+1) < height && (grid[y+1][x] == 0 || grid[y+1][x+1] == 0)) ? " " : "_");
			else if(cell & E)
				print(((cell | grid[y][x+1]) & S) ? " " : "_");
			else
				print ("|");
		}
		print("\n");
	}
}
///
//  Sidewinder algorithm
///
void gen_maze()
{
	u32 x, y, cell;
	for(y = 0; y < height; y++)
	{
		u32 run_start = 0;
		for(x = 0; x < width; x++)
		{
			// not first row, is last col or not
			if(y > 0 && (x+1 == width || _rand(weight) == 0))
			{
				cell = run_start + _rand(x - run_start + 1);
				grid[y][cell] |= N;
				grid[y-1][cell] |= S;
				run_start = x+1;
			}
			// not last col
			else if (x+1 < width)
			{
				grid[y][x] |= E;
				grid[y][x+1] |= W;
			}
		}
	}
}

int main()
{
	gen_maze();
	prt_maze();
	return 0;
}


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值