迷宮產生器
改寫自我在騎魔滋事家哄騙小朋友的作業
原本的程式其實寫得蠻爛的
// design by novus 2008
// some right reserved
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define M(s) (s)-(1&((s)^1))

const int W = M(33), H = M(23);
char mz[H][W+1] = {0};

int g(const void* a, const void* b) {return rand()&1;}

void f(int r, int c, int d) {
if (0<r && r<H && 0<c && c<W && mz[r][c]!=' ') {
int v[]={-1, -2, 1, 2};
qsort(v, 4, sizeof(int), g);
mz[r][c]=mz[r-d/2][c-d%2]=' ';
for (int i=0; i<4; ++i)
f(r+2*(v[i]/2), c+2*(v[i]%2), v[i]);
}
}

int main() {
for (int i=0; i<H; memset(mz[i++], 1, W));
srand(time(0));
f(1, 1, 0);
for (int i=0; i<H; puts(mz[i++]));
system("pause");
}

緊湊化
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define M(s) (s)-(1&((s)^1))

const int W=46,H=23;char mz[M(H)][M(W)+1]={'\0'};int g(
const void*a, const void*b){return rand()&1;}void f(int
r,int c,int d) {if(0<r&&r<M(H)&&0<c&&c<M(W)&&mz[r][c]!=
' '){int dir[]={-1,-2,1,2}; qsort(dir,4,sizeof(int),g);
mz[r][c]=mz[r-d/2][c-d%2]=' ';for(int i=0;i<4;++i)f(r+2
*(dir[i]/2),c+2*(dir[i]%2),dir[i]);}}int main(){for(int
i=0;i<M(H);memset(mz[i++],1,M(W)));srand(time(0));f(1,1
,0);for(int i=0;i<M(H);puts(mz[i++]));system("pause");}

排成這樣比寫程式還累
// design by novus 2008
// some right reserved
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define M(s) (s)-(1&((s)^1))

const int W=46,H=23;char mz[M(H)][M(W)+1]={'\0'};int g(
const void*a, const void*b){return rand()&1;}void f(int
r,int c,int d){if ( 0<r
&&r<M (H)&& 0<c&& c<M(W
)&&mz [r][c ]!=' '){int dir[] ={-1,-2, 1,2};
qsort (dir, 4,sizeof(int),g);mz[r][c]= mz[r-
d/2][ c-d%2 ]=' ' ;for(
int i =0;i< 4;++i )f(r+ 2*(dir [i]/2
),c+2 *(dir [i]%2 ),dir [i]);
}}int main() {for( int i
=0;i<M(H);memset(mz[i++],1,M(W)));srand(time(0)); f(1,1
,0);for(int i=0;i<M(H);puts(mz[i++]));system("pause");}
轉載請註明出處
須用C++方式編譯(理論上C99也可,如果你找得到這種東西的話)
如果發現bug或有更好的改進意見,請讓我知道

novus 發表在 痞客邦 PIXNET 留言(0) 人氣()