Advertisement
SpandITime

CaveGen.c

Jan 9th, 2019
350
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.15 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <time.h>
  4.  
  5. struct TileMap{
  6.  
  7.     unsigned int Width,Height;
  8.  
  9.     int* Map;
  10.  
  11. };
  12.  
  13. struct TileMap* generateCave(
  14.         unsigned int Width,
  15.         unsigned int Height,    
  16.         unsigned int FP,        //Fill Percent
  17.         unsigned int SL,        //Smooth level (must be 0-8)
  18.         unsigned int HM         //Human made mode(may be -1,0,1)   -1 - digging, 0 - standart, 1 - building
  19.         ){
  20.     srand(time(0));
  21.     struct TileMap*m;
  22.     m=(struct TileMap*) malloc(sizeof(struct TileMap));
  23.     m->Map=(int*) malloc(Width * Height * sizeof(int*));
  24.    
  25.     if(HM<-1)
  26.         HM=-1;//normalize
  27.    
  28.     if(HM>1)
  29.         HM=1;//normalize
  30.  
  31.     m->Height=Height;
  32.     m->Width=Width;
  33.  
  34.     //random fill map
  35.     for(unsigned int y=0;y<Height-1;y++)
  36.         for(unsigned int x=0;x<Width-1;x++)
  37.             if(y==0||x==0||y==Height-2||x==Width-2)
  38.                 m->Map[y*Width+x]=1;//wall arround Map
  39.             else
  40.                 m->Map[y*Width+x]=(1+rand()%100<FP-(0.4f*FP*(HM)));
  41.  
  42.     for(unsigned int i=0;i<SL;i++)
  43.         for(unsigned int y=1;y<Height-2;y++)
  44.             for(unsigned int x=1;x<Width-2;x++)
  45.             {
  46.                 int wall=0;
  47.                 for(unsigned int x1=x-1;x1<=x+1;x1++)
  48.                     for(unsigned int y1=y-1;y1<=y+1;y1++)
  49.                         if(x1!=x||y1!=y)
  50.                             wall+=(m->Map[y1*Width+x1])?(1):(0);
  51.                
  52.                
  53.                 if(wall>4)
  54.                     m->Map[y*Width+x]=1;
  55.                 else if(wall<4)
  56.                     m->Map[y*Width+x]=0;
  57.                 else if(HM==-1)
  58.                     m->Map[y*Width+x]=0;
  59.                 else if(HM==1)
  60.                     m->Map[y*Width+x]=1;
  61.             }
  62.     return m;
  63. }
  64.  
  65.  
  66. void visualiseTileMap(struct TileMap*m){
  67.     for(unsigned int y=0;y<m->Height;y++){
  68.         for(unsigned int x=0;x<m->Width;x++){
  69.             printf("%c",(m->Map[y*m->Width+x])?('#'):(' '));
  70.         }
  71.         printf("\n");
  72.     }
  73.  
  74. }
  75.  
  76. int main(){
  77.     struct TileMap* map;
  78.     map = generateCave(160,50,65,6,-1);
  79.     visualiseTileMap(map);
  80.     return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement