Skip to content

Instantly share code, notes, and snippets.

@ehaliewicz
Created November 28, 2012 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ehaliewicz/4165656 to your computer and use it in GitHub Desktop.
Save ehaliewicz/4165656 to your computer and use it in GitHub Desktop.
Random flood fill
// create stack and other structures
stack_t* draw_stack = (stack_t*)malloc(sizeof(stack_t));
stack_init(draw_stack, (wa.width*wa.height));
stack_element_t random_start;
// push random position onto stack
random_start.x = rand()%wa.width;
random_start.y = rand()%wa.height;
stack_push(draw_stack, random_start);
// allocate 2d array for flood fill
int fill_array[wa.width][wa.height];
/* create a X11 graphics context for drawing in the window */
g = XCreateGC (dpy, root, 0, NULL);
int depth = 0;
while (filling)
{
if (stack_is_empty(draw_stack))
{
printf("done.");
filling = false;
XFlush(dpy);
break;
}
else
{
// check for empty spots around the current pixel
stack_element_t stack_top = stack_peek(draw_stack);
int num_spots;
stack_element_t* empty_spots = get_empty_spots(stack_top, fill_array, wa.width, wa.height, num_spots);
// choose out of the empty spots randomly, draw, and continue looping
if (num_spots > 0 && empty_spots != NULL)
{
XColor new_col;
float d_r = (0.008 * depth);
float d_g = (0.09 * depth);
float d_b = (0.9 * depth);
d_r = (d_r > 65535) ? 65535 : d_r;
d_g = (d_g > 65535) ? 65535 : d_g;
d_b = (d_b > 65535) ? 65535 : d_b;
new_col.red = (65535 - d_r);
new_col.green = (65535 - d_g);
new_col.blue = (65535 - d_b);
stack_element_t random_spot = empty_spots[rand()%num_spots];
free (empty_spots);
// allocate color, and set foreground
XAllocColor(dpy, DefaultColormapOfScreen(DefaultScreenOfDisplay(dpy)), &new_col);
XSetForeground(dpy, g, new_col.pixel);
// draw pixel in random spot
XDrawPoint(dpy, root, g, random_spot.x, random_spot.y);
// fill array position
fill_array[random_spot.y][random_spot.x] = 1;
// add to top of stack
stack_push(draw_stack, random_spot);
depth++;
}
// otherwise, there are no empty spots
// so pop the stack and continue looping
else
{
stack_pop(draw_stack);
depth--;
}
}
/* flush changes to screen and sleep */
XFlush(dpy);
usleep(15);
}
free (data);
free (fill_array);
stack_cleanup(draw_stack);
free (draw_stack);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment