C - SDL (Simple Directmedia Layer) - Creating a multicolored window

May you want to create a night club with the SDL library?

It is maybe possible.
With the code below of this tutorial, you can generate a different color every millisecond.

So, why waiting?
Let's dance!

#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <unistd.h>
#include <sys/time.h>
#include <SDL/SDL.h>

typedef struct s_sdl
{
SDL_Surface *screen;
SDL_Surface *rectangle;
SDL_Rect *position;
} t_sdl;

int creation_rect(t_sdl *sdl, int r1, int r2, int r3)
{
sdl->rectangle = NULL;
if (SDL_FillRect(sdl->screen, NULL, SDL_MapRGB(sdl->screen->format, r1, r2, r3)) == -1)
{

fprintf(stderr, "Error: %s\n", SDL_GetError());

return (1);

}

if (SDL_Flip(sdl->screen) == -1)

{

fprintf(stderr, "Error: %s\n", SDL_GetError());

return (1);

}

return (0);

}


int init(t_sdl *sdl)

{

int i = 0;


if (SDL_Init(SDL_INIT_EVERYTHING) == -1)

{

fprintf(stderr, "Error: %s\n", strerror(errno));

return (1);

}

if ((sdl->screen = SDL_SetVideoMode(800, 600, 32, SDL_HWSURFACE)) == NULL)

{

fprintf(stderr, "Error: %s", SDL_GetError());

return (1);

}

SDL_WM_SetCaption("Night club! :D", NULL);

if (SDL_FillRect(sdl->screen, NULL, SDL_MapRGB(sdl->screen->format, 255, 32, 45)) == -1)

{

fprintf(stderr, "Error: %s\n", SDL_GetError());

return (1);

}

if (SDL_Flip(sdl->screen) == -1)

{

fprintf(stderr, "Error: %s\n", SDL_GetError());

return (1);

}

while (i < 100)

{

creation_rect(sdl, my_random(), my_random(), my_random());

++i;

}

SDL_FreeSurface(sdl->rectangle);

return (0);

}


int my_random()

{

double seed;

int fp;

time_t t1;

struct timeval  tv;


gettimeofday(&tv, NULL);

seed = (tv.tv_sec) * 1000 + (tv.tv_usec) / 1000;

srand(seed);

usleep(10000);

return (rand() % 255);

}


int main ()

{

t_sdl sdl;


sdl.screen = NULL;

if(init(&sdl))

return (1);

return (0);

}
 
Of course, we need to run this:
 
gcc main.c -c ; gcc main.o -o go -lSDL ; ./go 
 
I hope you like colors. angel