Skip to content

Instantly share code, notes, and snippets.

@solenum
Created February 16, 2019 20:00
Show Gist options
  • Save solenum/e13bae3448fd648a2435c62e71739f54 to your computer and use it in GitHub Desktop.
Save solenum/e13bae3448fd648a2435c62e71739f54 to your computer and use it in GitHub Desktop.
#include <inttypes.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
// generation constants
#define CAVE_WIDTH 150
#define CAVE_HEIGHT 300
#define WALL_PROB 55
#define BIAS_DIV 30 // 16
#define CELL_ITER 8
enum {
TILE_AIR,
TILE_HARD,
TILE_SOFT,
TILE_WALL,
TILE_FLOOR,
TILE_LEN
};
uint8_t cave[CAVE_HEIGHT][CAVE_WIDTH];
void cell()
{
// cellular automaton
for (int y=1; y<CAVE_HEIGHT-1; y++) {
for (int x=1; x<CAVE_WIDTH-1; x++) {
int wall_count = 0;
for (int j=-1; j<=1; j++) {
for (int k=-1; k<=1; k++) {
if (cave[y+j][x+k] == TILE_HARD)
wall_count++;
}
}
if (wall_count >= 5)
cave[y][x] = TILE_HARD;
else
cave[y][x] = TILE_AIR;
}
}
}
void gen()
{
srand(time(NULL));
memset(cave, TILE_HARD, CAVE_WIDTH*CAVE_HEIGHT);
// spawn initial wall cells
for (int y=1; y<CAVE_HEIGHT-1; y++) {
for (int x=1; x<CAVE_WIDTH-1; x++) {
// uint32_t bias = 1+abs(CAVE_WIDTH/2-x)/BIAS_DIV;
// its like, a circle or something
uint32_t bias = 1 + abs(CAVE_WIDTH/2 - 1.8 *
sqrt((x - CAVE_WIDTH/2) * (x - CAVE_WIDTH/2)
+ 0.15 * (y - CAVE_HEIGHT/2) * (y - CAVE_HEIGHT/2)))/BIAS_DIV;
if ((rand()%100) < WALL_PROB/bias)
cave[y][x] = TILE_AIR;
}
}
// do the cell automaton thingymajig
for (int i=0; i<CELL_ITER; i++)
cell();
// beautify things a lil bit
for (int y=1; y<CAVE_HEIGHT-1; y++) {
for (int x=1; x<CAVE_WIDTH-1; x++) {
if (cave[y-1][x] == TILE_HARD && cave[y+1][x] == TILE_AIR)
cave[y][x] = TILE_SOFT;
if (cave[y][x] == TILE_HARD) {
if (cave[y][x+1] == TILE_AIR || cave[y][x-1] == TILE_AIR) {
if (cave[y-1][x] == TILE_AIR)
cave[y][x] = TILE_FLOOR;
else
cave[y][x] = TILE_WALL;
}
}
}
}
}
void main()
{
gen();
// debug print
char tiles[TILE_LEN] = {
' ',
'+',
'#',
'|',
'_'
};
for (int y=0; y<CAVE_HEIGHT; y++) {
for (int x=0; x<CAVE_WIDTH; x++) {
printf("%c", tiles[cave[y][x]]);
}
printf("\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment