-
Notifications
You must be signed in to change notification settings - Fork 0
/
cell_auto_mapgen.c
80 lines (74 loc) · 1.99 KB
/
cell_auto_mapgen.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include "grid.h"
#define PROB 45
#define GENERATIONS 12
int ayn_rand(){
return (rand()%100<PROB);
}
int mapgen(struct Grid*map,struct Grid*map2){
int x, y;
for(y=1;y<map->r;y++)
for(x=1;x<map->c;x++)
*gridrc(map,y,x) = ayn_rand();
memset(map2->elem,1,map2->r*map2->c);
for(y=0;y<map->r;y++)
*gridrc(map,y,0) = *gridrc(map,y,map->c-1) = 1;
for(x=0;x<map->c;x++)
*gridrc(map,map->r-1,x) = *gridrc(map,0,x) = 1;
return 0;
}
void generation(struct Grid*map,struct Grid*map2){
int x,y,i,j;
for(y=1;y<map->r-1;y++)
for(x=1;x<map->c-1;x++){
int adjacent1 = 0, adjacent2 = 0;
for(i=-1;i<=1;i++)
for(j=-1;j<=1;j++)
if(*gridrc(map,y+i,x+j))
adjacent1++;
for(i=y-2;i<=y+2;i++)
for(j=x-2;j<=x+2;j++)
if(abs(i-y)+abs(j-x)<4&&gridrc(map,i,j)&&*gridrc(map,i,j))
adjacent2++;
*gridrc(map2,y,x)=adjacent1>=5||adjacent2<=2?1:0;
}
}
void flood(struct Grid*map,struct Grid*map2,int r, int c, int* filled){
*gridrc(map2,r,c) = 1;
*filled+=1;
for(int i=0;i<2;i++)
for(int j=-1;j<2;j+=2)
if(!*gridrc(map,r+i*j,c+!i*j)&&!*gridrc(map2,r+i*j,c+!i*j))
flood(map,map2,r+i*j,c+!i*j,filled);
}
struct Grid* mkmap(int r,int c){
srand(time(NULL));
int filled;
regen:
filled = 0;
struct Grid*map = mkgrid(r,c);
struct Grid*map2 = mkgrid(r,c);
//NOTE GENERATIONS HAVE TO BE EVEN FOR THIS TO WORK!!!
mapgen(map,map2);
for(int i = 0;i<GENERATIONS;i++){
generation(map,map2);
struct Grid*tmp=map;
map=map2;
map2=tmp;
}
int x,y;
do{
y = rand()%r;
x = rand()%c;
}while(*gridrc(map,y,x));
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
*gridrc(map2,i,j) = 0;
flood(map,map2,y,x,&filled);
if(filled<r*c*9/20) goto regen;
rmgrid(map);
return map2;
}